ripplo 0.5.6 → 0.5.8

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 +244 -201
  2. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -1,26 +1,26 @@
1
1
  #!/usr/bin/env node
2
- var ua=Object.create;var yr=Object.defineProperty;var da=Object.getOwnPropertyDescriptor;var pa=Object.getOwnPropertyNames;var ma=Object.getPrototypeOf,fa=Object.prototype.hasOwnProperty;var ga=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ya=(e,t)=>{for(var r in t)yr(e,r,{get:t[r],enumerable:!0})},gr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of pa(t))!fa.call(e,o)&&o!==r&&yr(e,o,{get:()=>t[o],enumerable:!(n=da(t,o))||n.enumerable});return e},hr=(e,t,r)=>(gr(e,t,"default"),r&&gr(r,t,"default")),wr=(e,t,r)=>(r=e!=null?ua(ma(e)):{},gr(t||!e||!e.__esModule?yr(r,"default",{value:e,enumerable:!0}):r,e));var At=ga((Qb,go)=>{"use strict";var Il=(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=Ol(n),this._batchScheduleFn=Dl(n),this._cacheKeyFn=Ll(n),this._cacheMap=_l(n),this._batch=null,this.name=Ul(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=jl(this),i=this._cacheMap,s;if(i){s=this._cacheKeyFn(n);var a=i.get(s);if(a){var l=o.cacheHits||(o.cacheHits=[]);return new Promise(function(p){l.push(function(){p(a)})})}}o.keys.push(n);var c=new Promise(function(p,m){o.callbacks.push({resolve:p,reject:m})});return i&&i.set(s,c),c},t.loadMany=function(n){if(!fo(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})(),$l=typeof process=="object"&&typeof process.nextTick=="function"?function(e){Dr||(Dr=Promise.resolve()),Dr.then(function(){process.nextTick(e)})}:typeof setImmediate=="function"?function(e){setImmediate(e)}:function(e){setTimeout(e)},Dr;function jl(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(){Nl(e,r)}),r}function Nl(e,t){if(t.hasDispatched=!0,t.keys.length===0){_r(t);return}var r;try{r=e._batchLoadFn(t.keys)}catch(n){return Lr(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 Lr(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(!fo(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 Sa=Object.create;var yr=Object.defineProperty;var ka=Object.getOwnPropertyDescriptor;var Pa=Object.getOwnPropertyNames;var Ra=Object.getPrototypeOf,xa=Object.prototype.hasOwnProperty;var Ea=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ca=(e,t)=>{for(var r in t)yr(e,r,{get:t[r],enumerable:!0})},gr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Pa(t))!xa.call(e,o)&&o!==r&&yr(e,o,{get:()=>t[o],enumerable:!(n=ka(t,o))||n.enumerable});return e},hr=(e,t,r)=>(gr(e,t,"default"),r&&gr(r,t,"default")),wr=(e,t,r)=>(r=e!=null?Sa(Ra(e)):{},gr(t||!e||!e.__esModule?yr(r,"default",{value:e,enumerable:!0}):r,e));var At=Ea((mv,wo)=>{"use strict";var Ml=(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=Gl(n),this._cacheMap=Kl(n),this._batch=null,this.name=Jl(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=Hl(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(!ho(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){Or||(Or=Promise.resolve()),Or.then(function(){process.nextTick(e)})}:typeof setImmediate=="function"?function(e){setImmediate(e)}:function(e){setTimeout(e)},Or;function Hl(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(){Wl(e,r)}),r}function Wl(e,t){if(t.hasDispatched=!0,t.keys.length===0){_r(t);return}var r;try{r=e._batchLoadFn(t.keys)}catch(n){return Lr(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 Lr(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(!ho(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)));_r(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){Lr(e,t,n)})}function Lr(e,t,r){_r(t);for(var n=0;n<t.keys.length;n++)e.clear(t.keys[n]),t.callbacks[n].reject(r)}function _r(e){if(e.cacheHits)for(var t=0;t<e.cacheHits.length;t++)e.cacheHits[t]()}function Ol(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 Dl(e){var t=e&&e.batchScheduleFn;if(t===void 0)return $l;if(typeof t!="function")throw new TypeError("batchScheduleFn must be a function: "+t);return t}function Ll(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 _l(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 Ul(e){return e&&e.name?e.name:null}function fo(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))}go.exports=Il});import{execFileSync as ha}from"child_process";import wa from"fs";import Pt from"path";function br(e){let t=va(e);return t??_n(e)}function _n(e){let t=Pt.dirname(e);return ba(Pt.join(e,".ripplo"))?e:t===e?null:_n(t)}function ba(e){try{return wa.statSync(e).isDirectory()}catch{return!1}}function va(e){let t=Sa(["rev-parse","--show-toplevel"],e);if(t==null)return null;let r=t.trim();return r.length===0?null:Pt.isAbsolute(r)?r:Pt.resolve(e,r)}function Sa(e,t){try{return ha("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import qa from"path";import{AsyncLocalStorage as ka}from"async_hooks";import Ra from"path";var Pa=new ka;function Un(){let e=Pa.getStore();return e!=null?e.fixturesDir:Ra.join(process.cwd(),".ripplo","fixtures")}async function we(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 xa=5e3;async function Le({fn:e,label:t,page:r,timeoutMs:n}){let o=n??xa,i=await we(r.context().newCDPSession(r),o,`${t} (newCDPSession)`);try{return await we(e(i),o,t)}finally{await i.detach().catch(()=>{})}}async function J({awaitPromise:e,expression:t,label:r,page:n,timeoutMs:o}){return Le({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 Ea=Object.prototype.toString,Ue=Array.isArray||function(t){return Ea.call(t)==="[object Array]"};function Sr(e){return typeof e=="function"}function Ca(e){return Ue(e)?"array":typeof e}function vr(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Vn(e,t){return e!=null&&typeof e=="object"&&t in e}function Ta(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Aa=RegExp.prototype.test;function Ia(e,t){return Aa.call(e,t)}var $a=/\S/;function ja(e){return!Ia($a,e)}var Na={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function Oa(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return Na[r]})}var Da=/\s*/,La=/\s+/,Fn=/\s*=/,_a=/\s*\}/,Ua=/#|\^|\/|>|\{|&|=|!/;function Va(e,t){if(!e)return[];var r=!1,n=[],o=[],i=[],s=!1,a=!1,l="",c=0;function p(){if(s&&!a)for(;i.length;)delete o[i.pop()];else i=[];s=!1,a=!1}var m,b,x;function A(se){if(typeof se=="string"&&(se=se.split(La,2)),!Ue(se)||se.length!==2)throw new Error("Invalid tags: "+se);m=new RegExp(vr(se[0])+"\\s*"),b=new RegExp("\\s*"+vr(se[1])),x=new RegExp("\\s*"+vr("}"+se[1]))}A(t||re.tags);for(var g=new at(e),H,E,M,$e,De,I;!g.eos();){if(H=g.pos,M=g.scanUntil(m),M)for(var q=0,he=M.length;q<he;++q)$e=M.charAt(q),ja($e)?(i.push(o.length),l+=$e):(a=!0,r=!0,l+=" "),o.push(["text",$e,H,H+1]),H+=1,$e===`
9
- `&&(p(),l="",c=0,r=!1);if(!g.scan(m))break;if(s=!0,E=g.scan(Ua)||"name",g.scan(Da),E==="="?(M=g.scanUntil(Fn),g.scan(Fn),g.scanUntil(b)):E==="{"?(M=g.scanUntil(x),g.scan(_a),g.scanUntil(b),E="&"):M=g.scanUntil(b),!g.scan(b))throw new Error("Unclosed tag at "+g.pos);if(E==">"?De=[E,M,H,g.pos,l,c,r]:De=[E,M,H,g.pos],c++,o.push(De),E==="#"||E==="^")n.push(De);else if(E==="/"){if(I=n.pop(),!I)throw new Error('Unopened section "'+M+'" at '+H);if(I[1]!==M)throw new Error('Unclosed section "'+I[1]+'" at '+H)}else E==="name"||E==="{"||E==="&"?a=!0:E==="="&&A(M)}if(p(),I=n.pop(),I)throw new Error('Unclosed section "'+I[1]+'" at '+g.pos);return Ma(Fa(o))}function Fa(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 Ma(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 _e(e,t){this.view=e,this.cache={".":this.view},this.parent=t}_e.prototype.push=function(t){return new _e(t,this)};_e.prototype.lookup=function(t){var r=this.cache,n;if(r.hasOwnProperty(t))n=r[t];else{for(var o=this,i,s,a,l=!1;o;){if(t.indexOf(".")>0)for(i=o.view,s=t.split("."),a=0;i!=null&&a<s.length;)a===s.length-1&&(l=Vn(i,s[a])||Ta(i,s[a])),i=i[s[a++]];else i=o.view[t],l=Vn(o.view,t);if(l){n=i;break}o=o.parent}r[t]=n}return Sr(n)&&(n=n.call(this.view)),n};function K(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}K.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};K.prototype.parse=function(t,r){var n=this.templateCache,o=t+":"+(r||re.tags).join(":"),i=typeof n<"u",s=i?n.get(o):void 0;return s==null&&(s=Va(t,r),i&&n.set(o,s)),s};K.prototype.render=function(t,r,n,o){var i=this.getConfigTags(o),s=this.parse(t,i),a=r instanceof _e?r:new _e(r,void 0);return this.renderTokens(s,a,n,t,o)};K.prototype.renderTokens=function(t,r,n,o,i){for(var s="",a,l,c,p=0,m=t.length;p<m;++p)c=void 0,a=t[p],l=a[0],l==="#"?c=this.renderSection(a,r,n,o,i):l==="^"?c=this.renderInverted(a,r,n,o,i):l===">"?c=this.renderPartial(a,r,n,i):l==="&"?c=this.unescapedValue(a,r):l==="name"?c=this.escapedValue(a,r,i):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(s+=c);return s};K.prototype.renderSection=function(t,r,n,o,i){var s=this,a="",l=r.lookup(t[1]);function c(b){return s.render(b,r,n,i)}if(l){if(Ue(l))for(var p=0,m=l.length;p<m;++p)a+=this.renderTokens(t[4],r.push(l[p]),n,o,i);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(t[4],r.push(l),n,o,i);else if(Sr(l)){if(typeof o!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(r.view,o.slice(t[3],t[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(t[4],r,n,o,i);return a}};K.prototype.renderInverted=function(t,r,n,o,i){var s=r.lookup(t[1]);if(!s||Ue(s)&&s.length===0)return this.renderTokens(t[4],r,n,o,i)};K.prototype.indentPartial=function(t,r,n){for(var o=r.replace(/[^ \t]/g,""),i=t.split(`
8
+ `+String(n)));_r(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){Lr(e,t,n)})}function Lr(e,t,r){_r(t);for(var n=0;n<t.keys.length;n++)e.clear(t.keys[n]),t.callbacks[n].reject(r)}function _r(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 Bl;if(typeof t!="function")throw new TypeError("batchScheduleFn must be a function: "+t);return t}function Gl(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 Kl(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 Jl(e){return e&&e.name?e.name:null}function ho(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))}wo.exports=Ml});import{execFileSync as Ta}from"child_process";import Aa from"fs";import Rt from"path";function br(e){let t=$a(e);return t??Vn(e)}function Vn(e){let t=Rt.dirname(e);return Ia(Rt.join(e,".ripplo"))?e:t===e?null:Vn(t)}function Ia(e){try{return Aa.statSync(e).isDirectory()}catch{return!1}}function $a(e){let t=ja(["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 ja(e,t){try{return Ta("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import tl from"path";import{AsyncLocalStorage as Na}from"async_hooks";import Da from"path";var Oa=new Na;function Fn(){let e=Oa.getStore();return e!=null?e.fixturesDir:Da.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 Mn=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??Mn,r??"evaluateOnSession");if(i.exceptionDetails==null)return i.result.value}async function La({fn:e,label:t,page:r,timeoutMs:n}){let o=n??Mn,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 La({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 _a=Object.prototype.toString,Le=Array.isArray||function(t){return _a.call(t)==="[object Array]"};function Sr(e){return typeof e=="function"}function Ua(e){return Le(e)?"array":typeof e}function vr(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Bn(e,t){return e!=null&&typeof e=="object"&&t in e}function Va(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Fa=RegExp.prototype.test;function Ma(e,t){return Fa.call(e,t)}var Ba=/\S/;function Ha(e){return!Ma(Ba,e)}var Wa={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function qa(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return Wa[r]})}var za=/\s*/,Ga=/\s+/,Hn=/\s*=/,Ka=/\s*\}/,Ja=/#|\^|\/|>|\{|&|=|!/;function Xa(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 A(z){if(typeof z=="string"&&(z=z.split(Ga,2)),!Le(z)||z.length!==2)throw new Error("Invalid tags: "+z);m=new RegExp(vr(z[0])+"\\s*"),g=new RegExp("\\s*"+vr(z[1])),R=new RegExp("\\s*"+vr("}"+z[1]))}A(t||re.tags);for(var y=new at(e),B,E,H,Ie,De,pe;!y.eos();){if(B=y.pos,H=y.scanUntil(m),H)for(var O=0,J=H.length;O<J;++O)Ie=H.charAt(O),Ha(Ie)?(i.push(o.length),l+=Ie):(a=!0,r=!0,l+=" "),o.push(["text",Ie,B,B+1]),B+=1,Ie===`
9
+ `&&(u(),l="",c=0,r=!1);if(!y.scan(m))break;if(s=!0,E=y.scan(Ja)||"name",y.scan(za),E==="="?(H=y.scanUntil(Hn),y.scan(Hn),y.scanUntil(g)):E==="{"?(H=y.scanUntil(R),y.scan(Ka),y.scanUntil(g),E="&"):H=y.scanUntil(g),!y.scan(g))throw new Error("Unclosed tag at "+y.pos);if(E==">"?De=[E,H,B,y.pos,l,c,r]:De=[E,H,B,y.pos],c++,o.push(De),E==="#"||E==="^")n.push(De);else if(E==="/"){if(pe=n.pop(),!pe)throw new Error('Unopened section "'+H+'" at '+B);if(pe[1]!==H)throw new Error('Unclosed section "'+pe[1]+'" at '+B)}else E==="name"||E==="{"||E==="&"?a=!0:E==="="&&A(H)}if(u(),pe=n.pop(),pe)throw new Error('Unclosed section "'+pe[1]+'" at '+y.pos);return Qa(Ya(o))}function Ya(e){for(var t=[],r,n,o=0,i=e.length;o<i;++o)r=e[o],r&&(r[0]==="text"&&n&&n[0]==="text"?(n[1]+=r[1],n[3]=r[3]):(t.push(r),n=r));return t}function Qa(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=Bn(i,s[a])||Va(i,s[a])),i=i[s[a++]];else i=o.view[t],l=Bn(o.view,t);if(l){n=i;break}o=o.parent}r[t]=n}return Sr(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=Xa(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(Sr(l)){if(typeof o!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(r.view,o.slice(t[3],t[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(t[4],r,n,o,i);return a}};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
- `)};K.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),s=Sr(n)?n(t[1]):n[t[1]];if(s!=null){var a=t[6],l=t[5],c=t[4],p=s;l==0&&c&&(p=this.indentPartial(s,c,a));var m=this.parse(p,i);return this.renderTokens(m,r,n,p,o)}}};K.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};K.prototype.escapedValue=function(t,r,n){var o=this.getConfigEscape(n)||re.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&o===re.escape?String(i):o(i)};K.prototype.rawValue=function(t){return t[1]};K.prototype.getConfigTags=function(t){return Ue(t)?t:t&&typeof t=="object"?t.tags:void 0};K.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!Ue(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 K;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 "'+Ca(t)+'" was given as the first argument for mustache#render(template, view, partials)');return st.render(t,r,n,o)};re.escape=Oa;re.Scanner=at;re.Context=_e;re.Writer=K;var Mn=re;function kr({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Ha({def:r,name:t})]))}var Ba={boolean:!1,number:0,string:""};function Ha({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??Ba[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 Mn.render(e,t,{},{escape:r=>r})}function Rr({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 Ve({name:e,store:t,value:r}){return{...t,[e]:r}}function V({locator:e,page:t,variables:r}){switch(e.by){case"testId":return t.getByTestId(Bn(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:Bn(e.name,r)})}}function Bn(e,t){return t==null?e:Ct({raw:e,variables:t})}async function Hn({node:e,page:t,timeout:r}){await V({locator:e.source,page:t,variables:void 0}).dragTo(V({locator:e.target,page:t,variables:void 0}),{timeout:r})}async function qn({node:e,page:t,timeout:r}){await V({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function Wn({node:e,page:t,variables:r}){return t.once("dialog",async n=>{e.action==="accept"?await n.accept(e.promptText??void 0):await n.dismiss()}),{variables:r}}async function zn({node:e,page:t,variables:r}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let o=Y({ref:e.value,variables:r}),i=JSON.stringify(o);return await J({awaitPromise:!0,expression:`navigator.clipboard.writeText(${i})`,label:"clipboard.writeText",page:t,timeoutMs:void 0}),{variables:r}}if(e.variable==null)throw new Error("clipboard read requires a variable name to store the result");let n=await J({awaitPromise:!0,expression:"navigator.clipboard.readText()",label:"clipboard.readText",page:t,timeoutMs:void 0})??"";return{variables:Ve({name:e.variable,store:r,value:n})}}async function Gn({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function Pr({node:e,page:t,timeout:r,variables:n}){switch(e.type){case"click":return await V({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 za({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 J({awaitPromise:!0,expression:"new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })",label:"goto raf-settle",page:t,timeoutMs:void 0}),{variables:n}}case"fill":return Ka({node:e,page:t,timeout:r,variables:n});case"select":return Ja({node:e,page:t,timeout:r,variables:n});case"type":return Ya({node:e,page:t,timeout:r,variables:n});case"press":return await Ga({node:e,page:t,timeout:r}),{variables:n};case"drag":return await Hn({node:e,page:t,timeout:r}),{variables:n};case"upload":return Xa({node:e,page:t,timeout:r,variables:n});case"extractText":return Za({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=Et({ref:e.value,variables:n});return{variables:Ve({name:e.variable,store:n,value:o})}}case"fail":throw new Error(e.message);case"setViewport":return await t.setViewportSize({height:e.height,width:e.width}),{variables:n};case"handleDialog":return Wn({node:e,page:t,variables:n});case"clipboard":return zn({node:e,page:t,variables:n});case"setPermission":return await Gn({node:e,page:t}),{variables:n}}}var Wa={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function za({node:e,page:t,timeout:r,variables:n}){return await V({locator:e.locator,page:t,variables:n})[Wa[e.type]]({timeout:r}),{variables:n}}async function Ga({node:e,page:t,timeout:r}){e.locator==null?await t.keyboard.press(e.key):await V({locator:e.locator,page:t,variables:void 0}).press(e.key,{timeout:r})}async function Ka({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await V({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function Ja({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await V({locator:e.locator,page:t,variables:n}).selectOption(o,{timeout:r}),{variables:n}}async function Ya({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await V({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function Xa({node:e,page:t,timeout:r,variables:n}){let o=e.files.map(i=>Qa(i));return await V({locator:e.locator,page:t,variables:n}).setInputFiles(o,{timeout:r}),{variables:n}}function Qa(e){return qa.join(Un(),e)}async function Za({node:e,page:t,timeout:r,variables:n}){let o=await V({locator:e.locator,page:t,variables:n}).textContent({timeout:r});if(o==null)throw new Error("extractText: element had no text content");return{variables:Ve({name:e.variable,store:n,value:o})}}var z={};ya(z,{default:()=>el});hr(z,vb);import*as vb from"playwright/test";import{default as el}from"playwright/test";async function xr({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 Er({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 Kn({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 Cr({expected:e,locator:t,operator:r,timeout:n}){await z.expect.poll(async()=>io({actual:await t.count(),expected:e,operator:r}),{timeout:n}).toBe(!0).catch(()=>{});let o=await t.count();return oo({actual:o,expected:e,label:"Count",operator:r})}async function Tr({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 Ar({locator:e,timeout:t}){return be({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,z.expect)(e).toBeVisible({timeout:t})})}async function Ir({locator:e,timeout:t}){return be({description:"Element is not visible",failureDetail:"Element still visible",run:()=>(0,z.expect)(e).toBeHidden({timeout:t})})}async function Jn({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 Yn({locator:e,timeout:t}){return be({description:"Element is enabled",failureDetail:"Element is disabled or not found",run:()=>(0,z.expect)(e).toBeEnabled({timeout:t})})}async function Xn({locator:e,timeout:t}){return be({description:"Element is disabled",failureDetail:"Element is enabled or not found",run:()=>(0,z.expect)(e).toBeDisabled({timeout:t})})}async function Qn({locator:e,timeout:t}){return be({description:"Element is checked",failureDetail:"Element is not checked",run:()=>(0,z.expect)(e).toBeChecked({timeout:t})})}async function Zn({locator:e,timeout:t}){return be({description:"Element is not checked",failureDetail:"Element is checked",run:()=>(0,z.expect)(e).not.toBeChecked({timeout:t})})}async function eo({locator:e,timeout:t}){return be({description:"Element is focused",failureDetail:"Element is not focused",run:()=>(0,z.expect)(e).toBeFocused({timeout:t})})}async function to({locator:e,timeout:t}){return be({description:"Element is not focused",failureDetail:"Element is focused",run:()=>(0,z.expect)(e).not.toBeFocused({timeout:t})})}async function be({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 z.expect.poll(async()=>{let o=await r().catch(()=>"");return no({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 ro({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: ${tl(s)}`,status:"failed"}}}function tl(e){let t=e.indexOf(`
12
- `);return t===-1?e:e.slice(0,t)}function ro(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=no(e),n=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:n,status:r?"passed":"failed"}}function no({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 oo(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=io(e),n=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:n,status:r?"passed":"failed"}}function io({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 nl}from"child_process";import{createRequire as ol}from"module";import so from"fs";import ao from"path";import{chromium as lo}from"playwright";import xb from"fs";import Cb from"path";import rl from"pino";var f=rl({level:process.env.LOG_LEVEL??"info",transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}});async function Fe({headed:e}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";try{return await lo.launch({headless:!e})}catch(t){throw il(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=Sr(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 "'+Ua(t)+'" was given as the first argument for mustache#render(template, view, partials)');return st.render(t,r,n,o)};re.escape=qa;re.Scanner=at;re.Context=Oe;re.Writer=X;var Wn=re;function kr({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,el({def:r,name:t})]))}var Za={boolean:!1,number:0,string:""};function el({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??Za[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 Wn.render(e,t,{},{escape:r=>r})}function Pr({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(qn(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:qn(e.name,r)})}}function qn(e,t){return t==null?e:Ct({raw:e,variables:t})}async function zn({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 Gn({node:e,page:t,timeout:r}){await F({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function Kn({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 Jn({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 Xn({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function Rr({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 nl({node:e,page:t,timeout:r,variables:n});case"rightClick":return await Gn({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 il({node:e,page:t,timeout:r,variables:n});case"select":return sl({node:e,page:t,timeout:r,variables:n});case"type":return al({node:e,page:t,timeout:r,variables:n});case"press":return await ol({node:e,page:t,timeout:r}),{variables:n};case"drag":return await zn({node:e,page:t,timeout:r}),{variables:n};case"upload":return ll({node:e,page:t,timeout:r,variables:n});case"extractText":return ul({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 Kn({node:e,page:t,variables:n});case"clipboard":return Jn({node:e,page:t,variables:n});case"setPermission":return await Xn({node:e,page:t}),{variables:n}}}var rl={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function nl({node:e,page:t,timeout:r,variables:n}){return await F({locator:e.locator,page:t,variables:n})[rl[e.type]]({timeout:r}),{variables:n}}async function ol({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 il({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 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}).selectOption(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}).pressSequentially(o,{timeout:r}),{variables:n}}async function ll({node:e,page:t,timeout:r,variables:n}){let o=e.files.map(i=>cl(i));return await F({locator:e.locator,page:t,variables:n}).setInputFiles(o,{timeout:r}),{variables:n}}function cl(e){return tl.join(Fn(),e)}async function ul({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={};Ca(G,{default:()=>dl});hr(G,Ob);import*as Ob from"playwright/test";import{default as dl}from"playwright/test";async function xr({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 Er({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 Yn({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 Cr({expected:e,locator:t,operator:r,timeout:n}){await G.expect.poll(async()=>lo({actual:await t.count(),expected:e,operator:r}),{timeout:n}).toBe(!0).catch(()=>{});let o=await t.count();return ao({actual:o,expected:e,label:"Count",operator:r})}async function Tr({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 Ar({locator:e,timeout:t}){return we({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,G.expect)(e).toBeVisible({timeout:t})})}async function Ir({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 Qn({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 Zn({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 eo({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 to({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 ro({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 no({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 oo({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 so({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 io({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: ${pl(s)}`,status:"failed"}}}function pl(e){let t=e.indexOf(`
12
+ `);return t===-1?e:e.slice(0,t)}function io(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=so(e),n=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:n,status:r?"passed":"failed"}}function so({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 ao(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=lo(e),n=r?void 0:`Got: ${String(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==="greaterThan"?e>t:r==="greaterThanOrEqual"?e>=t:r==="lessThan"?e<t:e<=t}import{execFile as fl}from"child_process";import{createRequire as gl}from"module";import co from"fs";import uo from"path";import{chromium as po}from"playwright";import Fb from"fs";import Bb from"path";import ml from"pino";var f=ml({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 po.launch({headless:!e})}catch(t){throw yl(t)?new Error(`Playwright browsers are not installed. Run:
13
13
 
14
14
  npx playwright install chromium
15
- `):t}}async function $r(){let e=lo.executablePath();if(so.existsSync(e))return;f.info("Chromium not found. Installing via Playwright...");let t=ol(import.meta.url),r=ao.dirname(t.resolve("playwright/package.json")),n=ao.join(r,"cli.js");if(await new Promise((o,i)=>{nl(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!so.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
15
+ `):t}}async function $r(){let e=po.executablePath();if(co.existsSync(e))return;f.info("Chromium not found. Installing via Playwright...");let t=gl(import.meta.url),r=uo.dirname(t.resolve("playwright/package.json")),n=uo.join(r,"cli.js");if(await new Promise((o,i)=>{fl(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!co.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 il(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{readdir as dl,rm as pl,stat as ml}from"fs/promises";import Mb from"os";import po from"path";import{graphql as fl}from"gql.tada";import{print as sl}from"graphql";var al=15e3,Me=class extends Error{errors;constructor(t){super(t.map(r=>r.message).join(", ")),this.name="GqlRequestError",this.errors=t}};async function y(e){let t=sl(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(al)})}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 ll({res:o,url:n});if(!cl(i))throw new Error("Invalid GraphQL response");if(ul(i))throw new Me(i.errors);if(i.data==null)throw new Error("No data returned from server");return i.data}async function ll({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 ul(e){return Array.isArray(e.errors)&&e.errors.length>0}var co=po.join(process.cwd(),".ripplo","debug"),uo=360*60*1e3,zb=fl(`
18
+ `);f.info("\u2713 Chromium installed")}function yl(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{readdir as kl,rm as Pl,stat as Rl}from"fs/promises";import rv from"os";import go from"path";import{graphql as xl}from"gql.tada";import{print as hl}from"graphql";var wl=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=hl(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(wl)})}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 bl({res:o,url:n});if(!vl(i))throw new Error("Invalid GraphQL response");if(Sl(i))throw new Ve(i.errors);if(i.data==null)throw new Error("No data returned from server");return i.data}async function bl({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 vl(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function Sl(e){return Array.isArray(e.errors)&&e.errors.length>0}var mo=go.join(process.cwd(),".ripplo","debug"),fo=360*60*1e3,av=xl(`
19
19
  mutation RevokeCurrentCliToken {
20
20
  revokeCurrentCliToken
21
21
  }
22
- `);async function Tt({maxRuns:e}){try{let r=(await dl(co,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let p=po.join(co,c.name),m=await ml(p);return{dirPath:p,mtime:m.mtimeMs}})),i=o.filter(c=>n-c.mtime>uo),a=o.filter(c=>n-c.mtime<=uo).toSorted((c,p)=>p.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>pl(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 gl=15e3,yl=2,hl=250,wl=3e4,jr=new Map;function Nr({appUrl:e}){let t=Date.now(),r=jr.get(e);if(r!=null&&r.expiresAt>t)return r.promise;let n=bl(e).catch(o=>{throw jr.delete(e),o});return jr.set(e,{expiresAt:t+wl,promise:n}),n}async function bl(e){let t=null,r=0;for(;r<=yl;){r>0&&await Sl(hl);let o=await vl(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 vl(e,t){let r=performance.now();try{return await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(gl)}),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 Sl(e){return new Promise(t=>setTimeout(t,e))}import{Agent as kl,RetryAgent as Rl,setGlobalDispatcher as Pl}from"undici";var xl=1500,El=4e3,Cl=3,Tl=50,Al=100,mo=!1;function Or(){if(mo)return;mo=!0;let e=new kl({connections:Al,keepAliveMaxTimeout:El,keepAliveTimeout:xl}),t=new Rl(e,{errorCodes:["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","UND_ERR_REQ_CONTENT_LENGTH_MISMATCH","UND_ERR_SOCKET"],maxRetries:Cl,methods:["GET","POST","HEAD","OPTIONS","PUT","DELETE"],minTimeout:Tl});Pl(t)}var Fo=wr(At(),1);import{z as md}from"zod";import{z as It}from"zod";var Vl=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 yo({legacy:void 0,migrators:[],name:e,schemas:[]})}function yo(e){return{initial:t=>Ur(t,{...e,schemas:[t]}),legacy:t=>yo({...e,legacy:t})}}function Ur(e,t){return{build:()=>Fl(e,t),legacy:r=>Ur(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Ur(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function Fl(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Ml(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Ml(e,t,r){let{data:n,version:o}=Bl(t,r),i=ho(t,n,o);return e.parse(i)}function Bl(e,t){let r=Vl.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 ho(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 ho(e,s(i),r+1)}import{z as So}from"zod";import{z as Be}from"zod";var Vr=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.");import{z as u}from"zod";import{z as ve}from"zod";var Hl=ve.object({by:ve.literal("testId"),value:ve.string().min(1)}),ql=ve.object({by:ve.literal("role"),name:ve.string().optional(),role:ve.string().min(1)}),R=ve.discriminatedUnion("by",[Hl,ql]);import{z as wo}from"zod";var Se=wo.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Ot=wo.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as N}from"zod";var Wl=N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),Dt=N.object({name:N.string().min(1),type:N.literal("variable")}),Lt=N.discriminatedUnion("type",[Wl,Dt]),Q=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.string()}),Dt]),_t=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.number().int().nonnegative()}),Dt]),Fr=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),Dt]);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:u.string().min(1).max(200),label:u.string().max(500).optional(),next:u.string().max(200).optional(),uiOnly:u.boolean().optional()},bo=500,zl=u.object({...v,type:u.literal("goto"),url:Q}),Gl=u.object({...v,locator:R,modifier:u.enum(["Alt","Control","Meta","Shift"]).optional(),type:u.literal("click")}),Kl=u.object({...v,locator:R,type:u.literal("fill"),value:Q}),Jl=u.object({...v,locator:R,type:u.literal("select"),value:Q}),Yl=u.object({...v,locator:R,type:u.literal("hover")}),Xl=u.object({...v,key:u.string().min(1),locator:R.optional(),type:u.literal("press")}),Ql=u.object({...v,locator:R,type:u.literal("check")}),Zl=u.object({...v,locator:R,type:u.literal("uncheck")}),ec=u.object({...v,height:u.number().int().positive(),type:u.literal("setViewport"),width:u.number().int().positive()}),tc=u.object({...v,message:u.string().min(1),type:u.literal("fail")}),rc=u.object({...v,type:u.literal("setVariable"),value:Lt,variable:u.string().min(1)}),nc=u.object({...v,locator:R,type:u.literal("extractText"),variable:u.string().min(1)}),oc=u.object({...v,files:u.array(u.string()).min(1),locator:R,type:u.literal("upload")}),ic=u.object({...v,locator:R,type:u.literal("dblclick")}),sc=u.object({...v,source:R,target:R,type:u.literal("drag")}),ac=u.object({...v,locator:R,type:u.literal("scrollIntoView")}),lc=u.object({...v,locator:R,type:u.literal("type"),value:Q}),cc=u.object({...v,locator:R,type:u.literal("focus")}),uc=u.object({...v,locator:R,type:u.literal("clear")}),dc=u.object({...v,locator:R,type:u.literal("rightClick")}),pc=u.object({...v,action:u.enum(["accept","dismiss"]),promptText:u.string().optional(),type:u.literal("handleDialog")}),mc=u.object({...v,action:u.enum(["read","write"]),type:u.literal("clipboard"),value:Q.optional(),variable:u.string().min(1).optional()}),fc=u.object({...v,permission:u.string().min(1),state:u.enum(["granted","prompt"]),type:u.literal("setPermission")}),gc=u.object({...v,locator:R,type:u.literal("assertVisible")}),yc=u.object({...v,locator:R,type:u.literal("assertNotVisible")}),hc=u.object({...v,expected:Q,locator:R,operator:Se,type:u.literal("assertText")}),wc=u.object({...v,expected:Q,operator:Se,type:u.literal("assertUrl")}),bc=u.object({...v,expected:_t,locator:R,operator:Ot,type:u.literal("assertCount")}),vc=u.object({...v,expected:Q,locator:R,operator:Se,type:u.literal("assertValue")}),Sc=u.object({...v,attribute:u.string().min(1),expected:Q,locator:R,operator:Se,type:u.literal("assertAttribute")}),kc=u.object({...v,locator:R,type:u.literal("assertEnabled")}),Rc=u.object({...v,locator:R,type:u.literal("assertDisabled")}),Pc=u.object({...v,expected:Q,operator:Se,type:u.literal("assertTitle")}),xc=u.object({...v,locator:R,type:u.literal("assertChecked")}),Ec=u.object({...v,locator:R,type:u.literal("assertNotChecked")}),Cc=u.object({...v,locator:R,type:u.literal("assertFocused")}),Tc=u.object({...v,locator:R,type:u.literal("assertNotFocused")}),Ac=u.object({...v,budget:u.enum(["fast","slow","async"]),observer:u.string().min(1).max(200),params:u.record(u.string().max(200),Fr),type:u.literal("assertObserver")}),vo=u.discriminatedUnion("type",[zl,Gl,Kl,Jl,Yl,Xl,Ql,Zl,gc,yc,hc,wc,bc,vc,Sc,kc,Rc,ec,tc,rc,nc,oc,ic,sc,ac,lc,cc,uc,dc,pc,mc,fc,Pc,xc,Ec,Cc,Tc,Ac]),Vt=u.object({entryNode:u.string().min(1).max(200),nodes:u.record(u.string().max(200),vo).refine(e=>Object.keys(e).length<=bo,`Workflow has more than ${String(bo)} nodes`),uiOnly:u.boolean().optional(),variableNamespaces:u.record(u.string().max(200),u.string().max(500)).optional(),variables:u.record(u.string().max(200),Ut).optional()});var Ic=So.record(So.string().max(200),Vr),$c={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},jc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Mr=Nt("workflow-spec").legacy($c).initial(Vt).build(),Nc=Nt("precondition-map").legacy(jc).initial(Ic).build();import{z as Br}from"zod";var ko=["fast","slow","async"],Oc=Br.object({budget:Br.enum(ko).describe("Polling budget tier: fast | slow | async"),description:Br.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 Mo,readFragment as fd}from"gql.tada";function Po(){let e,t=!1;function r(o){e=o,t&&Ro(o)}async function n(){t||(t=!0,e!=null&&await Ro(e))}return{attachContext:r,fire:n,fired:()=>t}}async function Ro(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 Hr,writeFile as W}from"fs/promises";import F from"path";import{z as ne}from"zod";async function Eo({context:e,page:t,runId:r,stepIndex:n,stepResult:o}){try{let i=F.join(process.cwd(),".ripplo","debug",r,"steps",String(n));await Hr(i,{recursive:!0});let s={assertions:o.assertions,detail:o.detail,duration:o.duration,nodeId:o.nodeId,nodeType:o.nodeType,snapshotTimestamp:o.snapshotTimestamp,status:o.status,stepIndex:o.stepIndex,title:o.title,url:o.url};await Promise.all([W(F.join(i,"info.json"),JSON.stringify(s,null,2)),Lc(Uc({context:e,page:t,stepDir:i}),Dc,`capturePageState step ${String(n)}`)])}catch(i){let s=i instanceof Error?i.message:String(i);f.warn("Failed to write step debug data for step %d: %s",n,s)}}var Dc=15e3;async function Lc(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 _c(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 Uc({context:e,page:t,stepDir:r}){let[n,o,i,s,a]=await Promise.all([Mc(t),qc(t),Yc({context:e,page:t}),Kc(t),Fc(t)]);await Promise.all([W(F.join(r,"dom.html"),_c(n)),W(F.join(r,"accessibility-tree.full.json"),JSON.stringify(o,null,2)),W(F.join(r,"accessibility-tree.json"),Wc(o)),W(F.join(r,"storage.json"),JSON.stringify(i,null,2)),W(F.join(r,"rrweb-elements.ndjson"),a),W(F.join(r,"screenshot.png"),s)])}var Vc=`
22
+ `);async function Tt({maxRuns:e}){try{let r=(await kl(mo,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let u=go.join(mo,c.name),m=await Rl(u);return{dirPath:u,mtime:m.mtimeMs}})),i=o.filter(c=>n-c.mtime>fo),a=o.filter(c=>n-c.mtime<=fo).toSorted((c,u)=>u.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>Pl(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 El=15e3,Cl=2,Tl=250,Al=3e4,jr=new Map;function Nr({appUrl:e}){let t=Date.now(),r=jr.get(e);if(r!=null&&r.expiresAt>t)return r.promise;let n=Il(e).catch(o=>{throw jr.delete(e),o});return jr.set(e,{expiresAt:t+Al,promise:n}),n}async function Il(e){let t=null,r=0;for(;r<=Cl;){r>0&&await jl(Tl);let o=await $l(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 $l(e,t){let r=performance.now();try{return await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(El)}),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 jl(e){return new Promise(t=>setTimeout(t,e))}import{Agent as Nl,RetryAgent as Dl,setGlobalDispatcher as Ol}from"undici";var Ll=1500,_l=4e3,Ul=3,Vl=50,Fl=100,yo=!1;function Dr(){if(yo)return;yo=!0;let e=new Nl({connections:Fl,keepAliveMaxTimeout:_l,keepAliveTimeout:Ll}),t=new Dl(e,{errorCodes:["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","UND_ERR_REQ_CONTENT_LENGTH_MISMATCH","UND_ERR_SOCKET"],maxRetries:Ul,methods:["GET","POST","HEAD","OPTIONS","PUT","DELETE"],minTimeout:Vl});Ol(t)}var zo=wr(At(),1);import{z as xd}from"zod";import{z as It}from"zod";var Xl=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 bo({legacy:void 0,migrators:[],name:e,schemas:[]})}function bo(e){return{initial:t=>Ur(t,{...e,schemas:[t]}),legacy:t=>bo({...e,legacy:t})}}function Ur(e,t){return{build:()=>Yl(e,t),legacy:r=>Ur(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Ur(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function Yl(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Ql(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Ql(e,t,r){let{data:n,version:o}=Zl(t,r),i=vo(t,n,o);return e.parse(i)}function Zl(e,t){let r=Xl.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 vo(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 vo(e,s(i),r+1)}import{z as Ro}from"zod";import{z as Fe}from"zod";var Vr=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 ec=be.object({by:be.literal("testId"),value:be.string().min(1)}),tc=be.object({by:be.literal("role"),name:be.string().optional(),role:be.string().min(1)}),x=be.discriminatedUnion("by",[ec,tc]);import{z as So}from"zod";var ve=So.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Dt=So.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as N}from"zod";var rc=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",[rc,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]),Fr=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()},ko=500,nc=d.object({...v,type:d.literal("goto"),url:Q}),oc=d.object({...v,locator:x,modifier:d.enum(["Alt","Control","Meta","Shift"]).optional(),type:d.literal("click")}),ic=d.object({...v,locator:x,type:d.literal("fill"),value:Q}),sc=d.object({...v,locator:x,type:d.literal("select"),value:Q}),ac=d.object({...v,locator:x,type:d.literal("hover")}),lc=d.object({...v,key:d.string().min(1),locator:x.optional(),type:d.literal("press")}),cc=d.object({...v,locator:x,type:d.literal("check")}),uc=d.object({...v,locator:x,type:d.literal("uncheck")}),dc=d.object({...v,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),pc=d.object({...v,message:d.string().min(1),type:d.literal("fail")}),mc=d.object({...v,type:d.literal("setVariable"),value:Lt,variable:d.string().min(1)}),fc=d.object({...v,locator:x,type:d.literal("extractText"),variable:d.string().min(1)}),gc=d.object({...v,files:d.array(d.string()).min(1),locator:x,type:d.literal("upload")}),yc=d.object({...v,locator:x,type:d.literal("dblclick")}),hc=d.object({...v,source:x,target:x,type:d.literal("drag")}),wc=d.object({...v,locator:x,type:d.literal("scrollIntoView")}),bc=d.object({...v,locator:x,type:d.literal("type"),value:Q}),vc=d.object({...v,locator:x,type:d.literal("focus")}),Sc=d.object({...v,locator:x,type:d.literal("clear")}),kc=d.object({...v,locator:x,type:d.literal("rightClick")}),Pc=d.object({...v,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),Rc=d.object({...v,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:Q.optional(),variable:d.string().min(1).optional()}),xc=d.object({...v,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),Ec=d.object({...v,locator:x,type:d.literal("assertVisible")}),Cc=d.object({...v,locator:x,type:d.literal("assertNotVisible")}),Tc=d.object({...v,expected:Q,locator:x,operator:ve,type:d.literal("assertText")}),Ac=d.object({...v,expected:Q,operator:ve,type:d.literal("assertUrl")}),Ic=d.object({...v,expected:_t,locator:x,operator:Dt,type:d.literal("assertCount")}),$c=d.object({...v,expected:Q,locator:x,operator:ve,type:d.literal("assertValue")}),jc=d.object({...v,attribute:d.string().min(1),expected:Q,locator:x,operator:ve,type:d.literal("assertAttribute")}),Nc=d.object({...v,locator:x,type:d.literal("assertEnabled")}),Dc=d.object({...v,locator:x,type:d.literal("assertDisabled")}),Oc=d.object({...v,expected:Q,operator:ve,type:d.literal("assertTitle")}),Lc=d.object({...v,locator:x,type:d.literal("assertChecked")}),_c=d.object({...v,locator:x,type:d.literal("assertNotChecked")}),Uc=d.object({...v,locator:x,type:d.literal("assertFocused")}),Vc=d.object({...v,locator:x,type:d.literal("assertNotFocused")}),Fc=d.object({...v,budget:d.enum(["fast","slow","async"]),observer:d.string().min(1).max(200),params:d.record(d.string().max(200),Fr),type:d.literal("assertObserver")}),Po=d.discriminatedUnion("type",[nc,oc,ic,sc,ac,lc,cc,uc,Ec,Cc,Tc,Ac,Ic,$c,jc,Nc,Dc,dc,pc,mc,fc,gc,yc,hc,wc,bc,vc,Sc,kc,Pc,Rc,xc,Oc,Lc,_c,Uc,Vc,Fc]),Vt=d.object({entryNode:d.string().min(1).max(200),nodes:d.record(d.string().max(200),Po).refine(e=>Object.keys(e).length<=ko,`Workflow has more than ${String(ko)} 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 Mc=Ro.record(Ro.string().max(200),Vr),Bc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},Hc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Mr=Nt("workflow-spec").legacy(Bc).initial(Vt).build(),Wc=Nt("precondition-map").legacy(Hc).initial(Mc).build();import{z as Br}from"zod";var xo=["fast","slow","async"],qc=Br.object({budget:Br.enum(xo).describe("Polling budget tier: fast | slow | async"),description:Br.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 Go,readFragment as Ed}from"gql.tada";function Co(){let e,t=!1;function r(o){e=o,t&&Eo(o)}async function n(){t||(t=!0,e!=null&&await Eo(e))}return{attachContext:r,fire:n,fired:()=>t}}async function Eo(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 Hr,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 Ao({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 Hr(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)),Kc(Xc({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,Gc=50;async function Kc(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 Jc(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 Xc({cdpSession:e,context:t,stepDir:r}){let[n,o,i,s,a]=await Promise.all([j({label:"captureDom",fn:()=>Zc(e)}),j({label:"captureAxTree",fn:()=>ru(e)}),j({label:"captureStorage",fn:()=>lu({cdpSession:e,context:t})}),j({label:"captureScreenshot",fn:()=>su(e)}),j({label:"captureRrwebElements",fn:()=>Qc(e)})]);await j({label:"writeStepFiles",fn:()=>Promise.all([q(M.join(r,"dom.html"),Jc(n)),q(M.join(r,"accessibility-tree.full.json"),JSON.stringify(o)),q(M.join(r,"accessibility-tree.json"),nu(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 Yc=`
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 Fc(e){return await J({awaitPromise:!1,expression:Vc,label:"captureRrwebElements",page:e,timeoutMs:void 0})??""}async function Mc(e){return await J({awaitPromise:!1,expression:"document.documentElement.outerHTML",label:"captureDom",page:e,timeoutMs:void 0})??"(unable to capture DOM)"}var Mt=ne.object({value:ne.unknown()}).partial(),Bc=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(),Hc=ne.object({nodes:ne.array(Bc)});async function qc(e){return Le({label:"captureAxTree",page:e,timeoutMs:void 0,fn:async t=>{let r=await t.send("Accessibility.getFullAXTree"),n=Hc.safeParse(r);return n.success?n.data:{nodes:[]}}})}function Wc(e){return e.nodes.filter(t=>t.ignored!==!0).map(t=>zc(t)).toSorted(Gc).map(t=>JSON.stringify(t)).join(`
88
- `)}function zc(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 Gc(e,t){return xo(e.nodeId)-xo(t.nodeId)}function xo(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 Kc(e){return Le({label:"captureScreenshot",page:e,timeoutMs:void 0,fn:async t=>{let r=await t.send("Page.captureScreenshot",{format:"png"});return Buffer.from(r.data,"base64")}})}var Jc=`(() => {
87
+ `;async function Qc(e){return await se({awaitPromise:!1,expression:Yc,label:"captureRrwebElements",session:e,timeoutMs:void 0})??""}async function Zc(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(),eu=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(),tu=ne.object({nodes:ne.array(eu)});async function ru(e){let t=await e.send("Accessibility.getFullAXTree"),r=tu.safeParse(t);return r.success?r.data:{nodes:[]}}function nu(e){return e.nodes.filter(t=>t.ignored!==!0).map(t=>ou(t)).toSorted(iu).map(t=>JSON.stringify(t)).join(`
88
+ `)}function ou(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 iu(e,t){return To(e.nodeId)-To(t.nodeId)}function To(e){if(e==null)return Number.MAX_SAFE_INTEGER;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER}async function su(e){let t=await e.send("Page.captureScreenshot",{format:"png",optimizeForSpeed:!0});return Buffer.from(t.data,"base64")}var au=`(() => {
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 Yc({context:e,page:t}){let[r,n]=await Promise.all([J({awaitPromise:!1,expression:Jc,label:"captureStorage",page:t,timeoutMs:void 0}),e.cookies().catch(()=>[])]);return{cookies:n,localStorage:r?.localStorage??{},sessionStorage:r?.sessionStorage??{}}}async function Co({pageEvents:e,runId:t,steps:r,summary:n}){try{let o=F.join(process.cwd(),".ripplo","debug",t);await Hr(o,{recursive:!0});let i=e.capturePerf(),s=e.drain();await Promise.all([W(F.join(o,"summary.txt"),tu({steps:r,summary:n})),W(F.join(o,"manifest.md"),ru({steps:r,summary:n})),W(F.join(o,"console.log"),Xc(e.consoleEntries)),W(F.join(o,"page-errors.log"),Qc(e.pageErrors)),W(F.join(o,"events.jsonl"),eu(e.lifecycle)),s.then(()=>W(F.join(o,"network.jsonl"),Zc(e.network))),i.then(a=>W(F.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 Xc(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 Qc(e){return e.map(t=>{let r=t.stack==null?"":`
98
+ })()`;async function lu({cdpSession:e,context:t}){let[r,n]=await Promise.all([se({awaitPromise:!1,expression:au,label:"captureStorage",session:e,timeoutMs:void 0}),t.cookies().catch(()=>[])]);return{cookies:n,localStorage:r?.localStorage??{},sessionStorage:r?.sessionStorage??{}}}async function Io({pageEvents:e,runId:t,steps:r,summary:n}){try{let o=M.join(process.cwd(),".ripplo","debug",t);await Hr(o,{recursive:!0});let i=e.capturePerf(),s=Promise.race([e.drain(),new Promise(a=>setTimeout(a,Gc))]);await Promise.all([q(M.join(o,"summary.txt"),mu({steps:r,summary:n})),q(M.join(o,"manifest.md"),fu({steps:r,summary:n})),q(M.join(o,"console.log"),cu(e.consoleEntries)),q(M.join(o,"page-errors.log"),uu(e.pageErrors)),q(M.join(o,"events.jsonl"),pu(e.lifecycle)),s.then(()=>q(M.join(o,"network.jsonl"),du(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 cu(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 uu(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 Zc(e){return e.map(t=>JSON.stringify(t)).join(`
103
- `)}function eu(e){return e.map(t=>JSON.stringify(t)).join(`
104
- `)}function tu({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 ru({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 To({error:e,runId:t,stack:r,workflowName:n}){try{let o=F.join(process.cwd(),".ripplo","debug",t);await Hr(o,{recursive:!0});let i=r==null?e:`${e}
102
+ `)}function du(e){return e.map(t=>JSON.stringify(t)).join(`
103
+ `)}function pu(e){return e.map(t=>JSON.stringify(t)).join(`
104
+ `)}function mu({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 fu({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 $o({error:e,runId:t,stack:r,workflowName:n}){try{let o=M.join(process.cwd(),".ripplo","debug",t);await Hr(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([W(F.join(o,"error.txt"),i),W(F.join(o,"summary.txt"),s),W(F.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 nu}from"fs";import{createRequire as ou}from"module";import Ao from"path";import{gzipSync as iu}from"zlib";var su=ou(import.meta.url),au=su.resolve("rrweb"),lu=Ao.join(Ao.dirname(au),"rrweb.umd.min.cjs"),cu=nu(lu,"utf8"),uu=[";(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
- `),du=cu+`
113
- `+uu;async function Io(e){let t,r=0;async function n(){await e.addScriptTag({content:du})}await n(),e.on("load",()=>{n().catch(l=>{let c=l instanceof Error?l.message:String(l);f.warn("rrweb re-injection on navigation failed: %s",c)})});async function o(){await J({awaitPromise:!1,expression:"globalThis.__ripploRrwebStart && globalThis.__ripploRrwebStart()",label:"rrweb start",page:e,timeoutMs:void 0});let l=await J({awaitPromise:!1,expression:"globalThis.__ripploRrwebStartedAt",label:"rrweb startedAt",page:e,timeoutMs:void 0});typeof l=="number"&&(t??=l)}function i(){if(t!=null)return Date.now()-t}async function s(){let l=await J({awaitPromise:!1,expression:"globalThis.__ripploRrwebDrain ? globalThis.__ripploRrwebDrain() : []",label:"rrweb drain",page:e,timeoutMs:void 0})??[],c=l[0],p=l.at(-1);if(c==null||p==null)return;t??=c.timestamp;let m=t,b=l.map(g=>JSON.stringify(g)).join(`
114
- `),A={body:iu(Buffer.from(b,"utf8")),chunkIndex:r,endTimestamp:p.timestamp-m,eventCount:l.length,startTimestamp:c.timestamp-m};return r+=1,A}async function a(){await J({awaitPromise:!1,expression:"globalThis.__ripploRrwebStop && globalThis.__ripploRrwebStop()",label:"rrweb stop",page:e,timeoutMs:void 0})}return{currentOffsetMs:i,detach:a,start:o,takeChunk:s}}function No(e){let t=[],r=[],n=[],o=[],i=[];return pu(e,t,r),mu(e,o),fu(e,n,i),{consoleEntries:t,lifecycle:o,network:n,pageErrors:r,capturePerf:()=>bu(e),drain:async()=>{await Promise.allSettled(i)}}}function pu(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 mu(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 fu(e,t,r){e.on("response",n=>{let o=n.request(),i=$o(o,n),s=t.push(i)-1;r.push(yu({idx:s,network:t,req:o,res:n}))}),e.on("requestfailed",n=>{t.push({...$o(n),failure:n.failure()?.errorText})})}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()}}var gu=new Set(["fetch","xhr"]);async function yu({idx:e,network:t,req:r,res:n}){let o=!gu.has(r.resourceType()),[i,s,a]=await Promise.all([jo(r.allHeaders()),jo(n.allHeaders()),o?Promise.resolve({error:void 0,text:void 0}):hu(n)]),l=t[e];l!=null&&(t[e]={...l,requestHeaders:i,responseBody:a.text,responseBodyError:a.error,responseHeaders:s})}async function jo(e){try{return await e}catch{return}}async function hu(e){try{return{error:void 0,text:(await e.body()).toString("utf8")}}catch(t){return{error:t instanceof Error?t.message:String(t),text:void 0}}}var wu=`(() => {
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 gu}from"fs";import{createRequire as yu}from"module";import jo from"path";import{gzipSync as hu}from"zlib";var wu=yu(import.meta.url),bu=wu.resolve("rrweb"),vu=jo.join(jo.dirname(bu),"rrweb.umd.min.cjs"),Su=gu(vu,"utf8"),ku=[";(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
+ `),Pu=Su+`
113
+ `+ku;async function No({cdpSession:e,page:t}){let r,n=0;async function o(){await t.addScriptTag({content:Pu})}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(B=>JSON.stringify(B)).join(`
114
+ `),y={body:hu(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 Uo({cdpSession:e,page:t}){let r=[],n=[],o=[],i=[],s=[];return Ru(t,r,n),xu(t,i),Eu(t,o,s),{consoleEntries:r,lifecycle:i,network:o,pageErrors:n,capturePerf:()=>Iu(e),drain:async()=>{await Promise.allSettled(s)}}}function Ru(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 xu(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 Eu(e,t,r){e.on("response",n=>{let o=n.request();if(!Do.has(o.resourceType()))return;let i=Oo(o,n),s=t.push(i)-1;r.push(Cu({idx:s,network:t,req:o,res:n}))}),e.on("requestfailed",n=>{Do.has(n.resourceType())&&t.push({...Oo(n),failure:n.failure()?.errorText})})}var Do=new Set(["fetch","xhr"]);function Oo(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 Cu({idx:e,network:t,req:r,res:n}){let[o,i,s]=await Promise.all([Lo(r.allHeaders()),Lo(n.allHeaders()),Tu(n)]),a=t[e];a!=null&&(t[e]={...a,requestHeaders:o,responseBody:s.text,responseBodyError:s.error,responseHeaders:i})}async function Lo(e){try{return await e}catch{return}}var _o=1500;async function Tu(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(_o)}ms`))},_o))])).toString("utf8")}}catch(t){return{error:t instanceof Error?t.message:String(t),text:void 0}}}var Au=`(() => {
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 bu(e){try{return await Le({label:"capturePerf",page:e,timeoutMs:void 0,fn:async t=>{let r=await t.send("Runtime.evaluate",{awaitPromise:!1,expression:wu,returnByValue:!0});if(r.exceptionDetails!=null){f.warn("capturePerf evaluation threw: %s",r.exceptionDetails.text);return}return r.result.value}})}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 Oo from"crypto";import{Webhook as vu}from"standardwebhooks";function ke({body:e,secret:t}){let r=new vu(t),n=`msg_${Oo.randomUUID()}`,o=new Date,i=r.sign(n,o,e),s=Math.floor(o.getTime()/1e3);return{"webhook-id":n,"webhook-signature":i,"webhook-timestamp":String(s)}}function qr(){return`whsec_${Oo.randomBytes(24).toString("base64")}`}var Su=15e4,ku={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},Ru=oe.discriminatedUnion("kind",[oe.object({kind:oe.literal("pass")}),oe.object({kind:oe.literal("retry"),reason:oe.string()}),oe.object({kind:oe.literal("fail"),reason:oe.string()})]),Pu=oe.object({error:oe.string().optional(),outcome:Ru.optional(),success:oe.boolean()});async function Do({apiUrl:e,budget:t,observer:r,params:n,webhookSecret:o}){let i=ku[t],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await Eu({apiUrl:e,observer:r,params:n,webhookSecret:o}),c=xu({observer:r,outcome:l,start:s,state:a});if(c!=null)return c;let p=i.timeoutMs-(performance.now()-s);if(p<=0)break;let m=Math.min(Cu({backoff:i.backoffMs,pollCount:a.pollCount}),p);await Tu(m)}return{description:`observer "${r}"`,detail:`budget "${t}" exhausted after ${String(a.pollCount)} poll(s) (${Lo(s)}); last: ${a.lastReason??"no retry reason"}
129
- \u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function xu({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 (${Lo(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 Eu({apiUrl:e,observer:t,params:r,webhookSecret:n}){let o=JSON.stringify({observer:t,params:r});try{let i=await fetch(`${e}/execute-observer`,{body:o,headers:{"Content-Type":"application/json",...ke({body:o,secret:n})},method:"PUT",signal:AbortSignal.timeout(Su)});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=Pu.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 Cu({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function Lo(e){return`${String(Math.round(performance.now()-e))}ms`}async function Tu(e){return new Promise(t=>setTimeout(t,e))}var Bt=15e3;async function Wr({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return Iu({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function Au({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function Iu({currentId:e,failFast:t,getRecordingOffsetMs:r,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],p=l,m=e;for(;m!=null;){let b=a.nodes[m];if(b==null)throw new Error(`Node "${m}" not found in spec`);let x=m,A=Ft(b);f.info("Executing node: %s [%s]",A,b.type);let g=await $u({getRecordingOffsetMs:r,node:b,nodeId:x,observerTransport:n,page:i,runStartTime:s,variables:p});if(Au({onStep:o,steps:[g],target:c}),p=g.variables,t&&g.status==="failed")break;m=b.next}return{steps:c,variables:p}}async function $u({getRecordingOffsetMs:e,node:t,nodeId:r,observerTransport:n,page:o,runStartTime:i,variables:s}){let a=performance.now(),l=e?.(),c=Ft(t),p=Bt;try{let m=await ju({node:t,observerTransport:n,page:o,timeout:p,variables:s}),b=Math.round(performance.now()-a),x=m.assertions.some(g=>g.status==="failed"),A=e?.();return{assertions:m.assertions,detail:void 0,duration:b,nodeId:r,nodeType:t.type,recordingEndMs:A,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:x?"failed":"passed",stepIndex:0,title:c,url:o.url(),variables:m.variables}}catch(m){let b=Math.round(performance.now()-a),x=m instanceof Error?m.message:String(m),A=e?.();return{assertions:[],detail:x,duration:b,nodeId:r,nodeType:t.type,recordingEndMs:A,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:"failed",stepIndex:0,title:c,url:o.url(),variables:s}}}async function ju({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(Nu(e)){let s=await Pr({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await Du({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function Nu(e){return["goto","click","dblclick","fill","select","hover","press","check","uncheck","clear","rightClick","handleDialog","clipboard","setPermission","setViewport","fail","setVariable","extractText","upload","drag","scrollIntoView","type","focus"].includes(e.type)}function Ou(e){return e.type.startsWith("assert")}async function Du({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!Ou(e))throw new Error(`Unknown node type: ${e.type}`);let i=e;switch(i.type){case"assertVisible":case"assertNotVisible":case"assertEnabled":case"assertDisabled":case"assertChecked":case"assertNotChecked":case"assertFocused":case"assertNotFocused":return _u({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=Y({ref:i.expected,variables:o});return[await xr({expected:s,locator:V({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=Y({ref:i.expected,variables:o});return[await Er({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=Y({ref:i.expected,variables:o});return[await Kn({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=Rr({ref:i.expected,variables:o});return[await Cr({expected:s,locator:V({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertValue":{let s=Y({ref:i.expected,variables:o});return[await Tr({expected:s,locator:V({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=Y({ref:i.expected,variables:o});return[await Jn({attribute:i.attribute,expected:s,locator:V({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 Do({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var Lu={assertChecked:Qn,assertDisabled:Xn,assertEnabled:Yn,assertFocused:eo,assertNotChecked:Zn,assertNotFocused:to,assertNotVisible:Ir,assertVisible:Ar};async function _u({assertNode:e,page:t,timeout:r,variables:n}){let o=Lu[e.type];return[await o({locator:V({locator:e.locator,page:t,variables:n}),timeout:r})]}var Uu=5e3,Vu=2e3;async function zr({abort:e,baseUrl:t,browser:r,cookies:n,extraVariables:o,observerTransport:i,onRecordingChunk:s,onStep:a,runId:l,spec:c}){let p=await r.newContext({baseURL:t});e.attachContext(p),p.setDefaultTimeout(Bt),p.setDefaultNavigationTimeout(Bt),n.length>0&&await p.addCookies(n);let m=await p.newPage(),b=No(m),x=await Io(m);async function A(){let I=await x.takeChunk();I!=null&&s?.(I)}let g=setInterval(()=>{A().catch(I=>{let q=I instanceof Error?I.message:String(I);f.warn("rrweb chunk flush failed: %s",q)})},2e3),H=[],E=!1;function M(I){a?.(I),E||(E=!0,x.start().catch(q=>{let he=q instanceof Error?q.message:String(q);f.warn("rrweb recorder start failed: %s",he)})),A().catch(q=>{let he=q instanceof Error?q.message:String(q);f.warn("rrweb step-boundary flush failed: %s",he)}),H.push(Eo({context:p,page:m,runId:l,stepIndex:I.stepIndex,stepResult:I}))}let $e=Fu(o,c.variableNamespaces),De={...kr({defs:c.variables}),...$e};try{let I=await Wr({failFast:!0,getRecordingOffsetMs:x.currentOffsetMs,observerTransport:i,onStep:M,page:m,spec:c,variables:De});clearInterval(g);let q=I.steps.filter(X=>X.status==="passed").length,he=I.steps.filter(X=>X.status==="failed").length,se={duration:I.steps.reduce((X,it)=>X+it.duration,0),failCount:he,passCount:q,runId:l,status:he>0?"failed":"passed",workflowName:""};return await we(Promise.allSettled([...H,Co({pageEvents:b,runId:l,steps:I.steps,summary:se}),x.detach().then(A).catch(X=>{let it=X instanceof Error?X.message:String(X);f.warn("Recorder detach failed: %s",it)})]),Uu,"post-run cleanup").catch(X=>{let it=X instanceof Error?X.message:String(X);f.warn("Post-run cleanup did not finish in budget: %s",it)}),I.steps}finally{clearInterval(g),await we(p.close(),Vu,"context.close").catch(I=>{let q=I instanceof Error?I.message:String(I);f.warn("Context close failed: %s",q)})}}function Fu(e,t){if(e==null||t==null)return{};let r=new Map;Object.entries(t).forEach(([o,i])=>{r.set(i,o)});let n={};return Object.entries(e).forEach(([o,i])=>{let s=r.get(o);s!=null&&(n[s]={...n[s],...i})}),n}async function pe({fn:e,label:t}){let r=performance.now(),n=await e();return f.debug("%s: %dms",t,Math.round(performance.now()-r)),n}var Jr=wr(At(),1);import{z as S}from"zod";var Mu=S.union([S.string(),S.number(),S.boolean()]),Bu=S.record(S.string(),S.record(S.string(),Mu)),Hu=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()}),qu=S.discriminatedUnion("ok",[S.object({cookies:S.array(Hu),data:Bu,executed:S.array(S.string()),ok:S.literal(!0),runId:S.string()}),S.object({error:S.string(),ok:S.literal(!1),runId:S.string()})]),Wu=S.object({results:S.array(qu)}),zu=S.object({results:S.array(S.object({error:S.string().optional(),ok:S.boolean(),runId:S.string()}))}),_o=3e4;async function Yr({apiUrl:e,data:t,executed:r,runId:n,webhookSecret:o}){if(r.length!==0)try{await Yu({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 Ht({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:[]}:Gu({apiUrl:o,preconditionNames:t,runId:r,webhookSecret:n})}async function Gu({apiUrl:e,preconditionNames:t,runId:r,webhookSecret:n}){return{...await Ku({apiUrl:e,webhookSecret:n}).load({preconditionNames:t,runId:r}),apiUrl:e}}function Xr(){Gr.clear(),Kr.clear()}var Gr=new Map;function Ku({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=Gr.get(r);if(n!=null)return n;let o=new Jr.default(i=>Ju({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,200)},cacheKeyFn:i=>i.runId});return Gr.set(r,o),o}async function Ju({apiUrl:e,keys:t,webhookSecret:r}){let n=performance.now(),o=JSON.stringify({batch:t.map(p=>({preconditions:[...p.preconditionNames],runId:p.runId}))}),i=await fetch(`${e}/execute-preconditions`,{body:o,headers:{"Content-Type":"application/json",...ke({body:o,secret:r})},method:"PUT",signal:AbortSignal.timeout(_o)});if(!i.ok){let p=await Zu(i),m=new Error(`execute-preconditions returned ${String(i.status)}: ${p}`);return t.map(()=>m)}let s=await i.json(),a=Wu.safeParse(s);if(!a.success){let p=new Error(`execute-preconditions response has invalid shape: ${a.error.message}`);return t.map(()=>p)}let l=new URL(e).hostname,c=new Map(a.data.results.map(p=>[p.runId,p]));return f.debug({batchSize:t.length,elapsedMs:Math.round(performance.now()-n),op:"execute-preconditions"},"batched op flushed"),t.map(p=>{let m=c.get(p.runId);return m==null?new Error(`execute-preconditions response missing runId ${p.runId}`):m.ok?(f.info("Preconditions resolved: %s",m.executed.join(", ")),{cookies:m.cookies.map(b=>rd({cookie:b,domain:l})),data:m.data,executed:m.executed}):new Error(`Precondition batch failed: ${m.error}`)})}var Kr=new Map;function Yu({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=Kr.get(r);if(n!=null)return n;let o=new Jr.default(i=>Xu({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,200)},cacheKeyFn:i=>i.runId});return Kr.set(r,o),o}async function Xu({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",...ke({body:n,secret:r})},method:"PUT",signal:AbortSignal.timeout(_o)});if(!o.ok){let l=new Error(`teardown-preconditions returned ${String(o.status)}`);return t.map(()=>l)}let i=await o.json(),s=zu.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 Qu=S.object({error:S.string()});async function Zu(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=ed(t),n=r==null?null:Qu.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function ed(e){try{return JSON.parse(e)}catch{return null}}var td={lax:"Lax",none:"None",strict:"Strict"};function rd({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=td[e.sameSite]??"Lax"),e.expires!=null&&(r.expires=e.expires),r}var ut=wr(At(),1);import{graphql as He}from"gql.tada";async function Qr({config:e,runId:t}){let r=nd(e);await r.start.load(t);let n=[];function o(c){return n.push(c.catch(()=>{})),c}function i(c){o(r.steps.load({runId:t,step:c})).catch(p=>{f.error(p,"submitRunSteps failed")})}function s(c){o(sd({chunk:c,config:e,runId:t})).catch(p=>{f.error(p,"submitRunRecordingChunk failed")})}async function a(){for(;n.length>0;){let c=n.splice(0);await Promise.all(c)}}async function l({flush:c,statusOverride:p,steps:m,summary:b}){c&&await pe({label:"flushSteps",fn:()=>a()});let x=m.filter(E=>E.status==="passed").length,A=m.filter(E=>E.status==="failed").length,g=m.reduce((E,M)=>E+M.duration,0),H=p??(A>0?"failed":"passed");await pe({label:"completeRun",fn:()=>r.complete.load({duration:g,failCount:A,passCount:x,runId:t,status:H,summary:b??null,warnCount:0})})}return{complete:l,enqueueRecordingChunk:s,enqueueStep:i,flushSteps:a,runId:t}}async function Zr({config:e,reason:t,runId:r}){await y({config:e,document:ld,variables:{reason:t,runId:r}})}var Uo=new Map;function nd(e){let t=`${e.ripploServerUrl}::${e.token}`,r=Uo.get(t);if(r!=null)return r;let n={artifactsUploaded:new ut.default(async o=>(await qt({config:e,document:ad,opName:"markRunArtifactsUploadedBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1}),complete:new ut.default(async o=>(await qt({config:e,document:pd,opName:"completeRunsBatch",size:o.length,variables:{items:[...o]}}),o.map(()=>!0)),{cache:!1}),start:new ut.default(async o=>(await qt({config:e,document:cd,opName:"startRunsBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,200)}}),steps:new ut.default(async o=>(await qt({config:e,document:ud,opName:"submitRunStepsBatch",size:o.length,variables:{items:od(o)}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,200)}})};return Uo.set(t,n),n}async function qt({config:e,document:t,opName:r,size:n,variables:o}){let i=performance.now();await y({config:e,document:t,variables:o}),f.debug({batchSize:n,elapsedMs:Math.round(performance.now()-i),op:r},"batched op flushed")}function od(e){let t=new Map;return e.forEach(({runId:r,step:n})=>{let o=id(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 id(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 sd({chunk:e,config:t,runId:r}){await y({config:t,document:dd,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runId:r,startTimestamp:e.startTimestamp}}})}var ad=He(`
128
+ })()`;async function Iu(e){try{return await se({awaitPromise:!1,expression:Au,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 Vo from"crypto";import{Webhook as $u}from"standardwebhooks";function Se({body:e,secret:t}){let r=new $u(t),n=`msg_${Vo.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 Wr(){return`whsec_${Vo.randomBytes(24).toString("base64")}`}var ju=15e4,Nu={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},Du=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()})]),Ou=oe.object({error:oe.string().optional(),outcome:Du.optional(),success:oe.boolean()});async function Fo({apiUrl:e,budget:t,observer:r,params:n,webhookSecret:o}){let i=Nu[t],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await _u({apiUrl:e,observer:r,params:n,webhookSecret:o}),c=Lu({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(Uu({backoff:i.backoffMs,pollCount:a.pollCount}),u);await Vu(m)}return{description:`observer "${r}"`,detail:`budget "${t}" exhausted after ${String(a.pollCount)} poll(s) (${Mo(s)}); last: ${a.lastReason??"no retry reason"}
129
+ \u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function Lu({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 (${Mo(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 _u({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(ju)});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=Ou.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 Uu({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function Mo(e){return`${String(Math.round(performance.now()-e))}ms`}async function Vu(e){return new Promise(t=>setTimeout(t,e))}var Bt=15e3;async function qr({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return Mu({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function Fu({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function Mu({currentId:e,failFast:t,getRecordingOffsetMs:r,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],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,A=Ft(g);f.info("Executing node: %s [%s]",A,g.type);let y=await Bu({getRecordingOffsetMs:r,node:g,nodeId:R,observerTransport:n,page:i,runStartTime:s,variables:u});if(Fu({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=Bt;try{let m=await Hu({node:t,observerTransport:n,page:o,timeout:u,variables:s}),g=Math.round(performance.now()-a),R=m.assertions.some(y=>y.status==="failed"),A=e?.();return{assertions:m.assertions,detail:void 0,duration:g,nodeId:r,nodeType:t.type,recordingEndMs:A,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),A=e?.();return{assertions:[],detail:R,duration:g,nodeId:r,nodeType:t.type,recordingEndMs:A,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:"failed",stepIndex:0,title:c,url:o.url(),variables:s}}}async function Hu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(Wu(e)){let s=await Rr({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 Wu(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 Ku({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=Y({ref:i.expected,variables:o});return[await xr({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 Er({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=Y({ref:i.expected,variables:o});return[await Yn({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=Pr({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"assertValue":{let s=Y({ref:i.expected,variables:o});return[await Tr({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 Qn({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 Fo({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var Gu={assertChecked:to,assertDisabled:eo,assertEnabled:Zn,assertFocused:no,assertNotChecked:ro,assertNotFocused:oo,assertNotVisible:Ir,assertVisible:Ar};async function Ku({assertNode:e,page:t,timeout:r,variables:n}){let o=Gu[e.type];return[await o({locator:F({locator:e.locator,page:t,variables:n}),timeout:r})]}var Ju=5e3,Xu=2e3;async function zr({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(Bt),u.setDefaultNavigationTimeout(Bt),n.length>0&&await u.addCookies(n);let m=await u.newPage(),g=await u.newCDPSession(m),R=Uo({cdpSession:g,page:m}),A=await No({cdpSession:g,page:m});async function y(){let O=await A.takeChunk();O!=null&&s?.(O)}let B=setInterval(()=>{y().catch(O=>{let J=O instanceof Error?O.message:String(O);f.warn("rrweb chunk flush failed: %s",J)})},2e3),E=[],H=!1;function Ie(O){a?.(O),H||(H=!0,A.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(Ao({cdpSession:g,context:u,page:m,runId:l,stepIndex:O.stepIndex,stepResult:O}))}let De=Qu(o,c.variableNamespaces),pe={...kr({defs:c.variables}),...De};try{let O=await qr({failFast:!0,getRecordingOffsetMs:A.currentOffsetMs,observerTransport:i,onStep:Ie,page:m,spec:c,variables:pe});clearInterval(B);let J=O.steps.filter(ot=>ot.status==="passed").length,z=O.steps.filter(ot=>ot.status==="failed").length,ba={duration:O.steps.reduce((ot,va)=>ot+va.duration,0),failCount:z,passCount:J,runId:l,status:z>0?"failed":"passed",workflowName:""};return await Yu({debugCaptures:E,flushRecording:y,pageEvents:R,recorder:A,runId:l,steps:O.steps,summary:ba}),O.steps}finally{clearInterval(B),await j({label:"cdpSession.detach",fn:()=>g.detach().catch(()=>{})}),await j({label:"context.close",fn:()=>me(u.close(),Xu,"context.close").catch(O=>{let J=O instanceof Error?O.message:String(O);f.warn("Context close failed: %s",J)})})}}async function Yu({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:()=>Io({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)})})]),Ju,"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 Qu(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 Jr=wr(At(),1);import{z as S}from"zod";var Zu=S.union([S.string(),S.number(),S.boolean()]),ed=S.record(S.string(),S.record(S.string(),Zu)),td=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()}),rd=S.discriminatedUnion("ok",[S.object({cookies:S.array(td),data:ed,executed:S.array(S.string()),ok:S.literal(!0),runId:S.string()}),S.object({error:S.string(),ok:S.literal(!1),runId:S.string()})]),nd=S.object({results:S.array(rd)}),od=S.object({results:S.array(S.object({error:S.string().optional(),ok:S.boolean(),runId:S.string()}))}),Bo=3e4;async function Xr({apiUrl:e,data:t,executed:r,runId:n,webhookSecret:o}){if(r.length!==0)try{await ld({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 Ht({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:[]}:id({apiUrl:o,preconditionNames:t,runId:r,webhookSecret:n})}async function id({apiUrl:e,preconditionNames:t,runId:r,webhookSecret:n}){return{...await sd({apiUrl:e,webhookSecret:n}).load({preconditionNames:t,runId:r}),apiUrl:e}}function Yr(){Gr.clear(),Kr.clear()}var Gr=new Map;function sd({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=Gr.get(r);if(n!=null)return n;let o=new Jr.default(i=>ad({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,100)},cacheKeyFn:i=>i.runId});return Gr.set(r,o),o}async function ad({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(Bo)});if(!i.ok){let u=await dd(i),m=new Error(`execute-preconditions returned ${String(i.status)}: ${u}`);return t.map(()=>m)}let s=await i.json(),a=nd.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=>fd({cookie:g,domain:l})),data:m.data,executed:m.executed}):new Error(`Precondition batch failed: ${m.error}`)})}var Kr=new Map;function ld({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=Kr.get(r);if(n!=null)return n;let o=new Jr.default(i=>cd({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,100)},cacheKeyFn:i=>i.runId});return Kr.set(r,o),o}async function cd({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(Bo)});if(!o.ok){let l=new Error(`teardown-preconditions returned ${String(o.status)}`);return t.map(()=>l)}let i=await o.json(),s=od.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 ud=S.object({error:S.string()});async function dd(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=pd(t),n=r==null?null:ud.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function pd(e){try{return JSON.parse(e)}catch{return null}}var md={lax:"Lax",none:"None",strict:"Strict"};function fd({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=md[e.sameSite]??"Lax"),e.expires!=null&&(r.expires=e.expires),r}var ut=wr(At(),1);import{graphql as Me}from"gql.tada";async function Zr({config:e,runId:t}){let r=gd(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(wd({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,A=m.filter(E=>E.status==="failed").length,y=m.reduce((E,H)=>E+H.duration,0),B=u??(A>0?"failed":"passed");await j({label:"completeRun",fn:()=>r.complete.load({duration:y,failCount:A,passCount:R,runId:t,status:B,summary:g??null,warnCount:0})})}return{complete:l,enqueueRecordingChunk:s,enqueueStep:i,flushSteps:a,runId:t}}async function en({config:e,reason:t,runId:r}){await h({config:e,document:vd,variables:{reason:t,runId:r}})}var Ho=new Map,Qr=new Set;async function tn(){await Promise.allSettled(Qr)}function Wo(e){Qr.add(e),e.finally(()=>{Qr.delete(e)})}function gd(e){let t=`${e.ripploServerUrl}::${e.token}`,r=Ho.get(t);if(r!=null)return r;let n={artifactsUploaded:new ut.default(async o=>(await Wt({config:e,document:bd,opName:"markRunArtifactsUploadedBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1}),complete:new ut.default(async o=>(await Wt({config:e,document:Rd,opName:"completeRunsBatch",size:o.length,variables:{items:[...o]}}),o.map(()=>!0)),{cache:!1}),start:new ut.default(async o=>(await Wt({config:e,document:Sd,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:kd,opName:"submitRunStepsBatch",size:o.length,variables:{items:yd(o)}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,100)}})};return Ho.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 yd(e){let t=new Map;return e.forEach(({runId:r,step:n})=>{let o=hd(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 hd(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 wd({chunk:e,config:t,runId:r}){await h({config:t,document:Pd,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runId:r,startTimestamp:e.startTimestamp}}})}var bd=Me(`
132
132
  mutation MarkRunArtifactsUploadedBatchCLI($runIds: [String!]!) {
133
133
  markRunArtifactsUploadedBatch(runIds: $runIds)
134
134
  }
135
- `),ld=He(`
135
+ `),vd=Me(`
136
136
  mutation FailRunCLI($runId: String!, $reason: String!) {
137
137
  failRun(runId: $runId, reason: $reason)
138
138
  }
139
- `),cd=He(`
139
+ `),Sd=Me(`
140
140
  mutation StartRunsBatchCLI($runIds: [String!]!) {
141
141
  startRunsBatch(runIds: $runIds) {
142
142
  id
143
143
  }
144
144
  }
145
- `),ud=He(`
145
+ `),kd=Me(`
146
146
  mutation SubmitRunStepsBatchCLI($items: [SubmitRunStepsItem!]!) {
147
147
  submitRunStepsBatch(items: $items)
148
148
  }
149
- `),dd=He(`
149
+ `),Pd=Me(`
150
150
  mutation SubmitRunRecordingChunkCLI($input: SubmitRunRecordingChunkInput!) {
151
151
  submitRunRecordingChunk(input: $input)
152
152
  }
153
- `),pd=He(`
153
+ `),Rd=Me(`
154
154
  mutation CompleteRunsBatchCLI($items: [CompleteRunItem!]!) {
155
155
  completeRunsBatch(items: $items) {
156
156
  id
157
157
  status
158
158
  }
159
159
  }
160
- `);var gd=12e4,yd=15e3,Bo=Mo(`
160
+ `);var Cd=12e4,Td=15e3,Ko=Go(`
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
- `),hd=Mo(`
172
+ `),Ad=Go(`
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
- `,[Bo]);async function en({baseUrl:e,browser:t,config:r,headed:n,preconditionNames:o,runId:i,webhookSecret:s}){let a="unknown",l,c,p=!1,m=Po(),b=performance.now();try{p=t==null,c=wd({externalBrowser:t,headed:n});let x=o==null?void 0:Ht({engineBaseUrl:r.engineUrl,preconditionNames:o,runId:i,webhookSecret:s}),[{engineBaseUrl:A,workflow:g},H]=await Promise.all([pe({label:"Run context resolved",fn:()=>xd({config:r,runId:i})}),pe({label:"Streaming run started",fn:()=>Qr({config:r,runId:i})}),Nr({appUrl:e})]);a=g.name,l=H;let E=Ed(g.spec);f.info("Executing workflow: %s",g.name),await Ad(vd({abort:m,baseUrl:e,browserPromise:c,engineBaseUrl:A,preconditionPromise:x,runId:i,specData:E,streaming:l,webhookSecret:s,workflow:g}),Td(),m)}catch(x){throw Id(x)?x:(await we(bd({browserPromise:c,config:r,error:x,ownsBrowser:p,runId:i,streaming:l,workflowName:a}),yd,"post-deadline cleanup").catch(A=>{let g=A instanceof Error?A.message:String(A);f.warn("Post-deadline cleanup did not finish in budget: %s",g)}),new Wt(x))}finally{f.debug({elapsedMs:Math.round(performance.now()-b),runId:i},"run finished (totalMs=%d)",Math.round(performance.now()-b))}}var Wt=class extends Error{cause;constructor(t){let r=t instanceof Error?t.message:String(t);super(r),this.name="RunReportedError",this.cause=t}};function wd({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):pe({label:"Browser launched",fn:()=>Fe({headed:t})})}async function bd({browserPromise:e,config:t,error:r,ownsBrowser:n,runId:o,streaming:i,workflowName:s}){let a=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;await To({error:a,runId:o,stack:l,workflowName:s}),i==null?await Zr({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 p=o??Ht({engineBaseUrl:n,preconditionNames:c.preconditions,runId:i,webhookSecret:l}),[m,b]=await Promise.all([p,r]);await Sd({abort:e,baseUrl:t,browser:b,preconditionResult:m,runId:i,specData:s,streaming:a,webhookSecret:l})}async function Sd({abort:e,baseUrl:t,browser:r,preconditionResult:n,runId:o,specData:i,streaming:s,webhookSecret:a}){let l=await pe({label:"Spec executed",fn:()=>zr({abort:e,baseUrl:t,browser:r,cookies:n.cookies,extraVariables:n.data,observerTransport:n.apiUrl==null?void 0:{apiUrl:n.apiUrl,webhookSecret:a},onRecordingChunk:s.enqueueRecordingChunk,onStep:s.enqueueStep,runId:o,spec:i})});await Pd({preconditionResult:n,runId:o,webhookSecret:a}),await s.complete({flush:!0,statusOverride:void 0,steps:l,summary:kd(l)});let c=l.filter(m=>m.status==="passed").length,p=l.filter(m=>m.status==="failed").length;f.info("Run complete: %d passed, %d failed",c,p)}function kd(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 ${Rd(n)}`}function Rd(e){return e.split(`
186
- `,1)[0]??e}async function Pd({preconditionResult:e,runId:t,webhookSecret:r}){e.apiUrl!=null&&await Yr({apiUrl:e.apiUrl,data:e.data,executed:e.executed,runId:t,webhookSecret:r})}async function xd({config:e,runId:t}){let r=await $d(e).load(t);if(r.workflow==null)throw new Error(`Run ${t} not found`);let n=fd(Bo,r.workflow),o=r.workflow.project?.engineBaseUrl??"";return{engineBaseUrl:e.engineUrl.length>0?e.engineUrl:o,workflow:n}}function Ed(e){if(e==null)throw new Error("Workflow has no spec");return Mr.decode(e)}var Cd=md.coerce.number().int().positive().catch(gd);function Td(){return Cd.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function Ad(e,t,r){let n,o=new Promise((i,s)=>{n=setTimeout(()=>{r.fire(),s(new Error(`Run timed out after ${String(t)}ms`))},t)});try{await Promise.race([e,o])}finally{n!=null&&clearTimeout(n)}}function Id(e){return e instanceof Me?e.errors.some(t=>t.extensions?.code==="THROTTLED"):!1}var Vo=new Map;function $d(e){let t=`${e.ripploServerUrl}::${e.token}`,r=Vo.get(t);if(r!=null)return r;let n=new Fo.default(async o=>{let i=performance.now(),s=await y({config:e,document:hd,variables:{ids:[...o]}}),a=new Map(s.runsByIds?.map(l=>[l.id,l])??[]);return f.debug({batchSize:o.length,elapsedMs:Math.round(performance.now()-i),op:"runsByIds"},"batched op flushed"),o.map(l=>a.get(l)??new Error(`Run ${l} not found`))},{cache:!1,batchScheduleFn:o=>{setTimeout(o,200)}});return Vo.set(t,n),n}import ft from"fs";import Ne from"fs";import jd from"os";import dt from"path";var Nd=".local",Od=".ripplo";function tn(e){return dt.join(e,".ripplo",Nd)}function pt(e){let t=tn(e);Ne.existsSync(t)||Ne.mkdirSync(t,{recursive:!0});let r=dt.join(t,".gitignore");return Ne.existsSync(r)||Ne.writeFileSync(r,`*
187
- `),t}function mt(e,t){return dt.join(tn(e),t)}function rn(){return dt.join(jd.homedir(),Od)}function nn(){let e=rn();return Ne.existsSync(e)?Ne.chmodSync(e,448):Ne.mkdirSync(e,{mode:448,recursive:!0}),e}function Re(e){return dt.join(rn(),e)}function ie(){let e=process.env.RIPPLO_TOKEN;if(e!=null&&e.trim().length>0)return e.trim();let t=Re("token");if(!ft.existsSync(t))return null;let r=ft.readFileSync(t,"utf8").trim();return r.length===0?null:r}function on(e){nn(),ft.writeFileSync(Re("token"),e+`
188
- `,{mode:384})}function sn(){let e=Re("token");return ft.existsSync(e)?(ft.unlinkSync(e),!0):!1}import{graphql as gt}from"gql.tada";var yk=gt(`
185
+ `,[Ko]);async function rn({baseUrl:e,browser:t,config:r,headed:n,preconditionNames:o,runId:i,webhookSecret:s}){let a="unknown",l,c,u=!1,m=Co(),g=performance.now();try{u=t==null,c=Id({externalBrowser:t,headed:n});let R=o==null?void 0:Ht({engineBaseUrl:r.engineUrl,preconditionNames:o,runId:i,webhookSecret:s}),[{engineBaseUrl:A,workflow:y},B]=await Promise.all([j({label:"Run context resolved",fn:()=>_d({config:r,runId:i})}),j({label:"Streaming run started",fn:()=>Zr({config:r,runId:i})}),Nr({appUrl:e})]);a=y.name,l=B;let E=Ud(y.spec);f.info("Executing workflow: %s",y.name),await Md(jd({abort:m,baseUrl:e,browserPromise:c,engineBaseUrl:A,preconditionPromise:R,runId:i,specData:E,streaming:l,webhookSecret:s,workflow:y}),Fd(),m)}catch(R){throw Bd(R)?R:(await me($d({browserPromise:c,config:r,error:R,ownsBrowser:u,runId:i,streaming:l,workflowName:a}),Td,"post-deadline cleanup").catch(A=>{let y=A instanceof Error?A.message:String(A);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 Id({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):j({label:"Browser launched",fn:()=>Ue({headed:t})})}async function $d({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 $o({error:a,runId:o,stack:l,workflowName:s}),i==null?await en({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 jd({abort:e,baseUrl:t,browserPromise:r,engineBaseUrl:n,preconditionPromise:o,runId:i,specData:s,streaming:a,webhookSecret:l,workflow:c}){let u=o??Ht({engineBaseUrl:n,preconditionNames:c.preconditions,runId:i,webhookSecret:l}),[m,g]=await Promise.all([u,r]);await Nd({abort:e,baseUrl:t,browser:g,preconditionResult:m,runId:i,specData:s,streaming:a,webhookSecret:l})}async function Nd({abort:e,baseUrl:t,browser:r,preconditionResult:n,runId:o,specData:i,streaming:s,webhookSecret:a}){let l=await j({label:"Spec executed",fn:()=>zr({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})});Ld({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:Dd(l)}).catch(g=>{let R=g instanceof Error?g.message:String(g);f.warn("streaming.complete failed: %s",R)});Wo(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 Dd(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 ${Od(n)}`}function Od(e){return e.split(`
186
+ `,1)[0]??e}async function Ld({preconditionResult:e,runId:t,webhookSecret:r}){e.apiUrl!=null&&await Xr({apiUrl:e.apiUrl,data:e.data,executed:e.executed,runId:t,webhookSecret:r})}async function _d({config:e,runId:t}){let r=await Hd(e).load(t);if(r.workflow==null)throw new Error(`Run ${t} not found`);let n=Ed(Ko,r.workflow),o=r.workflow.project?.engineBaseUrl??"";return{engineBaseUrl:e.engineUrl.length>0?e.engineUrl:o,workflow:n}}function Ud(e){if(e==null)throw new Error("Workflow has no spec");return Mr.decode(e)}var Vd=xd.coerce.number().int().positive().catch(Cd);function Fd(){return Vd.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function Md(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 qo=new Map;function Hd(e){let t=`${e.ripploServerUrl}::${e.token}`,r=qo.get(t);if(r!=null)return r;let n=new zo.default(async o=>{let i=performance.now(),s=await h({config:e,document:Ad,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 qo.set(t,n),n}import ft from"fs";import je from"fs";import Wd from"os";import dt from"path";var qd=".local",zd=".ripplo";function nn(e){return dt.join(e,".ripplo",qd)}function pt(e){let t=nn(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(nn(e),t)}function on(){return dt.join(Wd.homedir(),zd)}function sn(){let e=on();return je.existsSync(e)?je.chmodSync(e,448):je.mkdirSync(e,{mode:448,recursive:!0}),e}function ke(e){return dt.join(on(),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 an(e){sn(),ft.writeFileSync(ke("token"),e+`
188
+ `,{mode:384})}function ln(){let e=ke("token");return ft.existsSync(e)?(ft.unlinkSync(e),!0):!1}import{graphql as gt}from"gql.tada";var Nk=gt(`
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 hk=gt(`
202
+ `);var Dk=gt(`
203
203
  mutation StartAgentReviewWorker($reviewId: String!) {
204
204
  startAgentReview(reviewId: $reviewId)
205
205
  }
206
- `);var wk=gt(`
206
+ `);var Ok=gt(`
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 bk=gt(`
220
+ `);var Lk=gt(`
221
221
  mutation UpdateAgentReviewProgressWorker($reviewId: String!, $text: String!) {
222
222
  updateAgentReviewProgress(reviewId: $reviewId, text: $text)
223
223
  }
224
- `);var vk=gt(`
224
+ `);var _k=gt(`
225
225
  mutation FailAgentReviewWorker($reviewId: String!, $reason: String!) {
226
226
  failAgentReview(reviewId: $reviewId, reason: $reason)
227
227
  }
228
- `);import Wo from"fs";import Kt from"path";import{config as _d}from"dotenv";import{z as Gt}from"zod";import yt from"fs";import ln from"path";import{z as zt}from"zod";var Ho=ln.join(".ripplo","project.json"),an=[".env",".env.local"],Dd=zt.object({envFiles:zt.array(zt.string().min(1)).optional(),projectId:zt.string().min(1)});function cn(e){return ln.join(e,Ho)}function un(e){let t=cn(e);if(!yt.existsSync(t))throw new Error(`ripplo: missing ${Ho}. Run \`ripplo init\` to create it.`);let r=JSON.parse(yt.readFileSync(t,"utf8")),n=Dd.parse(r);return{envFiles:n.envFiles??an,projectId:n.projectId}}function dn(e){let t=cn(e);if(yt.existsSync(t))try{return un(e)}catch{return}}function qo({cwd:e,envFiles:t,projectId:r}){let n=cn(e);yt.mkdirSync(ln.dirname(n),{recursive:!0});let o={projectId:r};t!=null&&!Ld(t)&&(o.envFiles=[...t]),yt.writeFileSync(n,JSON.stringify(o,null,2)+`
229
- `)}function Ld(e){return e.length!==an.length?!1:e.every((t,r)=>t===an[r])}function zo(e){let r=dn(e)?.envFiles??[".env",".env.local"],n=Kt.join(e,".ripplo");r.forEach(o=>{let i=Kt.resolve(n,o);Wo.existsSync(i)&&_d({override:!0,path:i,quiet:!0})}),pn=void 0}var Ud=Gt.object({RIPPLO_APP_URL:Gt.url(),RIPPLO_ENGINE_URL:Gt.url(),RIPPLO_WEBHOOK_SECRET:Gt.string().min(1)}),pn;function qe(){return pn??=Vd(),pn}function Vd(){let e=Ud.safeParse(process.env);if(!e.success){let r=e.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
230
- `),n=mn(process.cwd()),o=n.map(s=>` ${s}`).join(`
228
+ `);import Yo from"fs";import Kt from"path";import{config as Jd}from"dotenv";import{z as Gt}from"zod";import yt from"fs";import un from"path";import{z as zt}from"zod";var Jo=un.join(".ripplo","project.json"),cn=[".env",".env.local"],Gd=zt.object({envFiles:zt.array(zt.string().min(1)).optional(),projectId:zt.string().min(1)});function dn(e){return un.join(e,Jo)}function pn(e){let t=dn(e);if(!yt.existsSync(t))throw new Error(`ripplo: missing ${Jo}. Run \`ripplo init\` to create it.`);let r=JSON.parse(yt.readFileSync(t,"utf8")),n=Gd.parse(r);return{envFiles:n.envFiles??cn,projectId:n.projectId}}function mn(e){let t=dn(e);if(yt.existsSync(t))try{return pn(e)}catch{return}}function Xo({cwd:e,envFiles:t,projectId:r}){let n=dn(e);yt.mkdirSync(un.dirname(n),{recursive:!0});let o={projectId:r};t!=null&&!Kd(t)&&(o.envFiles=[...t]),yt.writeFileSync(n,JSON.stringify(o,null,2)+`
229
+ `)}function Kd(e){return e.length!==cn.length?!1:e.every((t,r)=>t===cn[r])}function Qo(e){let r=mn(e)?.envFiles??[".env",".env.local"],n=Kt.join(e,".ripplo");r.forEach(o=>{let i=Kt.resolve(n,o);Yo.existsSync(i)&&Jd({override:!0,path:i,quiet:!0})}),fn=void 0}var Xd=Gt.object({RIPPLO_APP_URL:Gt.url(),RIPPLO_ENGINE_URL:Gt.url(),RIPPLO_WEBHOOK_SECRET:Gt.string().min(1)}),fn;function Be(){return fn??=Yd(),fn}function Yd(){let e=Xd.safeParse(process.env);if(!e.success){let r=e.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
230
+ `),n=gn(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 mn(e){let r=dn(e)?.envFiles??[],n=Kt.join(e,".ripplo");return r.map(o=>Kt.resolve(n,o)).filter(o=>!Wo.existsSync(o))}import _w from"yargs";import{hideBin as Uw}from"yargs/helpers";import{graphql as ep}from"gql.tada";import{exec as qd}from"child_process";import{createAuthClient as Fd}from"better-auth/client";import{deviceAuthorizationClient as Md}from"better-auth/client/plugins";function Go({baseURL:e}){return Fd({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[Md()]})}import{z as fn}from"zod";var Bd="https://ripplo.ai";function ee(){return Jt().RIPPLO_SERVER_URL}function Jo(){return Jt().RIPPLO_PROJECT_ID}var Hd=fn.object({RIPPLO_PROJECT_ID:fn.string().min(1).optional(),RIPPLO_SERVER_URL:fn.string().min(1).default(Bd)}),Ko;function Jt(){return Ko??=Hd.parse(process.env),Ko}var Wd=5e3,Yo="ripplo-cli";async function Xo({onDeviceCode:e,url:t}){let r=t??Jt().RIPPLO_SERVER_URL,n=Go({baseURL:r}),o=await n.device.code({client_id:Yo});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}),Xd(a);let l=await zd({authClient:n,deviceCode:i});return on(l),l}async function zd({authClient:e,deviceCode:t}){for(;;){await Jd(Wd);let r=await e.device.token({client_id:Yo,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(!Kd(r.error.error))throw new Error(`Authorization failed: ${r.error.error_description}`)}}var Gd=new Set(["authorization_pending","slow_down"]);function Kd(e){return Gd.has(e)}function Jd(e){return new Promise(t=>{setTimeout(t,e)})}function Yd(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function Xd(e){let t=Yd();qd(`${t} "${e}"`,()=>{})}function Pe({serverUrl:e,token:t}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:t,webhookSecret:""}}import Qd from"fs";import Zd from"path";function $(e){return Qd.existsSync(Zd.join(e,".ripplo"))}var tp=ep(`
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 gn(e){let r=mn(e)?.envFiles??[],n=Kt.join(e,".ripplo");return r.map(o=>Kt.resolve(n,o)).filter(o=>!Yo.existsSync(o))}import Qw from"yargs";import{hideBin as Zw}from"yargs/helpers";import{graphql as pp}from"gql.tada";import{exec as rp}from"child_process";import{createAuthClient as Qd}from"better-auth/client";import{deviceAuthorizationClient as Zd}from"better-auth/client/plugins";function Zo({baseURL:e}){return Qd({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[Zd()]})}import{z as yn}from"zod";var ep="https://ripplo.ai";function ee(){return Jt().RIPPLO_SERVER_URL}function ti(){return Jt().RIPPLO_PROJECT_ID}var tp=yn.object({RIPPLO_PROJECT_ID:yn.string().min(1).optional(),RIPPLO_SERVER_URL:yn.string().min(1).default(ep)}),ei;function Jt(){return ei??=tp.parse(process.env),ei}var np=5e3,ri="ripplo-cli";async function ni({onDeviceCode:e,url:t}){let r=t??Jt().RIPPLO_SERVER_URL,n=Zo({baseURL:r}),o=await n.device.code({client_id:ri});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}),cp(a);let l=await op({authClient:n,deviceCode:i});return an(l),l}async function op({authClient:e,deviceCode:t}){for(;;){await ap(np);let r=await e.device.token({client_id:ri,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(!sp(r.error.error))throw new Error(`Authorization failed: ${r.error.error_description}`)}}var ip=new Set(["authorization_pending","slow_down"]);function sp(e){return ip.has(e)}function ap(e){return new Promise(t=>{setTimeout(t,e)})}function lp(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function cp(e){let t=lp();rp(`${t} "${e}"`,()=>{})}function Pe({serverUrl:e,token:t}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:t,webhookSecret:""}}import up from"fs";import dp from"path";function I(e){return up.existsSync(dp.join(e,".ripplo"))}var mp=pp(`
239
239
  query AuthViewer {
240
240
  currentUser {
241
241
  name
242
242
  email
243
243
  }
244
244
  }
245
- `);async function Qo(){let e=ee(),t=ie();if(t!=null){let s=await gn({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 oi(){let e=ee(),t=ie();if(t!=null){let s=await hn({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 Xo({url:e,onDeviceCode:s=>{process.stdout.write(`Opening your browser to finish sign-in.
248
+ `)}let r=await ni({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 gn({serverUrl:e,token:r}),o=$(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
253
+ `)}}),n=await hn({serverUrl:e,token:r}),o=I(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
254
254
  `),process.stdout.write(n==null?`${i}.
255
- `:`${i}, ${rp(n)}.
256
- `),process.stdout.write(`Session saved to ${Re("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 rp(e){let t=e.name.trim().split(/\s+/)[0];return t!=null&&t.length>0?t:e.email}async function gn({serverUrl:e,token:t}){try{let n=(await y({config:Pe({serverUrl:e,token:t}),document:tp,variables:void 0})).currentUser;return n==null?null:{email:n.email,name:n.name}}catch{return null}}async function Zo(){let e=ie();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let t=ee(),r=await gn({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 ei(){if(!sn()){process.stdout.write(`No token to remove.
259
- `);return}process.stdout.write(`Removed ${Re("token")}
260
- `)}import{createHash as np}from"crypto";import ht from"fs/promises";import ze from"path";import{z as Yt}from"zod";import{z as ti}from"zod";import{z as We}from"zod";import{z as d}from"zod";import{z as xe}from"zod";import{z as ai}from"zod";import{z as O}from"zod";import{z as te}from"zod";import{z as yn}from"zod";import{z as C}from"zod";var op=Yt.object({__codec:Yt.string().min(1),data:Yt.unknown(),version:Yt.number().int().positive()}),ip=class extends Error{codec;currentVersion;gotVersion;constructor(e){super(`Unsupported ${e.codec} version ${String(e.gotVersion)} (current ${String(e.currentVersion)}). Upgrade Ripplo or rebuild with a compatible CLI.`),this.name="CodecVersionError",this.codec=e.codec,this.currentVersion=e.currentVersion,this.gotVersion=e.gotVersion}},sp=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function bn(e){return ii({legacy:void 0,migrators:[],name:e,schemas:[]})}function ap(e,t){let r=JSON.parse(t);return e.decode(r)}function ii(e){return{initial:t=>hn(t,{...e,schemas:[t]}),legacy:t=>ii({...e,legacy:t})}}function hn(e,t){return{build:()=>lp(e,t),legacy:r=>hn(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return hn(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function lp(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>cp(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function cp(e,t,r){let{data:n,version:o}=up(t,r),i=si(t,n,o);return e.parse(i)}function up(e,t){let r=op.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new sp({expected:e.name,got:r.data.__codec});return{data:r.data.data,version:r.data.version}}if(e.legacy!=null&&e.legacy.detect(t))return{data:t,version:e.legacy.assumedVersion};throw new Error(`Cannot decode "${e.name}": value is not a codec envelope and no legacy detector matched.`)}function si(e,t,r){let n=e.schemas.length;if(r>n)throw new ip({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 si(e,s(i),r+1)}var vn=We.object({depends:We.array(We.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:We.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:We.array(We.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."),dp=xe.object({by:xe.literal("testId"),value:xe.string().min(1)}),pp=xe.object({by:xe.literal("role"),name:xe.string().optional(),role:xe.string().min(1)}),T=xe.discriminatedUnion("by",[dp,pp]),wt=ai.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),mp=ai.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),fp=O.object({type:O.literal("static"),value:O.union([O.string(),O.number(),O.boolean()])}),Xt=O.object({name:O.string().min(1),type:O.literal("variable")}),gp=O.discriminatedUnion("type",[fp,Xt]),ae=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.string()}),Xt]),yp=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.number().int().nonnegative()}),Xt]),hp=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.union([O.string(),O.number(),O.boolean()])}),Xt]),wp=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:d.string().min(1).max(200),label:d.string().max(500).optional(),next:d.string().max(200).optional(),uiOnly:d.boolean().optional()},ri=500,bp=d.object({...k,type:d.literal("goto"),url:ae}),vp=d.object({...k,locator:T,modifier:d.enum(["Alt","Control","Meta","Shift"]).optional(),type:d.literal("click")}),Sp=d.object({...k,locator:T,type:d.literal("fill"),value:ae}),kp=d.object({...k,locator:T,type:d.literal("select"),value:ae}),Rp=d.object({...k,locator:T,type:d.literal("hover")}),Pp=d.object({...k,key:d.string().min(1),locator:T.optional(),type:d.literal("press")}),xp=d.object({...k,locator:T,type:d.literal("check")}),Ep=d.object({...k,locator:T,type:d.literal("uncheck")}),Cp=d.object({...k,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),Tp=d.object({...k,message:d.string().min(1),type:d.literal("fail")}),Ap=d.object({...k,type:d.literal("setVariable"),value:gp,variable:d.string().min(1)}),Ip=d.object({...k,locator:T,type:d.literal("extractText"),variable:d.string().min(1)}),$p=d.object({...k,files:d.array(d.string()).min(1),locator:T,type:d.literal("upload")}),jp=d.object({...k,locator:T,type:d.literal("dblclick")}),Np=d.object({...k,source:T,target:T,type:d.literal("drag")}),Op=d.object({...k,locator:T,type:d.literal("scrollIntoView")}),Dp=d.object({...k,locator:T,type:d.literal("type"),value:ae}),Lp=d.object({...k,locator:T,type:d.literal("focus")}),_p=d.object({...k,locator:T,type:d.literal("clear")}),Up=d.object({...k,locator:T,type:d.literal("rightClick")}),Vp=d.object({...k,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),Fp=d.object({...k,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:ae.optional(),variable:d.string().min(1).optional()}),Mp=d.object({...k,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),Bp=d.object({...k,locator:T,type:d.literal("assertVisible")}),Hp=d.object({...k,locator:T,type:d.literal("assertNotVisible")}),qp=d.object({...k,expected:ae,locator:T,operator:wt,type:d.literal("assertText")}),Wp=d.object({...k,expected:ae,operator:wt,type:d.literal("assertUrl")}),zp=d.object({...k,expected:yp,locator:T,operator:mp,type:d.literal("assertCount")}),Gp=d.object({...k,expected:ae,locator:T,operator:wt,type:d.literal("assertValue")}),Kp=d.object({...k,attribute:d.string().min(1),expected:ae,locator:T,operator:wt,type:d.literal("assertAttribute")}),Jp=d.object({...k,locator:T,type:d.literal("assertEnabled")}),Yp=d.object({...k,locator:T,type:d.literal("assertDisabled")}),Xp=d.object({...k,expected:ae,operator:wt,type:d.literal("assertTitle")}),Qp=d.object({...k,locator:T,type:d.literal("assertChecked")}),Zp=d.object({...k,locator:T,type:d.literal("assertNotChecked")}),em=d.object({...k,locator:T,type:d.literal("assertFocused")}),tm=d.object({...k,locator:T,type:d.literal("assertNotFocused")}),rm=d.object({...k,budget:d.enum(["fast","slow","async"]),observer:d.string().min(1).max(200),params:d.record(d.string().max(200),hp),type:d.literal("assertObserver")}),nm=d.discriminatedUnion("type",[bp,vp,Sp,kp,Rp,Pp,xp,Ep,Bp,Hp,qp,Wp,zp,Gp,Kp,Jp,Yp,Cp,Tp,Ap,Ip,$p,jp,Np,Op,Dp,Lp,_p,Up,Vp,Fp,Mp,Xp,Qp,Zp,em,tm,rm]),li=d.object({entryNode:d.string().min(1).max(200),nodes:d.record(d.string().max(200),nm).refine(e=>Object.keys(e).length<=ri,`Workflow has more than ${String(ri)} nodes`),uiOnly:d.boolean().optional(),variableNamespaces:d.record(d.string().max(200),d.string().max(500)).optional(),variables:d.record(d.string().max(200),wp).optional()}),om=ti.record(ti.string().max(200),vn),im={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},sm={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},JR=bn("workflow-spec").legacy(im).initial(li).build(),YR=bn("precondition-map").legacy(sm).initial(om).build(),am=["fast","slow","async"],ci=yn.object({budget:yn.enum(am).describe("Polling budget tier: fast | slow | async"),description:yn.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",lm=".ripplo/fixtures",ui=5e3,cm=C.record(C.string().max(200),C.string().max(200)),di=C.object({coverage:C.array(C.string().max(500)).max(2e3).default([]),expectedOutcome:C.string().max(2e3),name:C.string().max(200),preconditions:C.array(C.string().max(200)).max(1e3),requiresKeys:cm,slug:C.string().max(200),sourcePath:C.string().max(500).optional(),spec:li}),um=C.object({sha256:C.string().regex(/^[0-9a-f]{64}$/u),size:C.number().int().nonnegative()}),dm=C.record(C.string().min(1).max(500),um),pm=C.object({observers:C.record(C.string().max(200),ci),preconditions:C.record(C.string().max(200),vn),tests:C.array(di).max(ui)}),mm=C.object({fixtures:dm,observers:C.record(C.string().max(200),ci),preconditions:C.record(C.string().max(200),vn),tests:C.array(di).max(ui)}),pi=bn("ripplo-lockfile").initial(pm).upgrade(mm,e=>({...e,fixtures:{}})).build();function mi(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 wn(e){let t=pi.encode(e);return`${JSON.stringify(t,hm(t),2)}
261
- `}async function Qt({cwd:e}){let t=ze.join(e,le),r=await ym(t);return r==null?null:ap(pi,r)}var ni=10*1024*1024,oi=50*1024*1024;async function ce({cwd:e,result:t}){let r=await fi({cwd:e,result:t}),n=mi(r),o=ze.join(e,le);await ht.mkdir(ze.dirname(o),{recursive:!0}),await ht.writeFile(o,wn(n),"utf8")}async function fi({cwd:e,result:t}){let r=gm(t);if(r.size===0)return{...t,fixtures:{}};let n=ze.join(e,lm),o=[...r].toSorted((a,l)=>a.localeCompare(l)),i=await Promise.all(o.map(async a=>{let l=await fm({fixturesRoot:n,name:a});if(l.size>ni)throw new Error(`Fixture "${a}" is ${String(l.size)} bytes; exceeds per-file limit of ${String(ni)} bytes`);return[a,l]}));if(i.reduce((a,[,l])=>a+l.size,0)>oi)throw new Error(`Total fixtures size exceeds limit of ${String(oi)} bytes`);return{...t,fixtures:Object.fromEntries(i)}}async function fm({fixturesRoot:e,name:t}){if(t.includes("..")||ze.isAbsolute(t))throw new Error(`Invalid fixture name "${t}": must be a path under .ripplo/fixtures/`);let r=ze.join(e,t),n=await ht.lstat(r).catch(s=>{throw gi(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:np("sha256").update(o).digest("hex"),size:o.byteLength}}function gm(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 Zt({compiled:e,cwd:t,existing:r}){if(r==null)return"missing";let n=await fi({cwd:t,result:e}),o=wn(mi(n)),i=wn(r);return o===i?"match":"stale"}async function ym(e){try{return await ht.readFile(e,"utf8")}catch(t){if(gi(t)&&t.code==="ENOENT")return null;throw t}}function gi(e){return e instanceof Error&&"code"in e}function hm(e){return function(r,n){return n===e||!wm(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function wm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import bt from"fs";import rr from"path";var Sn=["**/src/**","**/app/**","**/apps/**","**/pages/**","**/routes/**","**/components/**","**/server/**","**/api/**","**/backend/**","**/features/**","**/modules/**","**/views/**","**/ui/**","**/hooks/**","**/contexts/**","**/providers/**","**/controllers/**","**/handlers/**","**/resolvers/**","**/services/**","**/middleware/**","**/lib/**"],Ee=["**/*.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 yi(e){return e.data}function hi(e){return{as(t){return{data:{label:t,node:e}}}}}function er(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();bm(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 bm(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}=km(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[Sm(i),...s],l=Rm(a,n,e.requiresKeys,e.uiOnly),c=[];Object.keys(e.requiresKeys).length>0&&n.size===0&&e.implemented&&c.push("Test requires preconditions but never references their data \u2014 destructure and use precondition data in steps()");let m=xm(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 Sm(e){return hi({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function km(e){let t=new Set,r={};return Object.keys(e).forEach(n=>{r[n]=new Proxy({},{get(o,i){if(typeof i=="string"){let s=`${n}.${i}`;return t.add(s),`{{${s}}}`}}})}),{accessedKeys:t,vars:r}}function Rm(e,t,r,n){let o={};e.forEach((a,l)=>{let c=`step-${String(l)}`,p=l<e.length-1?`step-${String(l+1)}`:void 0;o[c]=Pm(a,c,p)});let i={};t.forEach(a=>{i[a]={default:`test-${a}`,type:"string"}});let s={...r};return{entryNode:"step-0",nodes:o,uiOnly:n,variableNamespaces:s,variables:i}}function Pm(e,t,r){let{label:n,node:o}=yi(e);return{...o,id:t,label:n,next:r}}function xm(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 aP,WebhookVerificationError as lP}from"standardwebhooks";import{z as D}from"zod";var wi=D.union([D.string(),D.number(),D.boolean()]),Em=D.record(D.string(),D.record(D.string(),wi)),uP=D.object({batch:D.array(D.object({preconditions:D.array(D.string().min(1)),runId:D.string().min(1)})).min(1)}),dP=D.object({batch:D.array(D.object({data:Em,preconditions:D.array(D.string().min(1)),runId:D.string().min(1)})).min(1)}),pP=D.object({observer:D.string().min(1).max(200),params:D.record(D.string().max(200),wi)});function Ge(e){let t=[];return e.tests.forEach(r=>{let n=Cm(r),o=i=>{t.push({...i,test:r.slug})};Ym.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function Cm(e){let t=[],r=e.spec.entryNode,n=new Set;for(;r!=null&&!n.has(r);){n.add(r);let o=e.spec.nodes[r];if(o==null)break;t.push(o),r=o.next}return t}function Tm(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 Am(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&vi(o.value)){let i=o.value.value;!Si(i)&&Lm(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 Im(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 $m(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 jm(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 Nm(e,t,r){let n=0;e.forEach((o,i)=>{if(!(i===0&&o.type==="goto")){if(Ke(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 Om(e,t,r){if(e.length===0)return;let n=e.at(-1);n!=null&&!Ke(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 Dm(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function vi(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function Si(e){return e.includes("{{")}function Lm(e){return e.includes("@")||/\b[a-f0-9]{8,}\b/.test(e)||/^(test|ripplo|example|sample|demo)/i.test(e)}function Ke(e){return e.type.startsWith("assert")}var _m=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function Um(e){return _m.has(e.type)}function Vm(e,t,r){!t.implemented||e.length===0||e.some(n=>Ke(n))||r({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function Fm(e,t,r){if(!t.implemented||e.length<=3)return;let n=e.filter(i=>Ke(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 kn(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 Mm(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=kn(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&kn(c)===i)==null||s.some(c=>Um(c)||Ke(c)&&kn(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 Bm=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 Rn(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!Bm.has(t))}function Hm(e){let t=e.label==null?[]:Rn(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,...Rn(n)]}function qm(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(Rn(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>Ke(s));if(o.length===0)return;o.some(s=>Hm(s).some(a=>n.has(a)))||r({message:`No assertion references any keyword from expectedOutcome (${[...n].join(", ")}) \u2014 the outcome may not actually be verified`,rule:"expected-outcome-keyword-coverage",step:void 0})}var Wm=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function bi(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 Wm.test(r)}function zm(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!bi(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(p=>bi(p)),a=s===-1?i.length:s;i.slice(0,a).some(p=>p.type==="assertObserver")||r({message:`"${n.label??n.id}" looks like it mutates backend state but no assert.backend(...) observer verifies it \u2014 the test can pass while the server is broken. You need to add an observer that checks the persisted result (see .ripplo/observers/ for examples). Only if this action truly does NOT change any server state (pure client-side interaction, presentation toggle, etc.) should you fall back to marking the step { uiOnly: true } to silence this rule.`,rule:"mutation-without-observer-coverage",step:n.label??n.id})})}function Gm(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])=>vi(a)&&Si(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 Km(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 Jm(e,t,r){let n=new Set(Object.keys(t.spec.variables??{})),o=/\{\{([^{}]+?)\}\}/g;e.forEach(i=>{let a=[...JSON.stringify(i).matchAll(o)],l=[...new Set(a.map(m=>m[1]).filter(m=>m!=null&&!n.has(m)))];if(l.length===0)return;let c=l.map(m=>`{{${m}}}`).join(", "),p=[...new Set(l.map(m=>m.split(".")[0]??m))].join(", ");r({message:`"${i.label??i.id}" contains literal template string(s) ${c} \u2014 destructure the proxy in .steps(({ ${p} }) => \u2026) and pass the proxy value (e.g. \`${l[0]??""}\`) directly. Writing the template as a string bypasses type-checking and silently accepts typos.`,rule:"no-literal-template-strings",step:i.label??i.id})})}var Ym=[Tm,Am,Jm,Im,$m,jm,Nm,Om,Dm,Vm,Fm,Mm,qm,zm,Gm,Km];import kf from"picomatch";import{execFileSync as Xm,spawnSync as Qm}from"child_process";function G(e,t){return Xm("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function ki(e,t){let r=Qm("git",["show",e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(r.status===0)return r.stdout;if(r.status===128)return null;throw new Error(`git show ${e} failed (${String(r.status)}): ${r.stderr}`)}import w from"typescript";import*as Ri from"remeda";var Pi=[["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"]],Zm=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),ef=[[/(?:^|[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 tr({filePath:e,source:t}){let r=w.createSourceFile(e,t,w.ScriptTarget.Latest,!0,w.ScriptKind.TSX);return r.statements.flatMap(n=>tf({filePath:e,sf:r,stmt:n}))}function tf({filePath:e,sf:t,stmt:r}){let n=nf(r);if(n==null||rf(n))return[];let o=xi(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return Ri.uniqueBy(o,i=>i.id)}function rf(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function nf(e){if(w.isExportAssignment(e))return of(e.expression);if(!sf(e))return null;if(w.isFunctionDeclaration(e)||w.isClassDeclaration(e))return e.name?.text??null;if(w.isVariableStatement(e)){let t=e.declarationList.declarations[0];return t!=null&&w.isIdentifier(t.name)?t.name.text:null}return null}function of(e){return w.isIdentifier(e)?e.text:(w.isFunctionExpression(e)||w.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function sf(e){if(!w.canHaveModifiers(e))return!1;let t=w.getModifiers(e);return t!=null&&t.some(r=>r.kind===w.SyntaxKind.ExportKeyword)}function xi(e,t){let r=af(e,t),n=e.getChildren(t).flatMap(o=>xi(o,t));return r==null?n:[r,...n]}function af(e,t){let r=lf(e);if(r==null)return null;let n=cf(r);if(n==null)return null;let o=ff(r,n);return o==null?null:{kind:n,label:o,line:Sf(t,e.getStart(t))}}function lf(e){return w.isJsxSelfClosingElement(e)&&w.isIdentifier(e.tagName)?{attrs:e.attributes,children:[],tag:e.tagName.text}:w.isJsxElement(e)&&w.isIdentifier(e.openingElement.tagName)?{attrs:e.openingElement.attributes,children:e.children,tag:e.openingElement.tagName.text}:null}function cf({attrs:e,tag:t}){let r=ue(e,"role");return r!=null?Zm.get(r)??null:df(t,e)??pf(t)??mf(e)}var uf=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 df(e,t){return uf.get(e)?.(t)??null}function pf(e){return/^[A-Z]/.test(e)?ef.find(([t])=>t.test(e))?.[1]??null:null}function mf(e){return Pi.find(([t])=>hf(e,t))?.[1]??null}function ff({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")??(gf(r)?void 0:vf(t))??yf(e,n)}function gf(e){return e==="input"||e==="textarea"||e==="select"}function yf(e,t){let r=Pi.find(([,o])=>o===t)?.[0];if(r==null)return;let n=wf(e,r);if(n!=null){if(w.isIdentifier(n))return n.text;if(w.isArrowFunction(n)||w.isFunctionExpression(n))return Ei(n.body)}}function Ei(e){if(w.isCallExpression(e)){let t=e.expression;return w.isIdentifier(t)?t.text:w.isPropertyAccessExpression(t)?t.name.text:void 0}return w.forEachChild(e,Ei)}function hf(e,t){return e.properties.some(r=>w.isJsxAttribute(r)&&w.isIdentifier(r.name)&&r.name.text===t)}function Ci(e,t){return e.properties.find(r=>w.isJsxAttribute(r)&&w.isIdentifier(r.name)&&r.name.text===t)}function ue(e,t){let r=Ci(e,t);return r==null?void 0:bf(r.initializer)}function wf(e,t){let r=Ci(e,t);if(!(r?.initializer==null||!w.isJsxExpression(r.initializer)))return r.initializer.expression}function bf(e){if(e==null)return"";if(w.isStringLiteral(e))return e.text;if(w.isJsxExpression(e))return Ai(e.expression)}function vf(e){let t=e.flatMap(r=>Ti(r)).join(" ").trim();return t.length===0?void 0:t}function Ti(e){if(w.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(w.isJsxExpression(e)){let t=Ai(e.expression);return t==null?[]:[t]}return w.isJsxElement(e)?e.children.flatMap(t=>Ti(t)):[]}function Ai(e){if(e!=null){if(w.isStringLiteral(e)||w.isNoSubstitutionTemplateLiteral(e))return e.text;if(w.isCallExpression(e)&&e.arguments.length===1){let t=e.arguments[0];if(t!=null&&(w.isStringLiteral(t)||w.isNoSubstitutionTemplateLiteral(t)))return t.text}}}function Sf(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var Rf=rr.join(".ripplo","coverage.d.ts");function Je({cwd:e}){Pf({cwd:e,ignorePaths:Ee})}function Pf({cwd:e,ignorePaths:t}){let r=Ye({cwd:e,ignorePaths:t});Cf({content:Ef(r),cwd:e})}function Ye({cwd:e,ignorePaths:t}){let n=xf({cwd:e,ignorePaths:t}).flatMap(o=>Pn({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function xf({cwd:e,ignorePaths:t}){let r=G(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=kf([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>bt.existsSync(rr.join(e,o)))}function Pn({cwd:e,file:t}){let r=bt.readFileSync(rr.join(e,t),"utf8");return tr({filePath:t,source:r}).map(n=>n.id)}function Ef(e){let t=`// GENERATED \u2014 do not edit
255
+ `:`${i}, ${fp(n)}.
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 fp(e){let t=e.name.trim().split(/\s+/)[0];return t!=null&&t.length>0?t:e.email}async function hn({serverUrl:e,token:t}){try{let n=(await h({config:Pe({serverUrl:e,token:t}),document:mp,variables:void 0})).currentUser;return n==null?null:{email:n.email,name:n.name}}catch{return null}}async function ii(){let e=ie();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let t=ee(),r=await hn({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 si(){if(!ln()){process.stdout.write(`No token to remove.
259
+ `);return}process.stdout.write(`Removed ${ke("token")}
260
+ `)}import{createHash as gp}from"crypto";import ht from"fs/promises";import We from"path";import{z as Xt}from"zod";import{z as ai}from"zod";import{z as He}from"zod";import{z as p}from"zod";import{z as Re}from"zod";import{z as mi}from"zod";import{z as D}from"zod";import{z as te}from"zod";import{z as wn}from"zod";import{z as C}from"zod";var yp=Xt.object({__codec:Xt.string().min(1),data:Xt.unknown(),version:Xt.number().int().positive()}),hp=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}},wp=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function Sn(e){return di({legacy:void 0,migrators:[],name:e,schemas:[]})}function bp(e,t){let r=JSON.parse(t);return e.decode(r)}function di(e){return{initial:t=>bn(t,{...e,schemas:[t]}),legacy:t=>di({...e,legacy:t})}}function bn(e,t){return{build:()=>vp(e,t),legacy:r=>bn(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return bn(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function vp(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Sp(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Sp(e,t,r){let{data:n,version:o}=kp(t,r),i=pi(t,n,o);return e.parse(i)}function kp(e,t){let r=yp.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new wp({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 pi(e,t,r){let n=e.schemas.length;if(r>n)throw new hp({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 pi(e,s(i),r+1)}var kn=He.object({depends:He.array(He.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:He.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:He.array(He.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name."),Pp=Re.object({by:Re.literal("testId"),value:Re.string().min(1)}),Rp=Re.object({by:Re.literal("role"),name:Re.string().optional(),role:Re.string().min(1)}),T=Re.discriminatedUnion("by",[Pp,Rp]),wt=mi.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),xp=mi.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),Ep=D.object({type:D.literal("static"),value:D.union([D.string(),D.number(),D.boolean()])}),Yt=D.object({name:D.string().min(1),type:D.literal("variable")}),Cp=D.discriminatedUnion("type",[Ep,Yt]),ae=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.string()}),Yt]),Tp=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.number().int().nonnegative()}),Yt]),Ap=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.union([D.string(),D.number(),D.boolean()])}),Yt]),Ip=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()},li=500,$p=p.object({...k,type:p.literal("goto"),url:ae}),jp=p.object({...k,locator:T,modifier:p.enum(["Alt","Control","Meta","Shift"]).optional(),type:p.literal("click")}),Np=p.object({...k,locator:T,type:p.literal("fill"),value:ae}),Dp=p.object({...k,locator:T,type:p.literal("select"),value:ae}),Op=p.object({...k,locator:T,type:p.literal("hover")}),Lp=p.object({...k,key:p.string().min(1),locator:T.optional(),type:p.literal("press")}),_p=p.object({...k,locator:T,type:p.literal("check")}),Up=p.object({...k,locator:T,type:p.literal("uncheck")}),Vp=p.object({...k,height:p.number().int().positive(),type:p.literal("setViewport"),width:p.number().int().positive()}),Fp=p.object({...k,message:p.string().min(1),type:p.literal("fail")}),Mp=p.object({...k,type:p.literal("setVariable"),value:Cp,variable:p.string().min(1)}),Bp=p.object({...k,locator:T,type:p.literal("extractText"),variable:p.string().min(1)}),Hp=p.object({...k,files:p.array(p.string()).min(1),locator:T,type:p.literal("upload")}),Wp=p.object({...k,locator:T,type:p.literal("dblclick")}),qp=p.object({...k,source:T,target:T,type:p.literal("drag")}),zp=p.object({...k,locator:T,type:p.literal("scrollIntoView")}),Gp=p.object({...k,locator:T,type:p.literal("type"),value:ae}),Kp=p.object({...k,locator:T,type:p.literal("focus")}),Jp=p.object({...k,locator:T,type:p.literal("clear")}),Xp=p.object({...k,locator:T,type:p.literal("rightClick")}),Yp=p.object({...k,action:p.enum(["accept","dismiss"]),promptText:p.string().optional(),type:p.literal("handleDialog")}),Qp=p.object({...k,action:p.enum(["read","write"]),type:p.literal("clipboard"),value:ae.optional(),variable:p.string().min(1).optional()}),Zp=p.object({...k,permission:p.string().min(1),state:p.enum(["granted","prompt"]),type:p.literal("setPermission")}),em=p.object({...k,locator:T,type:p.literal("assertVisible")}),tm=p.object({...k,locator:T,type:p.literal("assertNotVisible")}),rm=p.object({...k,expected:ae,locator:T,operator:wt,type:p.literal("assertText")}),nm=p.object({...k,expected:ae,operator:wt,type:p.literal("assertUrl")}),om=p.object({...k,expected:Tp,locator:T,operator:xp,type:p.literal("assertCount")}),im=p.object({...k,expected:ae,locator:T,operator:wt,type:p.literal("assertValue")}),sm=p.object({...k,attribute:p.string().min(1),expected:ae,locator:T,operator:wt,type:p.literal("assertAttribute")}),am=p.object({...k,locator:T,type:p.literal("assertEnabled")}),lm=p.object({...k,locator:T,type:p.literal("assertDisabled")}),cm=p.object({...k,expected:ae,operator:wt,type:p.literal("assertTitle")}),um=p.object({...k,locator:T,type:p.literal("assertChecked")}),dm=p.object({...k,locator:T,type:p.literal("assertNotChecked")}),pm=p.object({...k,locator:T,type:p.literal("assertFocused")}),mm=p.object({...k,locator:T,type:p.literal("assertNotFocused")}),fm=p.object({...k,budget:p.enum(["fast","slow","async"]),observer:p.string().min(1).max(200),params:p.record(p.string().max(200),Ap),type:p.literal("assertObserver")}),gm=p.discriminatedUnion("type",[$p,jp,Np,Dp,Op,Lp,_p,Up,em,tm,rm,nm,om,im,sm,am,lm,Vp,Fp,Mp,Bp,Hp,Wp,qp,zp,Gp,Kp,Jp,Xp,Yp,Qp,Zp,cm,um,dm,pm,mm,fm]),fi=p.object({entryNode:p.string().min(1).max(200),nodes:p.record(p.string().max(200),gm).refine(e=>Object.keys(e).length<=li,`Workflow has more than ${String(li)} nodes`),uiOnly:p.boolean().optional(),variableNamespaces:p.record(p.string().max(200),p.string().max(500)).optional(),variables:p.record(p.string().max(200),Ip).optional()}),ym=ai.record(ai.string().max(200),kn),hm={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},wm={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},pR=Sn("workflow-spec").legacy(hm).initial(fi).build(),mR=Sn("precondition-map").legacy(wm).initial(ym).build(),bm=["fast","slow","async"],gi=wn.object({budget:wn.enum(bm).describe("Polling budget tier: fast | slow | async"),description:wn.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",vm=".ripplo/fixtures",yi=5e3,Sm=C.record(C.string().max(200),C.string().max(200)),hi=C.object({coverage:C.array(C.string().max(500)).max(2e3).default([]),expectedOutcome:C.string().max(2e3),name:C.string().max(200),preconditions:C.array(C.string().max(200)).max(1e3),requiresKeys:Sm,slug:C.string().max(200),sourcePath:C.string().max(500).optional(),spec:fi}),km=C.object({sha256:C.string().regex(/^[0-9a-f]{64}$/u),size:C.number().int().nonnegative()}),Pm=C.record(C.string().min(1).max(500),km),Rm=C.object({observers:C.record(C.string().max(200),gi),preconditions:C.record(C.string().max(200),kn),tests:C.array(hi).max(yi)}),xm=C.object({fixtures:Pm,observers:C.record(C.string().max(200),gi),preconditions:C.record(C.string().max(200),kn),tests:C.array(hi).max(yi)}),wi=Sn("ripplo-lockfile").initial(Rm).upgrade(xm,e=>({...e,fixtures:{}})).build();function bi(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 vn(e){let t=wi.encode(e);return`${JSON.stringify(t,Am(t),2)}
261
+ `}async function Qt({cwd:e}){let t=We.join(e,le),r=await Tm(t);return r==null?null:bp(wi,r)}var ci=10*1024*1024,ui=50*1024*1024;async function ce({cwd:e,result:t}){let r=await vi({cwd:e,result:t}),n=bi(r),o=We.join(e,le);await ht.mkdir(We.dirname(o),{recursive:!0}),await ht.writeFile(o,vn(n),"utf8")}async function vi({cwd:e,result:t}){let r=Cm(t);if(r.size===0)return{...t,fixtures:{}};let n=We.join(e,vm),o=[...r].toSorted((a,l)=>a.localeCompare(l)),i=await Promise.all(o.map(async a=>{let l=await Em({fixturesRoot:n,name:a});if(l.size>ci)throw new Error(`Fixture "${a}" is ${String(l.size)} bytes; exceeds per-file limit of ${String(ci)} bytes`);return[a,l]}));if(i.reduce((a,[,l])=>a+l.size,0)>ui)throw new Error(`Total fixtures size exceeds limit of ${String(ui)} bytes`);return{...t,fixtures:Object.fromEntries(i)}}async function Em({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 Si(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:gp("sha256").update(o).digest("hex"),size:o.byteLength}}function Cm(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 Zt({compiled:e,cwd:t,existing:r}){if(r==null)return"missing";let n=await vi({cwd:t,result:e}),o=vn(bi(n)),i=vn(r);return o===i?"match":"stale"}async function Tm(e){try{return await ht.readFile(e,"utf8")}catch(t){if(Si(t)&&t.code==="ENOENT")return null;throw t}}function Si(e){return e instanceof Error&&"code"in e}function Am(e){return function(r,n){return n===e||!Im(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function Im(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import bt from"fs";import rr from"path";var Pn=["**/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 ki(e){return e.data}function Pi(e){return{as(t){return{data:{label:t,node:e}}}}}function er(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();$m(n);let o={};t.forEach(a=>{o[a.name]={depends:[...a.dependsOn],description:a.description,returns:[...a.returns]}});let i={};r.forEach(a=>{i[a.name]={budget:a.budget,description:a.description}});let s=n.map(a=>jm(a,t));return{fixtures:{},observers:i,preconditions:o,tests:s}}function $m(e){let t=new Map;e.forEach(r=>{let n=t.get(r.id);if(n!=null)throw new Error(`Duplicate test id "${r.id}" used by "${n}" and "${r.name}"`);t.set(r.id,r.name)})}function jm(e,t){let r=e.id,{accessedKeys:n,vars:o}=Dm(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[Nm(i),...s],l=Om(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=_m(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 Nm(e){return Pi({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function Dm(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 Om(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]=Lm(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 Lm(e,t,r){let{label:n,node:o}=ki(e);return{...o,id:t,label:n,next:r}}function _m(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 RR,WebhookVerificationError as xR}from"standardwebhooks";import{z as L}from"zod";var Ri=L.union([L.string(),L.number(),L.boolean()]),Um=L.record(L.string(),L.record(L.string(),Ri)),CR=L.object({batch:L.array(L.object({preconditions:L.array(L.string().min(1)),runId:L.string().min(1)})).min(1)}),TR=L.object({batch:L.array(L.object({data:Um,preconditions:L.array(L.string().min(1)),runId:L.string().min(1)})).min(1)}),AR=L.object({observer:L.string().min(1).max(200),params:L.record(L.string().max(200),Ri)});function qe(e){let t=[];return e.tests.forEach(r=>{let n=Vm(r),o=i=>{t.push({...i,test:r.slug})};cf.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function Vm(e){let t=[],r=e.spec.entryNode,n=new Set;for(;r!=null&&!n.has(r);){n.add(r);let o=e.spec.nodes[r];if(o==null)break;t.push(o),r=o.next}return t}function Fm(e,t,r){e.forEach(n=>{n.type==="assertText"&&"operator"in n&&n.operator!=="equals"&&r({message:`${n.type} uses operator "${n.operator}" \u2014 only "equals" is allowed for determinism`,rule:"exact-text-match",step:n.label??n.id})})}function Mm(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&Ei(o.value)){let i=o.value.value;!Ci(i)&&Km(i)&&r({message:`fill() uses hardcoded value "${i}" \u2014 consider using precondition data via {{namespace.key}}`,rule:"no-hardcoded-data",step:o.label??o.id})}})}function Bm(e,t,r){if(Object.keys(t.spec.variables??{}).length===0)return;e.some(i=>JSON.stringify(i).includes("{{"))||r({message:"Test requires preconditions but steps() never references precondition data \u2014 destructure and use it",rule:"prefer-precondition-data",step:void 0})}function Hm(e,t,r){e.forEach(n=>{(n.label==null||n.label.length===0)&&r({message:`Step "${n.id}" lacks .as("...") label \u2014 every step must be labeled`,rule:"missing-label",step:n.id})})}function Wm(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 Gm(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function Ei(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function Ci(e){return e.includes("{{")}function Km(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 Jm=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function Xm(e){return Jm.has(e.type)}function Ym(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 Qm(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 Rn(e){if(!("locator"in e)||e.locator==null)return;let t=e.locator;return t.by==="role"?`role:${t.role}:${t.name??""}`:`testId:${t.value}`}function Zm(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=Rn(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&Rn(c)===i)==null||s.some(c=>Xm(c)||ze(c)&&Rn(c)!==i)||r({message:`click "${n.label??n.id}" is followed only by assert.visible on the same locator \u2014 verifies nothing about the click's effect`,rule:"tautological-post-click-assert",step:n.label??n.id})})}var ef=new Set(["the","is","a","an","and","or","of","to","in","on","at","for","that","this","with","be","are","was","were","it","its","as","by","from","after","before","should","will","can","still","but","not","no","so","if","then","than","user","users","page","view","shows","show","see","click","clicks","clicked","clickable","visible","appears","appear","displayed","stays","remains"]);function xn(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!ef.has(t))}function tf(e){let t=e.label==null?[]:xn(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,...xn(n)]}function rf(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(xn(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>ze(s));if(o.length===0)return;o.some(s=>tf(s).some(a=>n.has(a)))||r({message:`No assertion references any keyword from expectedOutcome (${[...n].join(", ")}) \u2014 the outcome may not actually be verified`,rule:"expected-outcome-keyword-coverage",step:void 0})}var nf=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function xi(e){if(e.type==="upload")return!0;if(e.type!=="click")return!1;let t=e.locator,r=t.by==="role"?t.name??"":t.value;return nf.test(r)}function of(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!xi(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(u=>xi(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 sf(e,t,r){Object.keys(t.spec.variables??{}).length!==0&&e.forEach(o=>{if(o.type!=="assertObserver")return;let i=Object.entries(o.params);i.length===0||i.some(([,a])=>Ei(a)&&Ci(a.value))||r({message:`assert.backend "${o.label??o.id}" passes only hardcoded params while the test defines precondition variables \u2014 observer assertions should reference {{namespace.key}} so they match the actual precondition data`,rule:"observer-params-reference-variables",step:o.label??o.id})})}function af(e,t,r){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 lf(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 cf=[Fm,Mm,lf,Bm,Hm,Wm,qm,zm,Gm,Ym,Qm,Zm,rf,of,sf,af];import Df from"picomatch";import{execFileSync as uf,spawnSync as df}from"child_process";function K(e,t){return uf("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function Ti(e,t){let r=df("git",["show",e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(r.status===0)return r.stdout;if(r.status===128)return null;throw new Error(`git show ${e} failed (${String(r.status)}): ${r.stderr}`)}import b from"typescript";import*as Ai from"remeda";var Ii=[["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"]],pf=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),mf=[[/(?:^|[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 tr({filePath:e,source:t}){let r=b.createSourceFile(e,t,b.ScriptTarget.Latest,!0,b.ScriptKind.TSX);return r.statements.flatMap(n=>ff({filePath:e,sf:r,stmt:n}))}function ff({filePath:e,sf:t,stmt:r}){let n=yf(r);if(n==null||gf(n))return[];let o=$i(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return Ai.uniqueBy(o,i=>i.id)}function gf(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function yf(e){if(b.isExportAssignment(e))return hf(e.expression);if(!wf(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 hf(e){return b.isIdentifier(e)?e.text:(b.isFunctionExpression(e)||b.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function wf(e){if(!b.canHaveModifiers(e))return!1;let t=b.getModifiers(e);return t!=null&&t.some(r=>r.kind===b.SyntaxKind.ExportKeyword)}function $i(e,t){let r=bf(e,t),n=e.getChildren(t).flatMap(o=>$i(o,t));return r==null?n:[r,...n]}function bf(e,t){let r=vf(e);if(r==null)return null;let n=Sf(r);if(n==null)return null;let o=Ef(r,n);return o==null?null:{kind:n,label:o,line:Nf(t,e.getStart(t))}}function vf(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 Sf({attrs:e,tag:t}){let r=ue(e,"role");return r!=null?pf.get(r)??null:Pf(t,e)??Rf(t)??xf(e)}var kf=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 Pf(e,t){return kf.get(e)?.(t)??null}function Rf(e){return/^[A-Z]/.test(e)?mf.find(([t])=>t.test(e))?.[1]??null:null}function xf(e){return Ii.find(([t])=>Af(e,t))?.[1]??null}function Ef({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")??(Cf(r)?void 0:jf(t))??Tf(e,n)}function Cf(e){return e==="input"||e==="textarea"||e==="select"}function Tf(e,t){let r=Ii.find(([,o])=>o===t)?.[0];if(r==null)return;let n=If(e,r);if(n!=null){if(b.isIdentifier(n))return n.text;if(b.isArrowFunction(n)||b.isFunctionExpression(n))return ji(n.body)}}function ji(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,ji)}function Af(e,t){return e.properties.some(r=>b.isJsxAttribute(r)&&b.isIdentifier(r.name)&&r.name.text===t)}function Ni(e,t){return e.properties.find(r=>b.isJsxAttribute(r)&&b.isIdentifier(r.name)&&r.name.text===t)}function ue(e,t){let r=Ni(e,t);return r==null?void 0:$f(r.initializer)}function If(e,t){let r=Ni(e,t);if(!(r?.initializer==null||!b.isJsxExpression(r.initializer)))return r.initializer.expression}function $f(e){if(e==null)return"";if(b.isStringLiteral(e))return e.text;if(b.isJsxExpression(e))return Oi(e.expression)}function jf(e){let t=e.flatMap(r=>Di(r)).join(" ").trim();return t.length===0?void 0:t}function Di(e){if(b.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(b.isJsxExpression(e)){let t=Oi(e.expression);return t==null?[]:[t]}return b.isJsxElement(e)?e.children.flatMap(t=>Di(t)):[]}function Oi(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 Nf(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var Of=rr.join(".ripplo","coverage.d.ts");function Ge({cwd:e}){Lf({cwd:e,ignorePaths:xe})}function Lf({cwd:e,ignorePaths:t}){let r=Ke({cwd:e,ignorePaths:t});Vf({content:Uf(r),cwd:e})}function Ke({cwd:e,ignorePaths:t}){let n=_f({cwd:e,ignorePaths:t}).flatMap(o=>En({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function _f({cwd:e,ignorePaths:t}){let r=K(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=Df([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>bt.existsSync(rr.join(e,o)))}function En({cwd:e,file:t}){let r=bt.readFileSync(rr.join(e,t),"utf8");return tr({filePath:t,source:r}).map(n=>n.id)}function Uf(e){let t=`// GENERATED \u2014 do not edit
262
262
  import "@ripplo/testing";
263
263
 
264
264
  declare module "@ripplo/testing" {
@@ -269,22 +269,23 @@ declare module "@ripplo/testing" {
269
269
  `:`${t}${r}
270
270
  }
271
271
  }
272
- `}function Cf({content:e,cwd:t}){let r=rr.join(t,Rf);bt.existsSync(r)&&bt.readFileSync(r,"utf8")===e||bt.writeFileSync(r,e)}import Ii from"path";import{createJiti as Tf}from"jiti";var Af=["getObservers","getPreconditions","getTests","getUnimplemented"];function If(e){return e==null||typeof e!="object"?!1:Af.every(t=>typeof Reflect.get(e,t)=="function")}function $f(e){return e===null?"null":Array.isArray(e)?"array":typeof e}async function P(e){let t=Ii.join(e,".ripplo","index.ts"),r=Ii.join(e,".ripplo");try{let o=await Tf(import.meta.url,{moduleCache:!1,sourceMaps:!0}).import(t),i=o!=null&&typeof o=="object"&&"default"in o?Reflect.get(o,"default"):o;if(!If(i))return{error:`${t} must default-export a RipploBuilder (got ${$f(i)})`,ok:!1};let s=er(i);return{builder:i,ok:!0,result:s}}catch(n){return{error:Nf(n,r),ok:!1}}}var jf=/\(?([^\s()]{1,500}\.ts):(\d{1,10}):(\d{1,10})\)?$/;function Nf(e,t){if(!(e instanceof Error))return String(e);let r=Of(e.stack,t);return r==null?e.message:`${r} \u2014 ${e.message}`}function Of(e,t){if(e==null)return;let n=e.split(`
273
- `).map(a=>jf.exec(a)).find(a=>a!=null&&a[1]!=null&&a[2]!=null&&a[3]!=null&&a[1].startsWith(t));if(n==null)return;let[,o,i,s]=n;return`${o??""}:${i??""}:${s??""}`}function h(e,t){return t==null?`Load \`/ripplo:${e}\` skill for instructions.`:`Load \`/ripplo:${e}\` skill for instructions on ${t}.`}function $i(e){return e.length===1?h(e[0]):`REQUIRED before proceeding: load ${e.map(r=>`\`/ripplo:${r}\``).join(" AND ")} skills (load every one \u2014 each carries rules the others don't).`}async function ji(e){let t=process.cwd(),r=await P(t);if(r.ok||(process.stderr.write(`Compilation failed: ${r.error}
274
- `),process.stderr.write(`${h("create","DSL authoring + lint rules")}
272
+ `}function Vf({content:e,cwd:t}){let r=rr.join(t,Of);bt.existsSync(r)&&bt.readFileSync(r,"utf8")===e||bt.writeFileSync(r,e)}import{readdir as Ff,stat as Mf}from"fs/promises";import vt from"path";import{createJiti as Bf}from"jiti";var Hf=["getObservers","getPreconditions","getTests","getUnimplemented"];function Wf(e){return e==null||typeof e!="object"?!1:Hf.every(t=>typeof Reflect.get(e,t)=="function")}function qf(e){return e===null?"null":Array.isArray(e)?"array":typeof e}var zf=new Set(["debug",".local"]),Li=new Map;async function P(e){let t=vt.join(e,".ripplo","index.ts"),r=vt.join(e,".ripplo"),n=await Kf(r),o=Li.get(e);if(o!=null&&o.fingerprint===n)return o.result;let i=await Gf(t,r);return Li.set(e,{fingerprint:n,result:i}),i}async function Gf(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 Wf(o)?{builder:o,ok:!0,result:er(o)}:{error:`${e} must default-export a RipploBuilder (got ${qf(o)})`,ok:!1}}catch(r){return{error:Xf(r,t),ok:!1}}}async function Kf(e){let t=[];return await _i(e,e,t),t.sort((r,n)=>r.localeCompare(n)),t.join(`
273
+ `)}async function _i(e,t,r){let n=await Ff(t,{withFileTypes:!0}).catch(()=>[]);await Promise.all(n.map(async o=>{if(o.isDirectory()){if(zf.has(o.name))return;await _i(e,vt.join(t,o.name),r);return}let i=vt.join(t,o.name),s=await Mf(i).catch(()=>{});s!=null&&r.push(`${vt.relative(e,i)}:${String(s.mtimeMs)}:${String(s.size)}`)}))}var Jf=/\(?([^\s()]{1,500}\.ts):(\d{1,10}):(\d{1,10})\)?$/;function Xf(e,t){if(!(e instanceof Error))return String(e);let r=Yf(e.stack,t);return r==null?e.message:`${r} \u2014 ${e.message}`}function Yf(e,t){if(e==null)return;let n=e.split(`
274
+ `).map(a=>Jf.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 Ui(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 Vi(e){let t=process.cwd(),r=await P(t);if(r.ok||(process.stderr.write(`Compilation failed: ${r.error}
275
+ `),process.stderr.write(`${w("create","DSL authoring + lint rules")}
275
276
  `),process.exit(1)),e.check){let n=await Qt({cwd:t}),o=await Zt({compiled:r.result,cwd:t,existing:n});if(o==="match"){process.stdout.write(`${le} is up to date
276
277
  `);return}let i=o==="missing"?"missing":"out of date";process.stderr.write(`${le} is ${i} \u2014 run \`ripplo compile\` and commit the result
277
- `),process.stderr.write(`${h("setup")}
278
- `),process.exit(1)}await ce({cwd:t,result:r.result}),Je({cwd:t}),process.stdout.write(`wrote ${le}
279
- `)}import me from"process";import Df from"fs";import Lf from"path";import _f from"picomatch";function Ni({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Ye({cwd:t,ignorePaths:r})),o=Li(e),i=Uf({cwd:t,ignorePaths:r});return Di({acknowledged:o,allStatements:n,unacked:i})}function Oi({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Ye({cwd:t,ignorePaths:r})),o=Li(e);return Di({acknowledged:o,allStatements:n,unacked:n})}function Di({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 Li(e){return new Set(e.tests.flatMap(t=>t.coverage))}function Uf({cwd:e,ignorePaths:t}){let r=Vf({cwd:e,ignorePaths:t}),n=new Set(r.flatMap(i=>Ff({cwd:e,file:i}))),o=new Set(r.flatMap(i=>Mf({cwd:e,file:i})?Pn({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function Vf({cwd:e,ignorePaths:t}){let r=G(["diff","--name-only","HEAD","-z"],e),n=G(["ls-files","--others","--exclude-standard","-z"],e),o=_f([...t]);return[...new Set([...r.split("\0"),...n.split("\0")])].filter(i=>i.length>0&&/\.(tsx|jsx)$/.test(i)).filter(i=>!o(i))}function Ff({cwd:e,file:t}){let r=ki(`HEAD:${t}`,e);return r==null?[]:tr({filePath:t,source:r}).map(n=>n.id)}function Mf({cwd:e,file:t}){return Df.existsSync(Lf.join(e,t))}async function _i(){let e=me.cwd(),t=await P(e);t.ok||(me.stderr.write(`Compilation failed: ${t.error}
280
- `),me.exit(1));let r=Ye({cwd:e,ignorePaths:Ee}),n=Oi({compileResult:t.result,cwd:e,ignorePaths:Ee}),o=n.filter(a=>a.kind==="unacknowledged"),i=n.filter(a=>a.kind==="stale"),s=r.length-o.length;me.stdout.write(`Coverage: ${String(s)}/${String(r.length)} statements acknowledged
281
- `),o.length>0&&(me.stdout.write(`
278
+ `),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 Qf from"fs";import Zf from"path";import eg from"picomatch";function Fi({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Ke({cwd:t,ignorePaths:r})),o=Hi(e),i=tg({cwd:t,ignorePaths:r});return Bi({acknowledged:o,allStatements:n,unacked:i})}function Mi({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Ke({cwd:t,ignorePaths:r})),o=Hi(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 Hi(e){return new Set(e.tests.flatMap(t=>t.coverage))}function tg({cwd:e,ignorePaths:t}){let r=rg({cwd:e,ignorePaths:t}),n=new Set(r.flatMap(i=>ng({cwd:e,file:i}))),o=new Set(r.flatMap(i=>og({cwd:e,file:i})?En({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function rg({cwd:e,ignorePaths:t}){let r=K(["diff","--name-only","HEAD","-z"],e),n=K(["ls-files","--others","--exclude-standard","-z"],e),o=eg([...t]);return[...new Set([...r.split("\0"),...n.split("\0")])].filter(i=>i.length>0&&/\.(tsx|jsx)$/.test(i)).filter(i=>!o(i))}function ng({cwd:e,file:t}){let r=Ti(`HEAD:${t}`,e);return r==null?[]:tr({filePath:t,source:r}).map(n=>n.id)}function og({cwd:e,file:t}){return Qf.existsSync(Zf.join(e,t))}async function Wi(){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=Mi({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
+ `),o.length>0&&(fe.stdout.write(`
282
283
  Unacknowledged (${String(o.length)}):
283
- `),o.forEach(a=>me.stdout.write(` ${a.id}
284
- `))),i.length>0&&(me.stdout.write(`
284
+ `),o.forEach(a=>fe.stdout.write(` ${a.id}
285
+ `))),i.length>0&&(fe.stdout.write(`
285
286
  Stale claims (${String(i.length)}):
286
- `),i.forEach(a=>me.stdout.write(` ${a.id}
287
- `))),n.length>0&&me.exit(1)}import{graphql as Jf}from"gql.tada";import Ui from"fs";import xn from"path";function Vi(e){let t=Ui.realpathSync(e),r=t,n=xn.dirname(r);for(;n!==r;){if(Ui.existsSync(xn.join(r,".git")))return r;r=n,n=xn.dirname(r)}return t}function B(e){let t=un(e),r=qe(),n=ie();if(n==null)throw new Error("ripplo: not authenticated. Run `ripplo auth login`.");return{appUrl:r.appUrl,cwd:Vi(e),engineUrl:r.engineUrl,projectId:Jo()??t.projectId,ripploServerUrl:ee(),token:n,webhookSecret:r.webhookSecret}}import fe from"fs";var Bf="dev.pid";function Mi(e){return mt(e,Bf)}function Qe(e){let t=Mi(e);if(!fe.existsSync(t))return!1;let r=fe.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 Bi(e){pt(e);let t=Mi(e);Hf({cwd:e,path:t});let r=!1;return()=>{if(!r){r=!0;try{let n=fe.readFileSync(t,"utf8").trim();Number.parseInt(n,10)===process.pid&&fe.unlinkSync(t)}catch{}}}}function Hf({cwd:e,path:t}){let r=()=>{try{let o=fe.openSync(t,"wx");return fe.writeSync(o,String(process.pid)),fe.closeSync(o),"ok"}catch(o){if(!qf(o))throw o;let i=Fi(t);if(i!=null&&Wf(i))throw new Xe({cwd:e,pid:i});return fe.unlinkSync(t),"retry"}};if(r()==="ok"||r()==="ok")return;let n=Fi(t);throw n!=null?new Xe({cwd:e,pid:n}):new Error("failed to acquire dev lock")}function qf(e){if(!(e instanceof Error)||!("code"in e))return!1;let{code:t}=e;return t==="EEXIST"}function Fi(e){try{let t=fe.readFileSync(e,"utf8").trim(),r=Number.parseInt(t,10);return Number.isFinite(r)&&r>0?r:null}catch{return null}}function Wf(e){try{return process.kill(e,0),!0}catch{return!1}}import zf from"fs";import En from"path";var Gf=["MERGE_HEAD","rebase-merge","rebase-apply","CHERRY_PICK_HEAD","REVERT_HEAD"];function nr(e){let t=Kf(e);return t==null?!1:Gf.some(r=>zf.existsSync(En.join(t,r)))}function Kf(e){try{let t=G(["rev-parse","--git-dir"],e).trim();return t.length===0?null:En.isAbsolute(t)?t:En.resolve(e,t)}catch{return null}}var Yf=Jf(`
287
+ `),i.forEach(a=>fe.stdout.write(` ${a.id}
288
+ `))),n.length>0&&fe.exit(1)}import{graphql as pg}from"gql.tada";import qi from"fs";import Cn from"path";function zi(e){let t=qi.realpathSync(e),r=t,n=Cn.dirname(r);for(;n!==r;){if(qi.existsSync(Cn.join(r,".git")))return r;r=n,n=Cn.dirname(r)}return t}function W(e){let t=pn(e),r=Be(),n=ie();if(n==null)throw new Error("ripplo: not authenticated. Run `ripplo auth login`.");return{appUrl:r.appUrl,cwd:zi(e),engineUrl:r.engineUrl,projectId:ti()??t.projectId,ripploServerUrl:ee(),token:n,webhookSecret:r.webhookSecret}}import ge from"fs";var ig="dev.pid";function Ki(e){return mt(e,ig)}function Xe(e){let t=Ki(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 Ji(e){pt(e);let t=Ki(e);sg({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 sg({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(!ag(o))throw o;let i=Gi(t);if(i!=null&&lg(i))throw new Je({cwd:e,pid:i});return ge.unlinkSync(t),"retry"}};if(r()==="ok"||r()==="ok")return;let n=Gi(t);throw n!=null?new Je({cwd:e,pid:n}):new Error("failed to acquire dev lock")}function ag(e){if(!(e instanceof Error)||!("code"in e))return!1;let{code:t}=e;return t==="EEXIST"}function Gi(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 lg(e){try{return process.kill(e,0),!0}catch{return!1}}import cg from"fs";import Tn from"path";var ug=["MERGE_HEAD","rebase-merge","rebase-apply","CHERRY_PICK_HEAD","REVERT_HEAD"];function nr(e){let t=dg(e);return t==null?!1:ug.some(r=>cg.existsSync(Tn.join(t,r)))}function dg(e){try{let t=K(["rev-parse","--git-dir"],e).trim();return t.length===0?null:Tn.isAbsolute(t)?t:Tn.resolve(e,t)}catch{return null}}var mg=pg(`
288
289
  query DevSessionCheckHealth($projectId: String!, $cwd: String!) {
289
290
  project(id: $projectId) {
290
291
  id
@@ -293,25 +294,25 @@ Stale claims (${String(i.length)}):
293
294
  }
294
295
  }
295
296
  }
296
- `);function Hi(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=Qe(e),r=nr(e),n;try{n=B(e)}catch{return{gitMidOperation:r,status:t?"starting":"missing",type:"dev-session"}}return(await y({config:n,document:Yf,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 Wi(e){switch(e.type){case"settings":return eg(e);case"env-files":return tg(e);case"token":return rg(e);case"dev-server":return ng(e);case"dev-session":return Hi(e);case"preconditions":return sg(e);case"webhook-verification":return og(e);case"preconditions-validation":return ag(e);case"workflows":return lg(e);case"browser":return ig(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 Xf(e);case"lockfile":return Qf(e);case"pre-commit-hook":return Zf(e)}}function Xf(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 Qf(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 Zf(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 eg(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function tg(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
297
+ `);function Xi(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 Yi(e){let t=Xe(e),r=nr(e),n;try{n=W(e)}catch{return{gitMidOperation:r,status:t?"starting":"missing",type:"dev-session"}}return(await h({config:n,document:mg,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 Qi(e){switch(e.type){case"settings":return hg(e);case"env-files":return wg(e);case"token":return bg(e);case"dev-server":return vg(e);case"dev-session":return Xi(e);case"preconditions":return Pg(e);case"webhook-verification":return Sg(e);case"preconditions-validation":return Rg(e);case"workflows":return xg(e);case"browser":return kg(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 fg(e);case"lockfile":return gg(e);case"pre-commit-hook":return yg(e)}}function fg(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 gg(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 yg(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 hg(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function wg(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
297
298
  ${e.missing.map(r=>` ${r}`).join(`
298
299
  `)}
299
- 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 rg(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 ng(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 og(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 ig(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function sg(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 ag(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"}
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 bg(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 vg(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 Sg(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 kg(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function Pg(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 Rg(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"}
300
301
  ${t.join(`
301
- `)}`}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=>cg(r));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
302
+ `)}`}function xg(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=>Eg(r));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
302
303
  ${t.join(`
303
- `)}`}function cg(e){let t=e.errors.map(r=>" - "+(r.path===""?"":r.path+": ")+r.message);return" "+e.name+`:
304
+ `)}`}function Eg(e){let t=e.errors.map(r=>" - "+(r.path===""?"":r.path+": ")+r.message);return" "+e.name+`:
304
305
  `+t.join(`
305
- `)}import Tn from"fs";import gg from"path";import{chromium as yg}from"playwright";import ug from"fs";import dg from"path";async function zi(e){let t=dg.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=qe();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 Cn(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 Gi({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 pg}from"gql.tada";var mg=pg(`
306
+ `)}import In from"fs";import jg from"path";import{chromium as Ng}from"playwright";import Cg from"fs";import Tg from"path";async function Zi(e){let t=Tg.join(e,".ripplo","index.ts");if(!Cg.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=Be();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 An(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 es({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 Ag}from"gql.tada";var Ig=Ag(`
306
307
  query DoctorAuthViewer {
307
308
  currentUser {
308
309
  name
309
310
  email
310
311
  }
311
312
  }
312
- `),fg="Failed to connect to Ripplo server";async function Ki({serverUrl:e,token:t}){try{let r=await y({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(fg)?{kind:"unreachable"}:{kind:"invalid"}}}function Ji(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 Yi(e){let t=await bg(e),r={missing:mn(e),type:"env-files"},n=await vg(),o=Sg(),i=await P(e),s=kg(i),a=xg(i),l=await hg(e,i),c=wg(e),p=await Eg(t,i);return[t,r,n,...p,s,a,l,c,o]}async function hg(e,t){if(!t.ok)return{status:"missing",type:"lockfile"};let r=await Qt({cwd:e});return{status:await Zt({compiled:t.result,cwd:e,existing:r}),type:"lockfile"}}function wg(e){let t=gg.join(e,".git","hooks","pre-commit");return Tn.existsSync(t)?{installed:Tn.readFileSync(t,"utf8").includes("ripplo compile --check"),type:"pre-commit-hook"}:{installed:!1,type:"pre-commit-hook"}}async function bg(e){let t=await zi(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 vg(){let e=ie();if(e==null||e.length===0)return{email:void 0,status:"missing",type:"token"};let t=await Ki({serverUrl:ee(),token:e});return t.kind==="valid"?{email:t.email,status:"valid",type:"token"}:{email:void 0,status:t.kind,type:"token"}}function Sg(){let e=yg.executablePath();return{installed:Tn.existsSync(e),type:"browser"}}function kg(e){if(!e.ok)return{errorCount:1,errors:[{message:e.error,path:""}],found:!1,type:"preconditions-validation",valid:!1};let t=Rg(e.result.preconditions,e.result.tests);return{errorCount:t.length,errors:t,found:!0,type:"preconditions-validation",valid:t.length===0}}function Rg(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}`})})}),Pg(e).forEach(o=>{r.push({message:o,path:"preconditions"})}),r}function Pg(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 xg(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 Eg(e,t){if(!e.valid||!t.ok)return[];let r;try{let a=qe();r={appUrl:a.appUrl,engineUrl:a.engineUrl,webhookSecret:a.webhookSecret}}catch{return[]}let n=[],o=await Cn(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 Cg(r,t);return n.push(...s),n}async function Cg(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=Ag(e.appUrl,e.engineUrl);if(i==null)return[o];let s=await Cn(i)==null,a=[];if(a.push({configured:!0,count:r,endpointReachable:s,type:"preconditions"}),Xi(e.engineUrl)&&a.push({reachable:s,type:"engine-endpoint",url:i}),!s)return a;let l=await Gi({appUrl:e.appUrl,engineUrl:e.engineUrl});a.push({rejectsUnsigned:l==null,type:"webhook-verification"});let c=await Tg({engineUrl:i,webhookSecret:e.webhookSecret});return a.push({status:c,type:"adapter-enabled",url:i}),a}async function Tg({engineUrl:e,webhookSecret:t}){if(t.length===0)return"no-secret";let r=JSON.stringify({preconditions:[]});try{let n=await fetch(`${e}/execute-preconditions`,{body:r,headers:{"Content-Type":"application/json",...ke({body:r,secret:t})},method:"PUT",signal:AbortSignal.timeout(5e3)});return n.status===404?"disabled":n.status===401||n.status===403?"bad-secret":"enabled"}catch{return"unreachable"}}function Xi(e){return e.startsWith("http://")||e.startsWith("https://")}function Ag(e,t){return Xi(t)?t:`${e}${t}`}async function Qi(){let e=process.cwd(),t=await Yi(e),r=t.map(o=>Wi(o));process.stdout.write(r.join(`
313
+ `),$g="Failed to connect to Ripplo server";async function ts({serverUrl:e,token:t}){try{let r=await h({config:Pe({serverUrl:e,token:t}),document:Ig,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($g)?{kind:"unreachable"}:{kind:"invalid"}}}function rs(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 ns(e){let t=await Lg(e),r={missing:gn(e),type:"env-files"},n=await _g(),o=Ug(),i=await P(e),s=Vg(i),a=Bg(i),l=await Dg(e,i),c=Og(e),u=await Hg(t,i);return[t,r,n,...u,s,a,l,c,o]}async function Dg(e,t){if(!t.ok)return{status:"missing",type:"lockfile"};let r=await Qt({cwd:e});return{status:await Zt({compiled:t.result,cwd:e,existing:r}),type:"lockfile"}}function Og(e){let t=jg.join(e,".git","hooks","pre-commit");return In.existsSync(t)?{installed:In.readFileSync(t,"utf8").includes("ripplo compile --check"),type:"pre-commit-hook"}:{installed:!1,type:"pre-commit-hook"}}async function Lg(e){let t=await Zi(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 _g(){let e=ie();if(e==null||e.length===0)return{email:void 0,status:"missing",type:"token"};let t=await ts({serverUrl:ee(),token:e});return t.kind==="valid"?{email:t.email,status:"valid",type:"token"}:{email:void 0,status:t.kind,type:"token"}}function Ug(){let e=Ng.executablePath();return{installed:In.existsSync(e),type:"browser"}}function Vg(e){if(!e.ok)return{errorCount:1,errors:[{message:e.error,path:""}],found:!1,type:"preconditions-validation",valid:!1};let t=Fg(e.result.preconditions,e.result.tests);return{errorCount:t.length,errors:t,found:!0,type:"preconditions-validation",valid:t.length===0}}function Fg(e,t){let r=[],n=new Set(Object.keys(e));return Object.entries(e).forEach(([o,i])=>{(i.depends??[]).forEach(s=>{n.has(s)||r.push({message:`Depends on non-existent precondition "${s}"`,path:`preconditions.${o}.depends`})})}),t.forEach(o=>{Object.entries(o.requiresKeys).forEach(([i,s])=>{n.has(s)||r.push({message:`Test "${o.slug}" requires non-existent precondition "${s}" (as ${i})`,path:`tests.${o.slug}.requiresKeys.${i}`})})}),Mg(e).forEach(o=>{r.push({message:o,path:"preconditions"})}),r}function Mg(e){let t=new Set,r=new Set,n=[];function o(i){if(r.has(i)){n.push(`Precondition "${i}" has a circular dependency`);return}t.has(i)||(t.add(i),r.add(i),(e[i]?.depends??[]).forEach(s=>{o(s)}),r.delete(i))}return Object.keys(e).forEach(i=>{o(i)}),n}function 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 Hg(e,t){if(!e.valid||!t.ok)return[];let r;try{let a=Be();r={appUrl:a.appUrl,engineUrl:a.engineUrl,webhookSecret:a.webhookSecret}}catch{return[]}let n=[],o=await An(r.appUrl)==null;n.push({appUrl:r.appUrl,reachable:o,type:"dev-server"});let i=await Yi(process.cwd());n.push(i);let s=await Wg(r,t);return n.push(...s),n}async function Wg(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=zg(e.appUrl,e.engineUrl);if(i==null)return[o];let s=await An(i)==null,a=[];if(a.push({configured:!0,count:r,endpointReachable:s,type:"preconditions"}),os(e.engineUrl)&&a.push({reachable:s,type:"engine-endpoint",url:i}),!s)return a;let l=await es({appUrl:e.appUrl,engineUrl:e.engineUrl});a.push({rejectsUnsigned:l==null,type:"webhook-verification"});let c=await qg({engineUrl:i,webhookSecret:e.webhookSecret});return a.push({status:c,type:"adapter-enabled",url:i}),a}async function qg({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 os(e){return e.startsWith("http://")||e.startsWith("https://")}function zg(e,t){return os(t)?t:`${e}${t}`}async function is(){let e=process.cwd(),t=await ns(e),r=t.map(o=>Qi(o));process.stdout.write(r.join(`
313
314
  `)+`
314
- `);let n=t.some(o=>Ji(o));process.exit(n?1:0)}import $g from"crypto";import{graphql as jg}from"gql.tada";import An from"fs";import In from"path";function or(e){try{let t=In.join(Ig(e),"HEAD"),r=An.readFileSync(t,"utf8").trim(),n="ref: refs/heads/";return r.startsWith(n)?r.slice(n.length):r.length===0?void 0:r.slice(0,7)}catch{return}}function Ig(e){let t=In.join(e,".git");if(An.statSync(t).isDirectory())return t;let n=An.readFileSync(t,"utf8").trim(),o="gitdir:";if(!n.startsWith(o))throw new Error(`unrecognized .git file at ${t}`);let i=n.slice(o.length).trim();if(i.length===0)throw new Error(`empty gitdir pointer at ${t}`);return In.resolve(e,i)}var Ng=jg(`
315
+ `);let n=t.some(o=>rs(o));process.exit(n?1:0)}import Kg from"crypto";import{graphql as Jg}from"gql.tada";import $n from"fs";import jn from"path";function or(e){try{let t=jn.join(Gg(e),"HEAD"),r=$n.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 Gg(e){let t=jn.join(e,".git");if($n.statSync(t).isDirectory())return t;let n=$n.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 jn.resolve(e,i)}var Xg=Jg(`
315
316
  mutation SyncDevSession(
316
317
  $projectId: String!
317
318
  $cwd: String!
@@ -330,13 +331,13 @@ ${t.join(`
330
331
  hooksPaused
331
332
  }
332
333
  }
333
- `);async function vt(e){let t=Og(e.compiled);return Lg({config:e.config,cwd:e.cwd,payload:t})}async function ge(e,t){let r=await P(e);if(!r.ok)throw new Error(`DSL compilation failed: ${r.error}`);let n=await vt({compiled:r.result,config:t,cwd:e});return{compiled:r.result,devSessionId:n.devSessionId}}function Og(e){return{preconditions:Object.entries(e.preconditions).map(([t,r])=>({depends:[...r.depends??[]],description:r.description,name:t,returns:[...r.returns??[]]})),workflows:e.tests.map(t=>({expectedOutcome:t.expectedOutcome,name:t.name,preconditions:[...t.preconditions],requiresKeys:Object.entries(t.requiresKeys).map(([r,n])=>({namespace:r,preconditionName:n})),slug:t.slug,sourcePath:t.sourcePath??null,spec:t.implemented?JSON.stringify(t.spec):null}))}}function Dg(e){return $g.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function Lg({config:e,cwd:t,payload:r}){let n=Dg(r),o=or(t),i=await y({config:e,document:Ng,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 Mg}from"gql.tada";import{createHash as Zi}from"crypto";import{mkdirSync as _g,readFileSync as $n,writeFileSync as Ug}from"fs";import ir from"path";var Vg=[".ts",".tsx",".js",".jsx"];function Ce(e){let t=Zi("sha256");return t.update(G(["rev-parse","HEAD"],e)),t.update("\0"),t.update(G(["diff","HEAD"],e)),t.update("\0"),G(["ls-files","--others","--exclude-standard"],e).split(`
334
- `).filter(n=>n.length>0).filter(n=>Vg.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(Fg(ir.join(e,n))),t.update("\0")}),t.digest("hex")}function es(e){let t=ir.join(e,".ripplo","ripplo.lock");try{let r=$n(t);return Zi("sha256").update(r).digest("hex")}catch{return null}}function Ze(e,t){try{return $n(ts(e,t),"utf8").trim()}catch{return null}}function et(e,t,r){let n=ts(e,t);_g(ir.dirname(n),{recursive:!0}),Ug(n,r)}function ts(e,t){return ir.join(e,".ripplo",".local",`${t}.hash`)}function Fg(e){try{return $n(e)}catch{return Buffer.alloc(0)}}import rs from"figures";var Oe={cross:rs.cross,tick:rs.tick};var os=St(`
334
+ `);async function Ye(e){let t=Yg(e.compiled);return Zg({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 Yg(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 Qg(e){return Kg.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function Zg({config:e,cwd:t,payload:r}){let n=Qg(r),o=or(t),i=await h({config:e,document:Xg,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 oy}from"gql.tada";import{createHash as ss}from"crypto";import{mkdirSync as ey,readFileSync as Nn,writeFileSync as ty}from"fs";import ir from"path";var ry=[".ts",".tsx",".js",".jsx"];function Ee(e){let t=ss("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=>ry.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(ny(ir.join(e,n))),t.update("\0")}),t.digest("hex")}function as(e){let t=ir.join(e,".ripplo","ripplo.lock");try{let r=Nn(t);return ss("sha256").update(r).digest("hex")}catch{return null}}function Qe(e,t){try{return Nn(ls(e,t),"utf8").trim()}catch{return null}}function Ze(e,t,r){let n=ls(e,t);ey(ir.dirname(n),{recursive:!0}),ty(n,r)}function ls(e,t){return ir.join(e,".ripplo",".local",`${t}.hash`)}function ny(e){try{return Nn(e)}catch{return Buffer.alloc(0)}}import cs from"figures";var Ne={cross:cs.cross,tick:cs.tick};var ds=St(`
335
336
  fragment WorkflowIdMCP on Workflow {
336
337
  id
337
338
  slug
338
339
  }
339
- `),Bg=St(`
340
+ `),iy=St(`
340
341
  query ProjectWorkflowIdsMCP($projectId: String!, $cwd: String!) {
341
342
  project(id: $projectId) {
342
343
  id
@@ -348,20 +349,36 @@ ${t.join(`
348
349
  }
349
350
  }
350
351
  }
351
- `,[os]),Hg=St(`
352
+ `,[ds]),sy=St(`
352
353
  mutation SetProjectViewCLI($projectId: String!, $devSessionId: String!) {
353
354
  setProjectView(projectId: $projectId, devSessionId: $devSessionId) {
354
355
  id
355
356
  }
356
357
  }
357
- `),qg=St(`
358
+ `),ay=St(`
358
359
  mutation CreateRunMCP($workflowId: String!, $lockfileHash: String, $repoHash: String) {
359
360
  createRun(workflowId: $workflowId, lockfileHash: $lockfileHash, repoHash: $repoHash) {
360
- id
361
- status
361
+ __typename
362
+ ... on Run {
363
+ id
364
+ status
365
+ }
366
+ ... on DevModeActiveError {
367
+ message
368
+ }
369
+ ... on RepoNotLinkedError {
370
+ message
371
+ }
372
+ ... on WorkflowSpecMissingError {
373
+ message
374
+ }
375
+ ... on LimitExceededError {
376
+ code
377
+ message
378
+ }
362
379
  }
363
380
  }
364
- `),Wg=St(`
381
+ `),ly=St(`
365
382
  query RunStatusMCP($id: String!) {
366
383
  run(id: $id) {
367
384
  id
@@ -388,21 +405,21 @@ ${t.join(`
388
405
  }
389
406
  }
390
407
  }
391
- `);async function sr({config:e,ids:t,presynced:r}){let n=await zg({config:e,ids:t,presynced:r}),o=await Promise.all(n.map(async a=>{try{let l=await Xg({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}
392
- ${h("setup","check auth + config")}`};let{entry:l,runId:c}=a;try{let p=await ey({config:e,runId:c}),m=Yg({config:e,id:l.id,runId:c}),b=`.ripplo/debug/${c}/`;return{id:l.id,runId:c,summary:`View run: ${m}
393
- Debug artifacts: ${b}
394
- ${h("debug","read summary.txt, accessibility-tree, network.jsonl before guessing")}
408
+ `);async function sr({config:e,ids:t,presynced:r}){let n=await cy({config:e,ids:t,presynced:r}),o=await Promise.all(n.map(async a=>{try{let l=await fy({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 hy({config:e,runId:c}),m=my({config:e,id:l.id,runId:c}),g=`.ripplo/debug/${c}/`;return{id:l.id,runId:c,summary:`View run: ${m}
410
+ Debug artifacts: ${g}
411
+ ${w("debug","read summary.txt, accessibility-tree, network.jsonl before guessing")}
395
412
 
396
- ${p}`}}catch(p){let m=p instanceof Error?p.message:String(p);return{id:l.id,runId:c,summary:`ERROR polling run ${c}: ${m}
397
- ${h("debug")}`}}})),s=i.map(a=>`**${a.id}:**
413
+ ${u}`}}catch(u){let m=u instanceof Error?u.message:String(u);return{id:l.id,runId:c,summary:`ERROR polling run ${c}: ${m}
414
+ ${w("debug")}`}}})),s=i.map(a=>`**${a.id}:**
398
415
  ${a.summary}`).join(`
399
416
 
400
417
  ---
401
418
 
402
- `);return{results:i,summary:s}}async function zg({config:e,ids:t,presynced:r}){let n=r??await ge(e.cwd,e),o=await y({config:e,document:Bg,variables:{cwd:e.cwd,projectId:e.projectId}});if(o.project==null)throw new Error("Project not found");let i=o.project.devSession;if(i==null)throw new Error("No active dev session. Start one by running `ripplo` (or `npx ripplo`) in your terminal, then try again.");await y({config:e,document:Hg,variables:{devSessionId:i.id,projectId:e.projectId}});let s=(i.workflows??[]).map(l=>Mg(os,l));if(t.length===0)return s.map(l=>({id:l.slug,workflowId:l.id}));let a=n.compiled.tests.map(l=>l.slug);return t.map(l=>{let c=s.find(p=>p.slug===l);if(c==null)throw new Error(Gg({compiledSlugs:a,slug:l}));return{id:l,workflowId:c.id}})}function Gg({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=Kg({compiledSlugs:e,limit:3,slug:t}),n=r.length>0?`
419
+ `);return{results:i,summary:s}}async function cy({config:e,ids:t,presynced:r}){let n=r??await ye(e.cwd,e),o=await h({config:e,document:iy,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:sy,variables:{devSessionId:i.id,projectId:e.projectId}});let s=(i.workflows??[]).map(l=>oy(ds,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(uy({compiledSlugs:a,slug:l}));return{id:l,workflowId:c.id}})}function uy({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=dy({compiledSlugs:e,limit:3,slug:t}),n=r.length>0?`
403
420
  Did you mean: ${r.join(", ")}?`:"";return`Test "${t}" is not registered in this dev session.${n}
404
- Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function Kg({compiledSlugs:e,limit:t,slug:r}){let n=new Set(r.split("-"));return e.map(i=>({candidate:i,score:Jg(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,t).map(i=>i.candidate)}function Jg(e,t){return t.split("-").filter(r=>e.has(r)).length}function Yg({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 Xg({config:e,workflowId:t}){let r=await y({config:e,document:qg,variables:{lockfileHash:es(e.cwd),repoHash:Qg(e.cwd),workflowId:t}});if(r.createRun==null)throw new Error("Failed to create run");return r.createRun.id}function Qg(e){try{return Ce(e)}catch{return null}}var Zg=2e3,ns=150;async function ey({config:e,runId:t}){let r=0;for(;r<ns;){await ny(Zg),r+=1;let o=(await y({config:e,document:Wg,variables:{id:t}})).run;if(o==null)throw new Error(`Run ${t} not found`);if(!(o.status==="pending"||o.status==="running"))return ty({run:o,runId:t})}return`Run ${t} timed out after polling ${String(ns)} times.`}function ty({run:e,runId:t}){let r=[`Run ${t}: ${e.status.toUpperCase()}`],n=ry(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"?Oe.tick:Oe.cross,s=o.detail==null?"":` \u2014 ${o.detail}`;r.push(` ${i} ${o.title} (${String(o.duration)}ms)${s}`),o.assertions.forEach(a=>{let l=a.status==="passed"?Oe.tick:Oe.cross,c=a.detail==null?"":` \u2014 ${a.detail}`;r.push(` ${l} ${a.description}${c}`)})}),r.join(`
405
- `)}function ry(e){if(e.caughtKind==null)return null;let t=e.workflow?.slug??"workflow";return e.caughtKind==="new_test"?` ${Oe.tick} ripplo caught a bug \u2014 new test "${t}" surfaced an issue in your app code`:` ${Oe.tick} ripplo caught a regression in "${t}"`}function ny(e){return new Promise(t=>{setTimeout(t,e)})}import{graphql as oy}from"gql.tada";var iy=oy(`
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 dy({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 my({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 fy({config:e,workflowId:t}){let n=(await h({config:e,document:ay,variables:{lockfileHash:as(e.cwd),repoHash:gy(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 gy(e){try{return Ee(e)}catch{return null}}var yy=2e3,us=150;async function hy({config:e,runId:t}){let r=0;for(;r<us;){await vy(yy),r+=1;let o=(await h({config:e,document:ly,variables:{id:t}})).run;if(o==null)throw new Error(`Run ${t} not found`);if(!(o.status==="pending"||o.status==="running"))return wy({run:o,runId:t})}return`Run ${t} timed out after polling ${String(us)} times.`}function wy({run:e,runId:t}){let r=[`Run ${t}: ${e.status.toUpperCase()}`],n=by(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 by(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 vy(e){return new Promise(t=>{setTimeout(t,e)})}import{graphql as Sy}from"gql.tada";var ky=Sy(`
406
423
  query DevSessionCheckPreflight($projectId: String!, $cwd: String!) {
407
424
  project(id: $projectId) {
408
425
  id
@@ -411,38 +428,38 @@ Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on
411
428
  }
412
429
  }
413
430
  }
414
- `);function de(){try{return B(process.cwd())}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
415
- `),process.stderr.write(`${h("setup")}
416
- `),process.exit(1)}}async function ye(e){(await y({config:e,document:iy,variables:{cwd:e.cwd,projectId:e.projectId}})).project?.devSession==null&&(process.stderr.write("No active dev session. Start `npx ripplo watch` as a background process (your app's dev server must also be running), then retry. Or run `/ripplo:start` in Claude Code.\n"),process.stderr.write(`${h("setup")}
417
- `),process.exit(1))}async function is({id:e,runs:t}){let r=de();await ye(r),process.stdout.write(`flake-detect "${e}" x${String(t)}...
418
- `);let n=await ge(r.cwd,r),o=await Promise.allSettled(Array.from({length:t},()=>sr({config:r,ids:[e],presynced:n}))),i=0,s=0,a=new Map;o.forEach(c=>{if(c.status==="rejected"){s++;let m=c.reason instanceof Error?c.reason.message:"unknown error";a.set(m,(a.get(m)??0)+1);return}let p=c.value.results[0];if(p==null){s++;return}if(p.summary.includes("FAILED")||p.summary.includes("ERROR")){s++;let m=p.summary.split(`
419
- `).find(b=>b.includes("FAILED")||b.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)
420
- `),a.size>0&&a.forEach((c,p)=>{process.stdout.write(` ${String(c)}x: ${p}
421
- `)}),s>0&&process.stderr.write(`${h("flake-detect","parallel safety + race conditions")}
422
- `),process.exit(s>0?1:0)}import ar from"fs";import{graphql as ay}from"gql.tada";import sy from"fs";function Te(e){return mt(e,"hooks-paused")}function _(e){return sy.existsSync(Te(e))||nr(e)?!1:Qe(e)}var ly=ay(`
431
+ `);function de(){try{return W(process.cwd())}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
432
+ `),process.stderr.write(`${w("setup")}
433
+ `),process.exit(1)}}async function he(e){(await h({config:e,document:ky,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 ps({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},()=>sr({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
+ `).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
+ `),a.size>0&&a.forEach((c,u)=>{process.stdout.write(` ${String(c)}x: ${u}
438
+ `)}),s>0&&process.stderr.write(`${w("flake-detect","parallel safety + race conditions")}
439
+ `),process.exit(s>0?1:0)}import ar from"fs";import{graphql as Ry}from"gql.tada";import Py from"fs";function Ce(e){return mt(e,"hooks-paused")}function U(e){return Py.existsSync(Ce(e))||nr(e)?!1:Xe(e)}var xy=Ry(`
423
440
  mutation CliSetHooksPaused($projectId: String!, $paused: Boolean!) {
424
441
  setHooksPaused(projectId: $projectId, paused: $paused) {
425
442
  id
426
443
  }
427
444
  }
428
- `);async function ss(){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=Te(e);if(ar.existsSync(t)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}ar.writeFileSync(t,""),await ls(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function as(){let e=process.cwd(),t=Te(e);if(!ar.existsSync(t)){process.stdout.write(`Hooks already active.
429
- `);return}ar.unlinkSync(t),await ls(e,!1),process.stdout.write(`Hooks resumed.
430
- `)}async function ls(e,t){let r;try{r=B(e)}catch{return}await y({config:r,document:ly,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import tt from"fs";import rt from"path";import{input as ds,select as ps}from"@inquirer/prompts";import{graphql as Iy}from"gql.tada";import{exec as cy}from"child_process";import L from"fs";import U from"path";import{promisify as uy}from"util";var dy=["@ripplo/testing"],cs=".ripplo/ripplo.lock linguist-generated=true",py=[".ripplo/debug/",".ripplo/.local/"],my=uy(cy);async function us({cwd:e,onStep:t}){t("Scaffolding project files..."),Ry({cwd:e}),t("Updating .gitignore..."),Py(e),t("Marking ripplo.lock as generated..."),yy(e),t("Installing dependencies...");let r=await fy(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 gy(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await $r(),n}async function fy(e){let t=hy({cwd:e,pm:ky(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(`
431
- `)[0]??r.message:String(r);return f.warn("Install failed (%s): %s",t,n),{cmd:t,ok:!1,reason:n}}}async function gy(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 yy(e){let t=U.join(e,".gitattributes"),r=L.existsSync(t)?L.readFileSync(t,"utf8"):"";if(r.includes(cs))return;let n=r.length===0||r.endsWith(`
445
+ `);async function ms(){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(ar.existsSync(t)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}ar.writeFileSync(t,""),await gs(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function fs(){let e=process.cwd(),t=Ce(e);if(!ar.existsSync(t)){process.stdout.write(`Hooks already active.
446
+ `);return}ar.unlinkSync(t),await gs(e,!1),process.stdout.write(`Hooks resumed.
447
+ `)}async function gs(e,t){let r;try{r=W(e)}catch{return}await h({config:r,document:xy,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import et from"fs";import tt from"path";import{input as ws,select as bs}from"@inquirer/prompts";import{graphql as Gy}from"gql.tada";import{exec as Ey}from"child_process";import _ from"fs";import V from"path";import{promisify as Cy}from"util";var Ty=["@ripplo/testing"],ys=".ripplo/ripplo.lock linguist-generated=true",Ay=[".ripplo/debug/",".ripplo/.local/"],Iy=Cy(Ey);async function hs({cwd:e,onStep:t}){t("Scaffolding project files..."),Fy({cwd:e}),t("Updating .gitignore..."),My(e),t("Marking ripplo.lock as generated..."),Ny(e),t("Installing dependencies...");let r=await $y(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 jy(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await $r(),n}async function $y(e){let t=Dy({cwd:e,pm:Vy(e)});f.info("Installing dependencies: %s",t);try{return await Iy(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 jy(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 Ny(e){let t=V.join(e,".gitattributes"),r=_.existsSync(t)?_.readFileSync(t,"utf8"):"";if(r.includes(ys))return;let n=r.length===0||r.endsWith(`
432
449
  `)?"":`
433
- `;L.writeFileSync(t,`${r}${n}${cs}
434
- `)}function hy({cwd:e,pm:t}){let r=dy.join(" ");return t==="pnpm"?vy(e)?`pnpm add -wD ${r}`:`pnpm add -D ${r}`:t==="yarn"?wy({cwd:e,deps:r}):t==="bun"?`bun add -d ${r}`:`npm install -D ${r}`}function wy({cwd:e,deps:t}){return by(e)?`yarn add -D ${t}`:Sy(e)?`yarn add -WD ${t}`:`yarn add -D ${t}`}function by(e){if(L.existsSync(U.join(e,".yarnrc.yml"))||L.existsSync(U.join(e,".pnp.cjs"))||L.existsSync(U.join(e,".pnp.js")))return!0;let t=U.join(e,"package.json");if(!L.existsSync(t))return!1;try{let r=JSON.parse(L.readFileSync(t,"utf8"));if(r==null||typeof r!="object"||!("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 vy(e){return L.existsSync(U.join(e,"pnpm-workspace.yaml"))||L.existsSync(U.join(e,"pnpm-workspace.yml"))}function Sy(e){let t=U.join(e,"package.json");if(!L.existsSync(t))return!1;try{let r=JSON.parse(L.readFileSync(t,"utf8"));if(r==null||typeof r!="object"||!("workspaces"in r))return!1;let n=r.workspaces;return Array.isArray(n)||n!=null&&typeof n=="object"}catch{return!1}}function ky(e){return L.existsSync(U.join(e,"pnpm-lock.yaml"))?"pnpm":L.existsSync(U.join(e,"yarn.lock"))?"yarn":L.existsSync(U.join(e,"bun.lockb"))||L.existsSync(U.join(e,"bun.lock"))?"bun":"npm"}function Ry({cwd:e}){let t=U.join(e,".ripplo"),r=U.join(t,"tests"),n=U.join(t,"preconditions"),o=U.join(t,"observers");L.mkdirSync(r,{recursive:!0}),L.mkdirSync(n,{recursive:!0}),L.mkdirSync(o,{recursive:!0}),kt(U.join(t,"index.ts"),xy),kt(U.join(n,"index.ts"),Ey),kt(U.join(o,"index.ts"),Cy),kt(U.join(r,"index.ts"),Ty),kt(U.join(t,"tsconfig.json"),Ay)}function kt(e,t){L.existsSync(e)||L.writeFileSync(e,t)}function Py(e){let t=U.join(e,".gitignore");if(!L.existsSync(t))return;let r=L.readFileSync(t,"utf8"),n=py.filter(i=>!r.includes(i));if(n.length===0)return;let o=r.endsWith(`
450
+ `;_.writeFileSync(t,`${r}${n}${ys}
451
+ `)}function Dy({cwd:e,pm:t}){let r=Ty.join(" ");return t==="pnpm"?_y(e)?`pnpm add -wD ${r}`:`pnpm add -D ${r}`:t==="yarn"?Oy({cwd:e,deps:r}):t==="bun"?`bun add -d ${r}`:`npm install -D ${r}`}function Oy({cwd:e,deps:t}){return Ly(e)?`yarn add -D ${t}`:Uy(e)?`yarn add -WD ${t}`:`yarn add -D ${t}`}function Ly(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 _y(e){return _.existsSync(V.join(e,"pnpm-workspace.yaml"))||_.existsSync(V.join(e,"pnpm-workspace.yml"))}function Uy(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 Vy(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 Fy({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"),Hy),kt(V.join(o,"index.ts"),Wy),kt(V.join(r,"index.ts"),qy),kt(V.join(t,"tsconfig.json"),zy)}function kt(e,t){_.existsSync(e)||_.writeFileSync(e,t)}function My(e){let t=V.join(e,".gitignore");if(!_.existsSync(t))return;let r=_.readFileSync(t,"utf8"),n=Ay.filter(i=>!r.includes(i));if(n.length===0)return;let o=r.endsWith(`
435
452
  `)?"":`
436
- `;L.writeFileSync(t,r+o+n.join(`
453
+ `;_.writeFileSync(t,r+o+n.join(`
437
454
  `)+`
438
- `)}var xy=`import { createRipplo } from "@ripplo/testing";
455
+ `)}var By=`import { createRipplo } from "@ripplo/testing";
439
456
  import { preconditions } from "./preconditions/index";
440
457
  import { observers } from "./observers/index";
441
458
  import { tests } from "./tests/index";
442
459
 
443
460
  export { preconditions, observers, tests };
444
461
  export default createRipplo({ preconditions, observers, tests });
445
- `,Ey=`// Declare preconditions with \`precondition(name)\` from @ripplo/testing and collect them
462
+ `,Hy=`// Declare preconditions with \`precondition(name)\` from @ripplo/testing and collect them
446
463
  // in the \`preconditions\` registry below. Every handle in this registry must be implemented
447
464
  // in your app server's \`createEngine(ripplo, { preconditions: {...}, observers: {...} })\` call.
448
465
  //
@@ -456,7 +473,7 @@ export default createRipplo({ preconditions, observers, tests });
456
473
  // export const preconditions = { authLoggedIn };
457
474
 
458
475
  export const preconditions = {};
459
- `,Cy=`// Declare observers with \`observer(name)\` from @ripplo/testing and collect them in
476
+ `,Wy=`// Declare observers with \`observer(name)\` from @ripplo/testing and collect them in
460
477
  // the \`observers\` registry below. Use them in tests via \`assert.backend(handle, params)\`.
461
478
  //
462
479
  // Example:
@@ -469,7 +486,7 @@ export const preconditions = {};
469
486
  // export const observers = { orgNameIs };
470
487
 
471
488
  export const observers = {};
472
- `,Ty=`// Each test file under ./tests exports a TestDefinition. Import them here and add them
489
+ `,qy=`// Each test file under ./tests exports a TestDefinition. Import them here and add them
473
490
  // to the \`tests\` array \u2014 that's what \`createRipplo({ ..., tests })\` receives.
474
491
  //
475
492
  // Example:
@@ -477,7 +494,7 @@ export const observers = {};
477
494
  // export const tests = [myTest] as const;
478
495
 
479
496
  export const tests = [] as const;
480
- `,Ay=`{
497
+ `,zy=`{
481
498
  "compilerOptions": {
482
499
  "strict": true,
483
500
  "noUncheckedIndexedAccess": true,
@@ -493,62 +510,67 @@ export const tests = [] as const;
493
510
  "include": ["*.ts", "coverage.d.ts", "observers/**/*.ts", "preconditions/**/*.ts", "tests/**/*.ts"],
494
511
  "exclude": ["node_modules"]
495
512
  }
496
- `;var $y=Iy(`
513
+ `;var Ky=Gy(`
497
514
  query InitProjects {
498
515
  projects {
499
516
  id
500
517
  name
501
518
  }
502
519
  }
503
- `),jn=["../.env.local","../.env"];async function ms(e=Oy()){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();jy(t)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${t}. Delete it first if you want to re-init.
504
- `),process.exit(1));let o=await Ny({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 Ly(o,e.projectId),s=await _y(t,e.envFile),a=await Uy(e.appUrl),l=Dy(a,e.engineUrl),c=rt.resolve(rt.join(t,".ripplo"),s);qo({cwd:t,envFiles:[s],projectId:i}),My({appUrl:a,engineUrl:l,filePath:c});let p=await us({cwd:t,onStep:m=>{process.stdout.write(` ${m}
505
- `)}});if(p.length>0){process.stdout.write(`Done with warnings:
506
- `),p.forEach(m=>{process.stdout.write(` - ${m.message}
520
+ `),Dn=["../.env.local","../.env"];async function vs(e=Yy()){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();Jy(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 Xy({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 Zy(o,e.projectId),s=await eh(t,e.envFile),a=await th(e.appUrl),l=Qy(a,e.engineUrl),c=tt.resolve(tt.join(t,".ripplo"),s);Xo({cwd:t,envFiles:[s],projectId:i}),oh({appUrl:a,engineUrl:l,filePath:c});let u=await hs({cwd:t,onStep:m=>{process.stdout.write(` ${m}
522
+ `)}});if(u.length>0){process.stdout.write(`Done with warnings:
523
+ `),u.forEach(m=>{process.stdout.write(` - ${m.message}
507
524
  `),m.manualCommand!=null&&process.stdout.write(` run: ${m.manualCommand}
508
- `)});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 jy(e){return tt.existsSync(rt.join(e,".ripplo","index.ts"))}async function Ny({serverUrl:e,token:t}){return((await y({config:Pe({serverUrl:e,token:t}),document:$y,variables:void 0})).projects??[]).map(n=>({id:n.id,name:n.name}))}function Oy(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function Dy(e,t){if(t!=null){try{new URL(t)}catch{process.stdout.write(`--engine-url is not a valid URL: ${t}
509
- `),process.exit(1)}return t}return`${e.replace(/\/$/,"")}/ripplo`}async function Ly(e,t){if(t!=null){let r=e.find(n=>n.id===t);return r==null&&(process.stdout.write(`Unknown project id: ${t}
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 Jy(e){return et.existsSync(tt.join(e,".ripplo","index.ts"))}async function Xy({serverUrl:e,token:t}){return((await h({config:Pe({serverUrl:e,token:t}),document:Ky,variables:void 0})).projects??[]).map(n=>({id:n.id,name:n.name}))}function Yy(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function Qy(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 Zy(e,t){if(t!=null){let r=e.find(n=>n.id===t);return r==null&&(process.stdout.write(`Unknown project id: ${t}
510
527
  `),process.exit(1)),process.stdout.write(`Using project: ${r.name} (${r.id})
511
528
  `),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})
512
- `),r.id}return ps({choices:e.map(r=>({name:r.name,value:r.id})),message:"Select a project"})}async function _y(e,t){return t!=null?(t.trim().length===0&&(process.stdout.write(`--env must not be empty
513
- `),process.exit(1)),t):Vy(e)}async function Uy(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
514
- `),process.exit(1)}return e}return Fy()}async function Vy(e){let t=rt.join(e,".ripplo"),r=jn.find(o=>tt.existsSync(rt.resolve(t,o))),n=await ps({choices:[...jn.map(o=>({name:r===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:r??jn[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:ds({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function Fy(){return ds({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 My({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=${qr()}`),/^ENABLE_RIPPLO_TESTING=/m.test(n)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=n.length===0||n.endsWith(`
529
+ `),r.id}return bs({choices:e.map(r=>({name:r.name,value:r.id})),message:"Select a project"})}async function eh(e,t){return t!=null?(t.trim().length===0&&(process.stdout.write(`--env must not be empty
530
+ `),process.exit(1)),t):rh(e)}async function th(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 nh()}async function rh(e){let t=tt.join(e,".ripplo"),r=Dn.find(o=>et.existsSync(tt.resolve(t,o))),n=await bs({choices:[...Dn.map(o=>({name:r===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:r??Dn[0],message:"Which env file should ripplo write RIPPLO_APP_URL, RIPPLO_ENGINE_URL, RIPPLO_WEBHOOK_SECRET, and ENABLE_RIPPLO_TESTING to?"});return n!=="__custom__"?n:ws({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function nh(){return ws({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 oh({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=${Wr()}`),/^ENABLE_RIPPLO_TESTING=/m.test(n)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=n.length===0||n.endsWith(`
515
532
  `)?"":`
516
- `;tt.writeFileSync(r,`${n}${i}${o.join(`
533
+ `;et.writeFileSync(r,`${n}${i}${o.join(`
517
534
  `)}
518
- `)}import Nn from"fs";import fs from"path";import*as gs from"remeda";import By from"path";import{graphql as Hy}from"gql.tada";var qy=Hy(`
535
+ `)}import On from"fs";import ks from"path";import*as Ps from"remeda";import{graphql as ih}from"gql.tada";var sh=ih(`
519
536
  mutation AutoScopeAddDirty($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
520
537
  addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
521
- id
538
+ __typename
539
+ ... on MutationAddDirtyTestsToScopeSuccess {
540
+ data {
541
+ id
542
+ }
543
+ }
522
544
  }
523
545
  }
524
- `);async function nt({compileResult:e,cwd:t}){if(!_(t))return{addedSlugs:[]};let r=Wy(t);if(r.length===0)return{addedSlugs:[]};let n=new Set(e.result.tests.map(c=>c.slug)),o=r.filter(c=>n.has(c));if(o.length===0)return{addedSlugs:[]};let i;try{i=B(t)}catch{return{addedSlugs:[]}}if(await vt({compiled:e.result,config:i,cwd:t}).catch(c=>(f.warn("auto-sync failed: %s",c instanceof Error?c.message:String(c)),null))==null)return{addedSlugs:[]};let a=await y({config:i,document:qy,variables:{cwd:i.cwd,projectId:i.projectId,workflowSlugs:o}}).catch(c=>(f.warn("auto-scope failed: %s",c instanceof Error?c.message:String(c)),null));return a==null?{addedSlugs:[]}:(a.addDirtyTestsToScope??[]).length===0?{addedSlugs:[]}:{addedSlugs:o}}function Wy(e){let t;try{t=G(["status","--porcelain","--",".ripplo/tests"],e)}catch{return[]}return t.split(`
525
- `).map(r=>r.slice(3).trim()).filter(r=>/^\.ripplo\/tests\/[^/]+\.ts$/.test(r)).map(r=>By.basename(r,".ts")).filter(r=>r!=="index")}async function ys(e){let{ids:t,requireImplemented:r}=e,n=process.cwd(),o=await P(n);o.ok||(process.stderr.write(`Compilation failed: ${o.error}
526
- `),process.stderr.write(`${h("create","DSL authoring + lint rules")}
527
- `),process.exit(1)),await ce({cwd:n,result:o.result});let i=Ge(o.result),s=t.length===0?i.diagnostics:i.diagnostics.filter(g=>t.includes(g.test)),a=gs.groupBy(s,g=>g.test);Object.entries(a).forEach(([g,H])=>{process.stderr.write(`
528
- ${g}
529
- `),H.forEach(E=>{let M=E.step==null?"":` at "${E.step}"`;process.stderr.write(` [${E.rule}]${M}
546
+ `);async function rt({compileResult:e,cwd:t}){if(!U(t))return{addedSlugs:[]};let r=lh(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 ah({cfg:i,slugs:o})?o:[]}}async function ah({cfg:e,slugs:t}){let n=(await h({config:e,document:sh,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 Ss=".ripplo/tests/";function lh(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(Ss)&&r.endsWith(".ts")).map(r=>r.slice(Ss.length)).filter(r=>r!=="index.ts"&&!r.endsWith("/index.ts"))}async function Rs(e){let{ids:t,requireImplemented:r}=e,n=process.cwd(),o=await P(n);o.ok||(process.stderr.write(`Compilation failed: ${o.error}
548
+ `),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=Ps.groupBy(s,y=>y.test);Object.entries(a).forEach(([y,B])=>{process.stderr.write(`
550
+ ${y}
551
+ `),B.forEach(E=>{let H=E.step==null?"":` at "${E.step}"`;process.stderr.write(` [${E.rule}]${H}
530
552
  `),process.stderr.write(` ${E.message}
531
- `)})});let l=new Set(o.builder.getUnimplemented().tests),c=r.filter(g=>l.has(g));c.length>0&&(process.stderr.write(`
553
+ `)})});let l=new Set(o.builder.getUnimplemented().tests),c=r.filter(y=>l.has(y));c.length>0&&(process.stderr.write(`
532
554
  not-implemented
533
- `),c.forEach(g=>{process.stderr.write(` ${g} is still marked .notImplemented()
534
- `)}));let p=Jy(n);p.length>0&&(process.stderr.write(`
555
+ `),c.forEach(y=>{process.stderr.write(` ${y} is still marked .notImplemented()
556
+ `)}));let u=ph(n);u.length>0&&(process.stderr.write(`
535
557
  preconditions
536
- `),p.forEach(g=>{process.stderr.write(` [hardcoded-identifier] ${g.file}
537
- `),process.stderr.write(` ${g.message}
538
- `)}));let m=s.length+c.length+p.length;m>0&&(process.stderr.write(`
558
+ `),u.forEach(y=>{process.stderr.write(` [hardcoded-identifier] ${y.file}
559
+ `),process.stderr.write(` ${y.message}
560
+ `)}));let m=s.length+c.length+u.length;m>0&&(process.stderr.write(`
539
561
  ${String(m)} error(s)
540
- `),zy({diagnostics:s,hardcodeWarnings:p,stillStubbed:c}),process.exit(1));let b=o.result.tests.length,x=t.length===0?"all tests":`${String(t.length)} test(s)`;process.stdout.write(`\u2713 ripplo lint: ${x} passed (${String(b)} compiled, lockfile written)
541
- `);let{addedSlugs:A}=await nt({compileResult:o,cwd:n});A.length>0&&process.stdout.write(`\u2713 Auto-scoped ${A.join(", ")} (dirty tests).
542
- `)}function zy({diagnostics:e,hardcodeWarnings:t,stillStubbed:r}){let n=new Set;(e.length>0||r.length>0)&&n.add("create"),t.length>0&&n.add("explore"),n.forEach(o=>process.stderr.write(`${h(o)}
543
- `))}var Gy=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,Ky=/['"`][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"`]/i;function Jy(e){let t=fs.join(e,".ripplo","preconditions");return Nn.existsSync(t)?Nn.readdirSync(t).filter(n=>n.endsWith(".ts")).flatMap(n=>Yy(fs.join(t,n))):[]}function Yy(e){let t=Nn.readFileSync(e,"utf8"),r=t.includes("ctx.uniqueEmail")||t.includes("ctx.uniqueId"),n=[],o=Gy.exec(t);o!=null&&!r&&n.push({file:e,message:`hardcoded email literal ${o[0]} \u2014 use ctx.uniqueEmail() so parallel runs don't collide`});let i=Ky.exec(t);return i!=null&&!r&&n.push({file:e,message:`hardcoded UUID-like literal ${i[0]} \u2014 use ctx.uniqueId() so parallel runs don't collide`}),n}import{graphql as Xy}from"gql.tada";var Qy=Xy(`
562
+ `),ch({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:A}=await rt({compileResult:o,cwd:n});A.length>0&&process.stdout.write(`\u2713 Auto-scoped ${A.join(", ")} (dirty tests).
564
+ `)}function ch({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 uh=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,dh=/['"`][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=ks.join(e,".ripplo","preconditions");return On.existsSync(t)?On.readdirSync(t).filter(n=>n.endsWith(".ts")).flatMap(n=>mh(ks.join(t,n))):[]}function mh(e){let t=On.readFileSync(e,"utf8"),r=t.includes("ctx.uniqueEmail")||t.includes("ctx.uniqueId"),n=[],o=uh.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=dh.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 fh}from"gql.tada";var gh=fh(`
544
566
  query ProjectsList {
545
567
  projects {
546
568
  id
547
569
  name
548
570
  }
549
571
  }
550
- `);async function hs(){let e=ie();e==null&&(process.stderr.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let t=ee(),n=((await y({config:Pe({serverUrl:t,token:e}),document:Qy,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:n},null,2)}
551
- `)}import{graphql as Zy}from"gql.tada";var lr=Zy(`
572
+ `);async function xs(){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:gh,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 yh}from"gql.tada";var lr=yh(`
552
574
  query ScopeStatus($projectId: String!, $cwd: String!) {
553
575
  project(id: $projectId) {
554
576
  id
@@ -568,17 +590,17 @@ ${String(m)} error(s)
568
590
  }
569
591
  }
570
592
  }
571
- `);async function ws({all:e,ids:t}){e&&t.length>0&&(process.stderr.write(`Pass either --all or test ids, not both.
572
- `),process.exit(1));let r=de();await ye(r);let n=await eh({all:e,cwd:r.cwd,ids:t});n==null&&process.exit(1);let{results:o,summary:i}=await sr({config:r,ids:n,presynced:void 0});process.stdout.write(`${i}
593
+ `);async function Es({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 hh({all:e,cwd:r.cwd,ids:t});n==null&&process.exit(1);let{results:o,summary:i}=await sr({config:r,ids:n,presynced:void 0});process.stdout.write(`${i}
573
595
  `);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.
574
- `),process.stderr.write(`${h("debug")}
575
- `)}process.exit(s.length>0?1:0)}async function eh({all:e,cwd:t,ids:r}){return r.length>0?r:e?[]:th(t)}async function th(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).
576
- `)}let o=(await y({config:t,document:lr,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(", ")}
577
- `),i.length===0?(process.stderr.write("No runnable tests in scope. Add tests with `ripplo scope add <id>`, or run the full suite with `ripplo run --all`.\n"),process.stderr.write(`${h("scope")}
578
- `),null):i}async function bs(){let e=process.cwd(),t=B(e);try{let r=await ge(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}
596
+ `),process.stderr.write(`${w("debug")}
597
+ `)}process.exit(s.length>0?1:0)}async function hh({all:e,cwd:t,ids:r}){return r.length>0?r:e?[]:wh(t)}async function wh(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:lr,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
+ `),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 Cs(){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}
579
601
  `)}catch(r){let n=r instanceof Error?r.message:String(r);process.stderr.write(`ripplo sync failed: ${n}
580
- `),process.stderr.write(`${h("setup","verify auth + server reachability")}
581
- `),process.exit(1)}}import cr from"fs";import{createClient as ah}from"graphql-sse";import{graphql as ot}from"gql.tada";import{print as Dn}from"graphql";import rh from"p-limit";var nh=4,vs=rh(nh),Rt=new Set;function On(e){!Number.isFinite(e)||e<1||(vs.concurrency=Math.floor(e),f.debug({concurrency:e},"Local executor concurrency set to %d",e))}var Ae;async function Ss(e){if(!Rt.has(e.runId)){Rt.add(e.runId),f.debug({inflight:Rt.size,runId:e.runId},"run dispatched (inflight=%d)",Rt.size);try{await vs(()=>ih(e))}finally{Rt.delete(e.runId)}}}async function ks(){if(Ae==null)return;let e=await Ae.catch(()=>{});Ae=void 0,e!=null&&e.isConnected()&&await e.close().catch(()=>{})}async function oh(){Ae??=Fe({headed:!1});let e=Ae,t=await e;return t.isConnected()?t:(Ae===e&&(Ae=Fe({headed:!1})),Ae)}async function ih({config:e,cwd:t,runId:r,workflowSlug:n}){try{let o=await oh(),i=t!=null&&n!=null?await sh({cwd:t,workflowSlug:n}):void 0;await en({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 sh({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 lh=6e4,Rs=100,ch=15e3,uh=ot(`
602
+ `),process.stderr.write(`${w("setup","verify auth + server reachability")}
603
+ `),process.exit(1)}}import cr from"fs";import{createClient as Rh}from"graphql-sse";import xh,{AbortError as Eh}from"p-retry";import{graphql as nt}from"gql.tada";import{print as _n}from"graphql";import bh from"p-limit";var vh=4,Ts=bh(vh),Pt=new Set;function Ln(e){!Number.isFinite(e)||e<1||(Ts.concurrency=Math.floor(e),f.debug({concurrency:e},"Local executor concurrency set to %d",e))}var Te;async function As(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 Ts(()=>kh(e))}finally{Pt.delete(e.runId)}}}async function Is(){if(Te==null)return;let e=await Te.catch(()=>{});Te=void 0,e!=null&&e.isConnected()&&await e.close().catch(()=>{})}async function Sh(){Te??=Ue({headed:!1});let e=Te,t=await e;return t.isConnected()?t:(Te===e&&(Te=Ue({headed:!1})),Te)}async function kh({config:e,cwd:t,runId:r,workflowSlug:n}){try{let o=await j({label:"getSharedBrowser",fn:()=>Sh()}),i=await j({label:"resolvePreconditionNames",fn:async()=>{if(!(t==null||n==null))return Ph({cwd:t,workflowSlug:n})}});await rn({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 Ph({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 Ch=6e4,$s=100,Th=15e3,Ah=nt(`
582
604
  subscription RunRequestedWatch($devSessionId: String!) {
583
605
  runRequested(devSessionId: $devSessionId) {
584
606
  runId
@@ -586,42 +608,54 @@ ${String(m)} error(s)
586
608
  workflowSlug
587
609
  }
588
610
  }
589
- `),dh=ot(`
611
+ `),Ih=nt(`
590
612
  subscription HooksPausedWatch($projectId: String!) {
591
613
  hooksPausedRequested(projectId: $projectId) {
592
614
  paused
593
615
  projectId
594
616
  }
595
617
  }
596
- `),ph=ot(`
618
+ `),$h=nt(`
597
619
  mutation HeartbeatDevSessionWatch($id: String!) {
598
620
  heartbeatDevSession(id: $id) {
599
- id
621
+ __typename
622
+ ... on DevSession {
623
+ id
624
+ }
625
+ ... on DevSessionEndedError {
626
+ message
627
+ }
600
628
  }
601
629
  }
602
- `),mh=ot(`
630
+ `),jh=nt(`
603
631
  query WatchLocalConcurrency {
604
632
  currentUser {
605
633
  id
606
634
  maxLocalConcurrentRuns
607
635
  }
608
636
  }
609
- `),fh=ot(`
637
+ `),Nh=nt(`
610
638
  subscription WatchLocalConcurrencyChanged {
611
639
  myMaxLocalConcurrentRunsChanged
612
640
  }
613
- `),gh=ot(`
641
+ `),Dh=nt(`
614
642
  mutation EndDevSessionWatch($projectId: String!, $cwd: String!) {
615
643
  endDevSession(projectId: $projectId, cwd: $cwd) {
616
- id
644
+ __typename
645
+ ... on DevSession {
646
+ id
647
+ }
648
+ ... on NoActiveDevSessionError {
649
+ message
650
+ }
617
651
  }
618
652
  }
619
- `);async function Ps(){Ah();let e=Sh(process.cwd()),t=e.cwd,r=vh(t),n=await P(t);n.ok||(process.stderr.write(`ripplo: DSL compilation failed: ${n.error}
620
- `),process.exit(1));let o=await Ph(()=>vt({compiled:n.result,config:e,cwd:t}));await Ih(e),xs({cwd:t,paused:o.hooksPaused});let i=or(t);i!=null&&f.info("watching branch %s in %s",i,t);let s=ah({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`}),a=yh({config:e,cwd:t,devSessionId:o.devSessionId,sseClient:s}),l=wh({cwd:t,projectId:e.projectId,sseClient:s}),c=hh({sseClient:s}),p=bh({config:e,devSessionId:o.devSessionId}),m=Th();process.stdout.write(`ripplo watch: ready as local executor for session ${o.devSessionId} (sync happens on each \`ripplo run\`; Ctrl-C to stop)
621
- `);let b=async()=>{p(),m(),a(),l(),c(),await Promise.race([y({config:e,document:gh,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise(A=>setTimeout(A,3e3))]),await ks(),Xr(),r()},x=()=>{b().finally(()=>process.exit(0))};process.on("SIGINT",x),process.on("SIGTERM",x),process.on("SIGHUP",x),process.on("SIGBREAK",x),await new Promise(()=>{})}function yh({config:e,cwd:t,devSessionId:r,sseClient:n}){return n.subscribe({query:Dn(uh),variables:{devSessionId:r}},{complete:()=>{},error:o=>{f.error(o,"runRequested subscription error")},next:o=>{let i=o.data?.runRequested;i!=null&&(process.stdout.write(`ripplo: run ${i.workflowSlug}
622
- `),Ss({config:e,cwd:t,runId:i.runId,workflowId:i.workflowId,workflowSlug:i.workflowSlug}).catch(s=>{f.error({err:s,runId:i.runId,workflowSlug:i.workflowSlug},"run execution failed; watch continuing")}))}})}function xs({cwd:e,paused:t}){let r=Te(e);if(t&&!cr.existsSync(r)){cr.writeFileSync(r,"");return}!t&&cr.existsSync(r)&&cr.unlinkSync(r)}function hh({sseClient:e}){return e.subscribe({query:Dn(fh)},{complete:()=>{},error:t=>{f.error(t,"localConcurrency subscription error")},next:t=>{let r=t.data?.myMaxLocalConcurrentRunsChanged;r!=null&&On(r)}})}function wh({cwd:e,projectId:t,sseClient:r}){return r.subscribe({query:Dn(dh),variables:{projectId:t}},{complete:()=>{},error:n=>{f.error(n,"hooksPaused subscription error")},next:n=>{let o=n.data?.hooksPausedRequested?.paused;o!=null&&xs({cwd:e,paused:o})}})}function bh({config:e,devSessionId:t}){let r=setInterval(()=>{y({config:e,document:ph,variables:{id:t}}).catch(n=>{f.warn("heartbeat failed: %s",n instanceof Error?n.message:String(n))})},ch);return()=>{clearInterval(r)}}function vh(e){try{return Bi(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}).
623
- `),process.exit(1)),t}}function Sh(e){try{return B(e)}catch(t){let r=t instanceof Error?t.message:String(t);process.stderr.write(`${r}
624
- `),process.exit(1)}}var kh=1e3,Rh=6e4;async function Ph(e){let t=Date.now()+Rh,r;for(;Date.now()<t;){let n=await xh(e);if(n.ok)return n.value;if(!Eh(n.message))throw n.error;r=n.error,await Ch(kh)}throw r instanceof Error?r:new Error("server never became ready")}async function xh(e){try{return{ok:!0,value:await e()}}catch(t){let r=t instanceof Error?t.message:String(t);return{error:t,message:r,ok:!1}}}function Eh(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function Ch(e){return new Promise(t=>setTimeout(t,e))}function Th(){Tt({maxRuns:Rs});let e=setInterval(()=>{Tt({maxRuns:Rs})},lh);return()=>{clearInterval(e)}}function Ah(){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 Ih(e){try{let r=(await y({config:e,document:mh,variables:void 0})).currentUser?.maxLocalConcurrentRuns;r!=null&&On(r)}catch(t){f.warn({err:t},"failed to fetch local concurrency setting; using default")}}import{graphql as ur}from"gql.tada";var $h=ur(`
653
+ `);async function js(){Wh();let e=Mh(process.cwd()),t=e.cwd,r=Fh(t),n=await P(t);n.ok||(process.stderr.write(`ripplo: DSL compilation failed: ${n.error}
654
+ `),process.exit(1));let o=await Ds(()=>Ye({compiled:n.result,config:e,cwd:t}),{config:e,label:"initial sync"});await qh(e),Ns({cwd:t,paused:o.hooksPaused});let i=or(t);i!=null&&f.info("watching branch %s in %s",i,t);let s=Rh({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`}),a=Vh({config:e,cwd:t,initialId:o.devSessionId,sseClient:s}),l=_h({cwd:t,projectId:e.projectId,sseClient:s}),c=Lh({sseClient:s}),u=Uh({config:e,session:a}),m=Hh();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:Dh,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise(A=>setTimeout(A,3e3))]),await tn(),await Is(),Yr(),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 Oh({config:e,cwd:t,devSessionId:r,onReconnecting:n,sseClient:o}){return o.subscribe({query:_n(Ah),variables:{devSessionId:r}},{complete:()=>{},error:i=>{f.warn("runRequested SSE retries exhausted: %s",i instanceof Error?i.message:String(i))},next:i=>{let s=i.data?.runRequested;s!=null&&(process.stdout.write(`ripplo: run ${s.workflowSlug}
656
+ `),As({config:e,cwd:t,runId:s.runId,workflowId:s.workflowId,workflowSlug:s.workflowSlug}).catch(a=>{f.error({err:a,runId:s.runId,workflowSlug:s.workflowSlug},"run execution failed; watch continuing")}))}},{connecting:i=>{i&&n()}})}function Ns({cwd:e,paused:t}){let r=Ce(e);if(t&&!cr.existsSync(r)){cr.writeFileSync(r,"");return}!t&&cr.existsSync(r)&&cr.unlinkSync(r)}function Lh({sseClient:e}){return e.subscribe({query:_n(Nh)},{complete:()=>{},error:t=>{f.error(t,"localConcurrency subscription error")},next:t=>{let r=t.data?.myMaxLocalConcurrentRunsChanged;r!=null&&Ln(r)}})}function _h({cwd:e,projectId:t,sseClient:r}){return r.subscribe({query:_n(Ih),variables:{projectId:t}},{complete:()=>{},error:n=>{f.error(n,"hooksPaused subscription error")},next:n=>{let o=n.data?.hooksPausedRequested?.paused;o!=null&&Ns({cwd:e,paused:o})}})}function Uh({config:e,session:t}){let r=async()=>{try{let o=await h({config:e,document:$h,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()},Th);return()=>{clearInterval(n)}}function Vh({config:e,cwd:t,initialId:r,sseClient:n}){let o=r,i=null,s=()=>{f.warn("runRequested SSE reconnecting; re-registering session"),u()},a=()=>Oh({config:e,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 Ds(()=>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 Fh(e){try{return Ji(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 Mh(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 Ds(e,{config:t,label:r}){let n=t.ripploServerUrl.includes("localhost")||t.ripploServerUrl.includes("127.0.0.1");return xh(async()=>{try{return await e()}catch(o){let i=o instanceof Error?o.message:String(o);throw Bh(i)?o:new Eh(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 Hh(){Tt({maxRuns:$s});let e=setInterval(()=>{Tt({maxRuns:$s})},Ch);return()=>{clearInterval(e)}}function Wh(){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 qh(e){try{let r=(await h({config:e,document:jh,variables:void 0})).currentUser?.maxLocalConcurrentRuns;r!=null&&Ln(r)}catch(t){f.warn({err:t},"failed to fetch local concurrency setting; using default")}}import{graphql as ur}from"gql.tada";var zh=ur(`
625
659
  query ScopeWorkflowBySlug($projectId: String!, $cwd: String!, $slug: String!) {
626
660
  project(id: $projectId) {
627
661
  id
@@ -634,45 +668,54 @@ ${String(m)} error(s)
634
668
  }
635
669
  }
636
670
  }
637
- `),jh=ur(`
671
+ `),Gh=ur(`
638
672
  mutation ScopeAddDirtyTests($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
639
673
  addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
640
- id
641
- workflow {
642
- id
643
- slug
674
+ __typename
675
+ ... on MutationAddDirtyTestsToScopeSuccess {
676
+ data {
677
+ id
678
+ workflow {
679
+ id
680
+ slug
681
+ }
682
+ }
683
+ }
684
+ ... on NoActiveDevSessionError {
685
+ message
644
686
  }
645
687
  }
646
688
  }
647
- `),Nh=ur(`
689
+ `),Kh=ur(`
648
690
  mutation ScopeLink($id: ID!, $workflowId: String!) {
649
691
  linkScopeItem(id: $id, workflowId: $workflowId) {
650
692
  id
651
693
  }
652
694
  }
653
- `),Oh=ur(`
695
+ `),Jh=ur(`
654
696
  mutation ScopeRemoveMany($ids: [ID!]!) {
655
697
  removeScopeItems(ids: $ids)
656
698
  }
657
- `);async function Es(e){let t=de();await ye(t);let n=(await y({config:t,document:lr,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(n,null,2)}
699
+ `);async function Os(e){let t=de();await he(t);let n=(await h({config:t,document:lr,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(n,null,2)}
658
700
  `);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??""}
659
701
  `);return}let s=i.spec==null?"stub":"implemented";process.stdout.write(` [${s}] (${o.id}) ${i.slug} \u2014 ${i.name}
660
- `)})}async function Cs({testIds:e}){let t=de();await ye(t),await ge(t.cwd,t);let n=(await y({config:t,document:jh,variables:{cwd:t.cwd,projectId:t.projectId,workflowSlugs:[...e]}})).addDirtyTestsToScope??[];if(n.length===0){process.stdout.write(`No scope items added.
661
- `);return}let o=n.map(i=>i.workflow?.slug??"?").join(", ");process.stdout.write(`Added ${String(n.length)} scope item(s): ${o}
662
- `)}async function Ts({id:e,testId:t}){let r=de();await ye(r),await ge(r.cwd,r);let n=await Dh({cfg:r,slug:t});await y({config:r,document:Nh,variables:{id:e,workflowId:n}}),process.stdout.write(`Linked scope item ${e} to ${t}
663
- `)}async function As({ids:e}){let t=de();await ye(t);let n=(await y({config:t,document:Oh,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${String(n)} scope item(s)
664
- `)}async function Dh({cfg:e,slug:t}){let n=(await y({config:e,document:$h,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.
665
- `),process.stderr.write(`${h("create")}
666
- `),process.exit(1)),n.id}async function Is(e){let t=process.cwd(),r=await P(t);r.ok||(process.stderr.write(`Compilation failed: ${r.error}
702
+ `)})}async function Ls({testIds:e}){let t=de();await he(t),await ye(t.cwd,t);let n=(await h({config:t,document:Gh,variables:{cwd:t.cwd,projectId:t.projectId,workflowSlugs:[...e]}})).addDirtyTestsToScope;n?.__typename==="NoActiveDevSessionError"&&(process.stderr.write(`${n.message}
703
+ `),process.exit(1));let o=n?.__typename==="MutationAddDirtyTestsToScopeSuccess"?n.data:[];if(o.length===0){process.stdout.write(`No scope items added.
704
+ `);return}let i=o.map(s=>s.workflow?.slug??"?").join(", ");process.stdout.write(`Added ${String(o.length)} scope item(s): ${i}
705
+ `)}async function _s({id:e,testId:t}){let r=de();await he(r),await ye(r.cwd,r);let n=await Xh({cfg:r,slug:t});await h({config:r,document:Kh,variables:{id:e,workflowId:n}}),process.stdout.write(`Linked scope item ${e} to ${t}
706
+ `)}async function Us({ids:e}){let t=de();await he(t);let n=(await h({config:t,document:Jh,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${String(n)} scope item(s)
707
+ `)}async function Xh({cfg:e,slug:t}){let n=(await h({config:e,document:zh,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
+ `),process.stderr.write(`${w("create")}
709
+ `),process.exit(1)),n.id}async function Vs(e){let t=process.cwd(),r=await P(t);r.ok||(process.stderr.write(`Compilation failed: ${r.error}
667
710
  `),process.exit(1));let{tests:n}=r.builder.getUnimplemented();if(e.format==="summary"){n.length>0&&process.stdout.write(`tests: ${n.join(", ")}
668
711
  `);return}let o={tests:n.map(i=>({id:i,implemented:!1}))};process.stdout.write(`${JSON.stringify(o,null,2)}
669
- `)}import{z as Lh}from"zod";function j(e,t){let r=Lh.custom(n=>typeof n=="object"&&n!==null&&"hook_event_name"in n&&n.hook_event_name===e);return{event:e,run:async n=>await t(r.parse(n))??void 0}}import{createHash as OT}from"crypto";import $s from"picomatch";function _h(e){return G(["diff","--name-only","HEAD"],e).split(`
670
- `).filter(t=>t.length>0)}function js({cwd:e,ignoreGlobs:t,watchGlobs:r}){let n=$s([...r]),o=$s([...t]);return _h(e).filter(i=>n(i)&&!o(i))}function dr(e,...t){return G(["diff","--name-only","HEAD","--",...t],e).split(`
671
- `).filter(r=>r.length>0)}function Ie(){return{ignorePaths:Ee,watchPaths:Sn}}var Ns=j("UserPromptSubmit",e=>{let{cwd:t}=e;if(!$(t)||!_(t))return;let r=Ce(t);if(Ze(t,"coverage-nudge")===r)return;let{ignorePaths:n,watchPaths:o}=Ie(),i=js({cwd:t,ignoreGlobs:n,watchGlobs:o});if(et(t,"coverage-nudge",r),!(i.length===0||dr(t,".ripplo/tests",".ripplo/preconditions",".ripplo/observers").length>0))return{hookSpecificOutput:{additionalContext:`SCOPE DRIFT: ${String(i.length)} app file(s) changed without .ripplo/tests updates. ${h("scope")}`,hookEventName:"UserPromptSubmit"}}});import pr from"fs";import Uh from"os";import Os from"path";var Ds=j("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!_(e.cwd))return;let t=Vh();if(t==null)return;let r=pr.readFileSync(t,"utf8");if(!/\.ripplo\/tests|Tests to implement|No e2e coverage needed/.test(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Plan must cite ripplo test stubs. Add a "Tests to implement" section listing .ripplo/tests/<id>.ts per affected flow, OR add "No e2e coverage needed: <reason>" if this plan touches no user-facing behavior. ${h("explore")}`}}});function Vh(){let e=Os.join(Uh.homedir(),".claude","plans");return pr.existsSync(e)?pr.readdirSync(e).filter(r=>r.endsWith(".md")).map(r=>Os.join(e,r)).map(r=>({full:r,mtime:pr.statSync(r).mtimeMs})).sort((r,n)=>n.mtime-r.mtime)[0]?.full??null:null}var Ls=j("UserPromptSubmit",async e=>{if(e.permission_mode!=="plan"||!$(e.cwd)||!_(e.cwd))return;let t=await P(e.cwd);if(!t.ok)return;let{tests:r}=t.builder.getUnimplemented(),n=['Plan must include "Tests to implement" with .ripplo/tests/<id>.ts per affected flow (ExitPlanMode blocks otherwise).'];return r.length>0&&n.push(`Existing stubs: ${r.join(", ")}`),{hookSpecificOutput:{additionalContext:n.join(`
672
- `),hookEventName:"UserPromptSubmit"}}});import Fh from"path";import _s from"picomatch";import{z as Us}from"zod";var Mh=Us.looseObject({file_path:Us.string()}),Vs=j("PostToolUse",async e=>{let t=Mh.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path,{cwd:n}=e;if(!$(n)||!_(n))return;let o=Fh.relative(n,r);if(o.startsWith(".."))return;let{ignorePaths:i,watchPaths:s}=Ie(),a=_s([...s]),l=_s([...i]);if(!a(o)||l(o))return;let c=await P(n);if(!c.ok)return;let{tests:p}=c.builder.getUnimplemented();if(p.length!==0)return{hookSpecificOutput:{additionalContext:`Reminder: .notImplemented() stubs still present \u2014 tests: ${p.join(", ")}`,hookEventName:"PostToolUse"}}});import{z as Fs}from"zod";var Bh=Fs.looseObject({file_path:Fs.string()}),Ms=j("PostToolUse",async e=>{let t=Bh.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path;if(!/\/\.ripplo\/.*\.ts$/.test(r))return;let{cwd:n}=e;if(!$(n))return;if(!_(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}),Je({cwd:n}),await Hh({compileResult:o,cwd:n})):{decision:"block",reason:`Compilation failed: ${o.error}
673
- ${h("create","DSL authoring + lint rules")}`}});async function Hh({compileResult:e,cwd:t}){let{diagnostics:r}=Ge(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(`
712
+ `)}import{z as Yh}from"zod";function $(e,t){let r=Yh.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 QT}from"crypto";import Fs from"picomatch";function Qh(e){return K(["diff","--name-only","HEAD"],e).split(`
713
+ `).filter(t=>t.length>0)}function Ms({cwd:e,ignoreGlobs:t,watchGlobs:r}){let n=Fs([...r]),o=Fs([...t]);return Qh(e).filter(i=>n(i)&&!o(i))}function dr(e,...t){return K(["diff","--name-only","HEAD","--",...t],e).split(`
714
+ `).filter(r=>r.length>0)}function Ae(){return{ignorePaths:xe,watchPaths:Pn}}var Bs=$("UserPromptSubmit",e=>{let{cwd:t}=e;if(!I(t)||!U(t))return;let r=Ee(t);if(Qe(t,"coverage-nudge")===r)return;let{ignorePaths:n,watchPaths:o}=Ae(),i=Ms({cwd:t,ignoreGlobs:n,watchGlobs:o});if(Ze(t,"coverage-nudge",r),!(i.length===0||dr(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 pr from"fs";import Zh from"os";import Hs from"path";var Ws=$("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!U(e.cwd))return;let t=ew();if(t==null)return;let r=pr.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 ew(){let e=Hs.join(Zh.homedir(),".claude","plans");return pr.existsSync(e)?pr.readdirSync(e).filter(r=>r.endsWith(".md")).map(r=>Hs.join(e,r)).map(r=>({full:r,mtime:pr.statSync(r).mtimeMs})).sort((r,n)=>n.mtime-r.mtime)[0]?.full??null:null}var qs=$("UserPromptSubmit",async e=>{if(e.permission_mode!=="plan"||!I(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 tw from"path";import zs from"picomatch";import{z as Gs}from"zod";var rw=Gs.looseObject({file_path:Gs.string()}),Ks=$("PostToolUse",async e=>{let t=rw.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path,{cwd:n}=e;if(!I(n)||!U(n))return;let o=tw.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 Js}from"zod";var nw=Js.looseObject({file_path:Js.string()}),Xs=$("PostToolUse",async e=>{let t=nw.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path;if(!/\/\.ripplo\/.*\.ts$/.test(r))return;let{cwd:n}=e;if(!I(n))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 ow({compileResult:o,cwd:n})):{decision:"block",reason:`Compilation failed: ${o.error}
716
+ ${w("create","DSL authoring + lint rules")}`}});async function ow({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(`
674
717
  `)}
675
- ${h("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 Bs}from"zod";var qh=Bs.looseObject({command:Bs.string()}),Wh=/\bripplo\s+hooks\s+pause\b/,Hs=j("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=qh.safeParse(e.tool_input);if(!t.success||!Wh.test(t.data.command))return;let{cwd:r}=e;if($(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 Yh}from"shell-quote";import{z as zs}from"zod";import{existsSync as zh,mkdirSync as Gh,rmSync as $A,writeFileSync as Kh}from"fs";import Ln from"path";function qs(e,t,r){let n=Ws(e,t,r);Gh(Ln.dirname(n),{recursive:!0}),Kh(n,"")}function mr(e,t,r){return zh(Ws(e,t,r))}function Jh(e,t){return Ln.join(e,".ripplo",".local","skills-loaded",t)}function Ws(e,t,r){return Ln.join(Jh(e,t),r)}var Xh=zs.looseObject({command:zs.string()}),Qh="debug",Zh=new Set(["tail","head","less","more","wc","sort","uniq","awk","sed","grep"]),Ks=j("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=Xh.safeParse(e.tool_input);if(!t.success)return;let r=ew(t.data.command);if(!tw(r))return;let{cwd:n}=e;if(!$(n)||!_(n))return;let o=nw(r);if(o!=null)return Gs(`Don't pipe \`ripplo run\` through \`${o}\` \u2014 buffering filters hold all stdout until EOF, hiding live progress; if you kill the pipeline mid-run the run is orphaned on the server. Redirect to a file instead: \`ripplo run <id> > /tmp/run.log 2>&1\` and Read the file, or use \`run_in_background: true\`.`);if(!mr(n,e.session_id,Qh))return Gs("Running `ripplo run` requires the `/ripplo:debug` skill loaded first. Load `/ripplo:debug` then retry \u2014 it carries the artifact-read order, the 3-strike rule, and the no-grep-piping guidance for run failures.")});function ew(e){try{return Yh(e)}catch{return[]}}function tw(e){return e.some((t,r)=>t==="ripplo"&&e[r+1]==="run")}function rw(e){return typeof e=="object"&&"op"in e&&e.op==="|"}function nw(e){let t=e.find((r,n)=>{let o=e[n-1];return o!=null&&rw(o)&&typeof r=="string"&&Zh.has(r)});return typeof t=="string"?t:null}function Gs(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}import ow from"path";import{z as Js}from"zod";var iw=new Set(["Edit","Write","NotebookEdit"]),sw=Js.looseObject({file_path:Js.string()}),aw="create",Ys=j("PreToolUse",e=>{if(!iw.has(e.tool_name))return;let t=sw.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!$(r)||!_(r))return;let n=ow.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!mr(r,e.session_id,aw))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 lw from"path";import Xs from"picomatch";import{graphql as cw}from"gql.tada";import{z as Qs}from"zod";var uw=new Set(["Edit","Write","NotebookEdit"]),dw=Qs.looseObject({file_path:Qs.string()}),pw=cw(`
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 Ys}from"zod";var iw=Ys.looseObject({command:Ys.string()}),sw=/\bripplo\s+hooks\s+pause\b/,Qs=$("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=iw.safeParse(e.tool_input);if(!t.success||!sw.test(t.data.command))return;let{cwd:r}=e;if(I(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"`ripplo hooks pause` is a human-only escape hatch \u2014 agents can't bypass Ripplo guardrails on their own. If watch genuinely can't start (auth, server down, intentional offline work), surface the blocker to the user and ask them to run `npx ripplo hooks pause` themselves from their terminal."}}});import{parse as dw}from"shell-quote";import{z as ta}from"zod";import{existsSync as aw,mkdirSync as lw,rmSync as JA,writeFileSync as cw}from"fs";import Un from"path";function Zs(e,t,r){let n=ea(e,t,r);lw(Un.dirname(n),{recursive:!0}),cw(n,"")}function mr(e,t,r){return aw(ea(e,t,r))}function uw(e,t){return Un.join(e,".ripplo",".local","skills-loaded",t)}function ea(e,t,r){return Un.join(uw(e,t),r)}var pw=ta.looseObject({command:ta.string()}),mw="debug",fw=new Set(["tail","head","less","more","wc","sort","uniq","awk","sed","grep"]),na=$("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=pw.safeParse(e.tool_input);if(!t.success)return;let r=gw(t.data.command);if(!yw(r))return;let{cwd:n}=e;if(!I(n)||!U(n))return;let o=ww(r);if(o!=null)return ra(`Don't pipe \`ripplo run\` through \`${o}\` \u2014 buffering filters hold all stdout until EOF, hiding live progress; if you kill the pipeline mid-run the run is orphaned on the server. Redirect to a file instead: \`ripplo run <id> > /tmp/run.log 2>&1\` and Read the file, or use \`run_in_background: true\`.`);if(!mr(n,e.session_id,mw))return ra("Running `ripplo run` requires the `/ripplo:debug` skill loaded first. Load `/ripplo:debug` then retry \u2014 it carries the artifact-read order, the 3-strike rule, and the no-grep-piping guidance for run failures.")});function gw(e){try{return dw(e)}catch{return[]}}function yw(e){return e.some((t,r)=>t==="ripplo"&&e[r+1]==="run")}function hw(e){return typeof e=="object"&&"op"in e&&e.op==="|"}function ww(e){let t=e.find((r,n)=>{let o=e[n-1];return o!=null&&hw(o)&&typeof r=="string"&&fw.has(r)});return typeof t=="string"?t:null}function ra(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}import bw from"path";import{z as oa}from"zod";var vw=new Set(["Edit","Write","NotebookEdit"]),Sw=oa.looseObject({file_path:oa.string()}),kw="create",ia=$("PreToolUse",e=>{if(!vw.has(e.tool_name))return;let t=Sw.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!I(r)||!U(r))return;let n=bw.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!mr(r,e.session_id,kw))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 Pw from"path";import sa from"picomatch";import{graphql as Rw}from"gql.tada";import{z as aa}from"zod";var xw=new Set(["Edit","Write","NotebookEdit"]),Ew=aa.looseObject({file_path:aa.string()}),Cw=Rw(`
676
719
  query PreEditScopeGate($projectId: String!, $cwd: String!) {
677
720
  project(id: $projectId) {
678
721
  id
@@ -684,9 +727,9 @@ ${h("create")}`};let{addedSlugs:n}=await nt({compileResult:e,cwd:t});if(n.length
684
727
  }
685
728
  }
686
729
  }
687
- `),Zs=j("PreToolUse",async e=>{if(!uw.has(e.tool_name))return;let t=dw.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!$(r)||!_(r))return;let n=lw.relative(r,t.data.file_path);if(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!mw(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). ${$i(["scope","create"])}`}}});function mw(e){let{ignorePaths:t,watchPaths:r}=Ie(),n=Xs([...r]),o=Xs([...t]);return n(e)&&!o(e)}async function fw(e){let t;try{t=B(e)}catch{return{degradedReason:"no project config \u2014 `ripplo init` not run here",populated:!0}}let r=await y({config:t,document:pw,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 gw from"fs";import yw from"path";import{z as ea}from"zod";var hw=new Set(["Edit","Write","NotebookEdit"]),ww=ea.looseObject({file_path:ea.string()}),ta=j("PreToolUse",async e=>{if(!hw.has(e.tool_name))return;let t=bw(e);if(t==null)return;let{cwd:r}=e;if(gw.existsSync(Te(r))||Qe(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. ${h("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:
730
+ `),la=$("PreToolUse",async e=>{if(!xw.has(e.tool_name))return;let t=Ew.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!I(r)||!U(r))return;let n=Pw.relative(r,t.data.file_path);if(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!Tw(n))return;let o=await Aw(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). ${Ui(["scope","create"])}`}}});function Tw(e){let{ignorePaths:t,watchPaths:r}=Ae(),n=sa([...r]),o=sa([...t]);return n(e)&&!o(e)}async function Aw(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:Cw,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 Iw from"fs";import $w from"path";import{z as ca}from"zod";var jw=new Set(["Edit","Write","NotebookEdit"]),Nw=ca.looseObject({file_path:ca.string()}),ua=$("PreToolUse",async e=>{if(!jw.has(e.tool_name))return;let t=Dw(e);if(t==null)return;let{cwd:r}=e;if(Iw.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:
688
731
  ${n.error}
689
- ${h("create","DSL authoring + lint rules")}`,hookEventName:"PreToolUse"}}});function bw(e){let t=ww.safeParse(e.tool_input);if(!t.success||!$(e.cwd))return null;let r=yw.relative(e.cwd,t.data.file_path);return r.startsWith("..")||r!==".ripplo"&&!r.startsWith(".ripplo/")?null:r}import{graphql as vw}from"gql.tada";var Sw=vw(`
732
+ ${w("create","DSL authoring + lint rules")}`,hookEventName:"PreToolUse"}}});function Dw(e){let t=Nw.safeParse(e.tool_input);if(!t.success||!I(e.cwd))return null;let r=$w.relative(e.cwd,t.data.file_path);return r.startsWith("..")||r!==".ripplo"&&!r.startsWith(".ripplo/")?null:r}import{graphql as Ow}from"gql.tada";var Lw=Ow(`
690
733
  query ScopeReminder($projectId: String!, $cwd: String!) {
691
734
  project(id: $projectId) {
692
735
  id
@@ -703,9 +746,9 @@ ${h("create","DSL authoring + lint rules")}`,hookEventName:"PreToolUse"}}});func
703
746
  }
704
747
  }
705
748
  }
706
- `),ra=j("UserPromptSubmit",async e=>{let{cwd:t}=e;if(!$(t)||!_(t))return;let r=Ce(t);if(Ze(t,"scope-reminder")===r)return;let n;try{n=B(t)}catch{return}let o=await y({config:n,document:Sw,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. ${h("scope")}`:`RIPPLO SCOPE (${String(i.length)}):
749
+ `),da=$("UserPromptSubmit",async e=>{let{cwd:t}=e;if(!I(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:Lw,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)}):
707
750
  ${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(`
708
- `)}`,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- **3-strike rule.** Same failure after 3 targeted fixes \u2192 stop and report. Repeated failure on the same step almost always means the diagnosis is wrong.\n- **`.ripplo/ripplo.lock` is committed, never hand-edited.** `ripplo lint` / `ripplo compile` regenerates it. Pre-commit runs `ripplo compile --check`.\n- **Scratch files live in `.ripplo/.local/`.** Never loose in `.ripplo/`.\n- **Worktrees are self-contained.** Each worktree has its own `.ripplo/` checkout, DevSession, scope, and debug artifacts. Auth and projectId are shared globally. Env files (typically gitignored) won't carry over to a fresh worktree \u2014 copy from main or point at a shared file. **If sibling worktrees run dev servers on different ports, the worktree's env file MUST update both `RIPPLO_APP_URL` and `RIPPLO_ENGINE_URL` to match the port that worktree's dev server is bound to** (e.g. main on `:3000`, this worktree on `:3001` \u2192 set `RIPPLO_APP_URL=http://localhost:3001` and `RIPPLO_ENGINE_URL=http://localhost:3001/ripplo` in the worktree's env file). Mismatched ports = `npx ripplo watch` (whether started via `/ripplo:start` or manually) talks to the wrong server, runs silently fail or hit the sibling worktree's app.\n- **DSL locators are semantic.** No `css` / `placeholder` / `waitFor` / `group`.\n- **New backend assertion?** Declare in `.ripplo/observers/index.ts`, implement in your app server's `engine.ts` (TS flags the missing impl).\n\n## Key files\n\n- `.ripplo/index.ts` \u2014 `createRipplo` call.\n- `.ripplo/{preconditions,observers,tests}/index.ts` \u2014 registry aggregators.\n- `.ripplo/project.json` \u2014 project id + env-file pointers.\n- `<app>/src/test/engine.ts` \u2014 single impl funnel via `createEngine`.\n- `packages/testing/README.md` (or the npm page for `@ripplo/testing`) \u2014 DSL reference.\n",na=j("SessionStart",e=>{if($(e.cwd))return{hookSpecificOutput:{additionalContext:kw,hookEventName:"SessionStart"}}});import{execFileSync as Rw}from"child_process";import Pw from"path";import oa from"process";import{graphql as xw}from"gql.tada";import{z as fr}from"zod";var Ew=xw(`
751
+ `)}`,hookEventName:"UserPromptSubmit"}}});var _w="# Ripplo \u2014 always-on session context\n\nEvery user-facing change in this repo ships with a deterministic, backend-aware test that proves it works end-to-end.\n\n## Load the right skill before acting \u2014 this is critical\n\nThe skills below carry the procedural detail you need to do Ripplo work correctly: precondition isolation, observer budget tiers, coverage IDs, scope discipline, artifact-read order on failures, parallelization patterns. **None of that is reproduced in this preamble** \u2014 only the always-on guardrails are. If you act on a Ripplo task without loading the matching skill, you will skip rules that exist to prevent specific past failure modes (cross-run data leakage, \"passing\" tests that never asserted backend state, cleared coverage gates without proof, etc.).\n\nMatch the task to a skill from the triage table; if unsure between two, load both. If completely unsure, load `/ripplo:explore` or `/ripplo:create`. Loading is cheap; acting under-informed is not.\n\n## Skill triage\n\n- Load `/ripplo:setup` skill for instructions on initializing Ripplo in a project; `ripplo doctor` reports the engine endpoint missing.\n- Load `/ripplo:explore` skill for instructions on planning/stubbing test coverage for a new project or new feature area.\n- Load `/ripplo:scope` skill for instructions on managing the working set of tests this session is responsible for.\n- Load `/ripplo:create` skill for instructions on authoring a single test spec for a user flow.\n- Load `/ripplo:run` skill for instructions on executing existing tests.\n- Load `/ripplo:debug` skill for instructions on a failed run; read artifacts in `.ripplo/debug/<runId>/` before re-running.\n- Load `/ripplo:flake-detect` skill for instructions on intermittent failures; parallelizes N runs (only use with evidence of flake).\n\n## Universal rules\n\n- **Two background processes must be running before feature work.** (1) The app's dev server, so the app is reachable; (2) `npx ripplo watch` (run `/ripplo:start` to spawn it, or invoke it directly via Bash with `run_in_background`), so the dev session is live. Without watch, scope/coverage hooks don't arm and `ripplo run` refuses to dispatch. Without the dev server, runs fail when they try to hit the app. `npx ripplo doctor` reports both.\n- **Two funnels.** Definitions \u2192 `createRipplo({ preconditions, observers, tests })` in `.ripplo/index.ts`. Implementations \u2192 `createEngine(ripplo, { preconditions, observers })` in your app server's `test/engine.ts`. Never call either elsewhere. TS enforces exhaustiveness across both.\n- **\"Done\" = app code delivers the behavior AND a passing test proves it.** Both halves. Shipping without a test isn't done; writing a test against broken UI/API isn't done.\n- **Scope is your job.** For any non-trivial change, enumerate every flow it could affect and either `scope add` existing tests or stub `.notImplemented()` tests. Don't wait to be told.\n- **`scope remove` is never for size/effort.** Valid only when an item is genuinely out of scope (wrong flow, duplicate, user said \"not this session,\" feature cut). \"Too many stubs\" \u2192 parallelize with subagents. Don't present \"implement vs. remove\" as a neutral A/B.\n- **Stub gates are not a question.** When `stop-enforce` blocks on `.notImplemented()` stubs, implement them \u2014 don't ask the user \"implement or defer?\", don't propose pausing hooks as option B. The fix isn't done until the test is. New scaffolding (precondition, observer, engine impl) is in-scope work, not follow-up.\n- **`uiOnly: true` is not a stub.** Observer wiring is in-scope for mutation flows; don't use it to silence observer lint.\n- **Never weaken a test to make it pass.** No `contains`/regex for exact text, no removed assertions, no fabricated locators. App lacks an accessible name \u2192 add one to the app, don't fall back to `testId()`. App bug \u2192 report with evidence.\n- **Artifacts first, re-run last.** Failed runs produce DOM, a11y tree, console, network, screenshots under `.ripplo/debug/<runId>/`. Read them. Never pipe `ripplo run` through `grep`/`tail`/`head`. Form a hypothesis citing an artifact line, make ONE change, re-run once.\n- **3-strike rule.** Same failure after 3 targeted fixes \u2192 stop and report. Repeated failure on the same step almost always means the diagnosis is wrong.\n- **`.ripplo/ripplo.lock` is committed, never hand-edited.** `ripplo lint` / `ripplo compile` regenerates it. Pre-commit runs `ripplo compile --check`.\n- **Scratch files live in `.ripplo/.local/`.** Never loose in `.ripplo/`.\n- **Worktrees are self-contained.** Each worktree has its own `.ripplo/` checkout, DevSession, scope, and debug artifacts. Auth and projectId are shared globally. Env files (typically gitignored) won't carry over to a fresh worktree \u2014 copy from main or point at a shared file. **If sibling worktrees run dev servers on different ports, the worktree's env file MUST update both `RIPPLO_APP_URL` and `RIPPLO_ENGINE_URL` to match the port that worktree's dev server is bound to** (e.g. main on `:3000`, this worktree on `:3001` \u2192 set `RIPPLO_APP_URL=http://localhost:3001` and `RIPPLO_ENGINE_URL=http://localhost:3001/ripplo` in the worktree's env file). Mismatched ports = `npx ripplo watch` (whether started via `/ripplo:start` or manually) talks to the wrong server, runs silently fail or hit the sibling worktree's app.\n- **DSL locators are semantic.** No `css` / `placeholder` / `waitFor` / `group`.\n- **New backend assertion?** Declare in `.ripplo/observers/index.ts`, implement in your app server's `engine.ts` (TS flags the missing impl).\n\n## Key files\n\n- `.ripplo/index.ts` \u2014 `createRipplo` call.\n- `.ripplo/{preconditions,observers,tests}/index.ts` \u2014 registry aggregators.\n- `.ripplo/project.json` \u2014 project id + env-file pointers.\n- `<app>/src/test/engine.ts` \u2014 single impl funnel via `createEngine`.\n- `packages/testing/README.md` (or the npm page for `@ripplo/testing`) \u2014 DSL reference.\n",pa=$("SessionStart",e=>{if(I(e.cwd))return{hookSpecificOutput:{additionalContext:_w,hookEventName:"SessionStart"}}});import{execFileSync as Uw}from"child_process";import Vw from"path";import ma from"process";import{graphql as Fw}from"gql.tada";import{z as fr}from"zod";var Mw=Fw(`
709
752
  query ScopeEnforce($projectId: String!, $cwd: String!) {
710
753
  project(id: $projectId) {
711
754
  id
@@ -724,14 +767,14 @@ ${i.map(a=>{let l=a.workflow;return l==null?` [intent] (${a.id}) ${a.label??""}
724
767
  }
725
768
  }
726
769
  }
727
- `),sa=j("Stop",async e=>{let{cwd:t}=e;if(!$(t)||!_(t))return;let r=Ce(t),n=Ze(t,"stop-enforce")===r;if(n&&!e.stop_hook_active)return;let o=Cw(t),i=await Tw(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:
770
+ `),ga=$("Stop",async e=>{let{cwd:t}=e;if(!I(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 Hw(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:
728
771
  ${i.join(`
729
772
 
730
773
  `)}`}:{decision:"block",reason:i.join(`
731
774
 
732
- `)}});function Cw(e){return dr(e,".ripplo/tests").filter(t=>t.endsWith(".ts")).map(t=>Pw.basename(t,".ts")).filter(t=>t!=="index")}async function Tw(e,t){let r=await P(e);if(!r.ok)return[`--- Compilation failed ---
775
+ `)}});function Bw(e){return dr(e,".ripplo/tests").filter(t=>t.endsWith(".ts")).map(t=>Vw.basename(t,".ts")).filter(t=>t!=="index")}async function Hw(e,t){let r=await P(e);if(!r.ok)return[`--- Compilation failed ---
733
776
  ${r.error}
734
- ${h("create")}`];await ce({cwd:e,result:r.result}),Je({cwd:e});let n=await Iw(e),o=$w(r,t),i=jw(r),s=Aw(e,r),l=t.length>0||n.hasRunnable?Nw(e):null;return[o,i,s,l,n.error].filter(c=>c!=null)}function Aw(e,t){let{ignorePaths:r}=Ie(),n=Ni({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(`
777
+ ${w("create")}`];await ce({cwd:e,result:r.result}),Ge({cwd:e});let n=await qw(e),o=zw(r,t),i=Gw(r),s=Ww(e,r),l=t.length>0||n.hasRunnable?Kw(e):null;return[o,i,s,l,n.error].filter(c=>c!=null)}function Ww(e,t){let{ignorePaths:r}=Ae(),n=Fi({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(`
735
778
  `);s.push(`Unacknowledged interactions (add to a test's .coverage(...)):
736
779
  ${a}`)}if(i.length>0){let a=i.map(l=>` ${l.id}`).join(`
737
780
  `);s.push(`Stale .coverage(...) claims (id no longer exists in source):
@@ -739,23 +782,23 @@ ${a}`)}return`--- Exhaustiveness ---
739
782
  ${s.join(`
740
783
 
741
784
  `)}
742
- ${h("create")}`}async function Iw(e){let t;try{t=B(e)}catch{return{error:null,hasRunnable:!1}}let n=(await y({config:t,document:Ew,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 ---
785
+ ${w("create")}`}async function qw(e){let t;try{t=W(e)}catch{return{error:null,hasRunnable:!1}}let n=(await h({config:t,document:Mw,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 ---
743
786
  ${o.join(`
744
787
  `)}
745
- ${h("create")}`,hasRunnable:i}}function $w(e,t){let{diagnostics:r}=Ge(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 ---
788
+ ${w("create")}`,hasRunnable:i}}function zw(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 ---
746
789
  ${[...i,...s].join(`
747
790
  `)}
748
- ${h("create")}`}function jw(e){let{tests:t}=e.builder.getUnimplemented();return t.length===0?null:`--- Unimplemented stubs ---
791
+ ${w("create")}`}function Gw(e){let{tests:t}=e.builder.getUnimplemented();return t.length===0?null:`--- Unimplemented stubs ---
749
792
  ${t.join(", ")}
750
793
  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.
751
- ${h("create")}`}function Nw(e){let t=Dw(["run"],e);if(t.code===0)return null;let r=t.output.split(`
794
+ ${w("create")}`}function Kw(e){let t=Xw(["run"],e);if(t.code===0)return null;let r=t.output.split(`
752
795
  `).filter(n=>/FAILED/.test(n)).join(`
753
796
  `);return r.length===0?null:`--- Ripplo Run Failures (scope) ---
754
797
  ${r}
755
- Artifacts: .ripplo/debug/<runId>/. ${h("debug")}`}var Ow=fr.object({status:fr.number().nullish(),stderr:fr.unknown().optional(),stdout:fr.unknown().optional()});function ia(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function Dw(e,t){let r=oa.argv[1];if(r==null)return{code:1,output:""};try{return{code:0,output:Rw(oa.execPath,[r,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}}catch(n){let o=Ow.safeParse(n);if(!o.success)return{code:1,output:""};let i=`${ia(o.data.stdout)}${ia(o.data.stderr)}`;return{code:o.data.status??1,output:i}}}import{z as aa}from"zod";var Lw=aa.looseObject({skill:aa.string()}),la=j("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let t=Lw.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&&$(e.cwd)&&qs(e.cwd,e.session_id,n)});zw();zo(process.cwd());Or();var ca={"coverage-nudge":Ns,"exit-plan-gate":Ds,"plan-reminder":Ls,"post-edit-flag-stubs":Vs,"post-edit-lint":Ms,"pre-bash-hooks-pause-gate":Hs,"pre-bash-run-gate":Ks,"pre-edit-ripplo-skill-gate":Ys,"pre-edit-scope-gate":Zs,"pre-edit-watch-gate":ta,"scope-reminder":ra,"session-preamble":na,"stop-enforce":sa,"track-skill-load":la};async function Vw(){await _w(Uw(process.argv)).scriptName("ripplo").version("0.5.6").command("watch","Watch for run requests and execute locally",()=>{},()=>Ps()).command("auth <subcommand>","Manage authentication",Ww).command("projects <subcommand>","Inspect Ripplo projects",qw).command("hooks <subcommand>","Pause or resume Ripplo hooks",Hw).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=>ms({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=>ws({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=>ys({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=>is({id:e.id,runs:e.runs})).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>bs()).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=>ji({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>_i()).command("doctor","Check project health",()=>{},()=>Qi()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>Is({format:e.format})).command("scope <subcommand>","Manage testing scope",Bw).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(ca),demandOption:!0,type:"string"}),e=>Fw(e.name)).strict().help().parse()}async function Fw(e){let t=ca[e];t==null&&(process.stderr.write(`Unknown hook: ${e}
756
- `),process.exit(1));let r=await Mw(),n=r.trim()===""?{}:JSON.parse(r),o=await t.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function Mw(){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)})}Vw().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
757
- `),process.exit(1)});function Bw(e){return e.command("status","Print the current scope",t=>t.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),t=>Es({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=>Cs({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=>Ts({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=>As({ids:t.ids})).demandCommand(1)}function Hw(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>ss()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>as()).demandCommand(1)}function qw(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>hs()).demandCommand(1)}function Ww(e){return e.command("login","Authenticate via device flow",()=>{},()=>Qo()).command("status","Show authentication status",()=>{},()=>Zo()).command("logout","Remove the saved token",()=>{},()=>{ei()}).demandCommand(1)}function zw(){let e=process.cwd(),t=br(e);t!=null&&t!==e&&(process.chdir(t),process.stderr.write(`ripplo: resolved .ripplo/ at ${t}
758
- `))}export{Vw as main};
798
+ Artifacts: .ripplo/debug/<runId>/. ${w("debug")}`}var Jw=fr.object({status:fr.number().nullish(),stderr:fr.unknown().optional(),stdout:fr.unknown().optional()});function fa(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function Xw(e,t){let r=ma.argv[1];if(r==null)return{code:1,output:""};try{return{code:0,output:Uw(ma.execPath,[r,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}}catch(n){let o=Jw.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 Yw=ya.looseObject({skill:ya.string()}),ha=$("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let t=Yw.safeParse(e.tool_input);if(!t.success)return;let r=/^ripplo:(.+)$/.exec(t.data.skill);if(r==null)return;let n=r[1];n!=null&&I(e.cwd)&&Zs(e.cwd,e.session_id,n)});ab();Qo(process.cwd());Dr();var wa={"coverage-nudge":Bs,"exit-plan-gate":Ws,"plan-reminder":qs,"post-edit-flag-stubs":Ks,"post-edit-lint":Xs,"pre-bash-hooks-pause-gate":Qs,"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};async function eb(){await Qw(Zw(process.argv)).scriptName("ripplo").version("0.5.8").command("watch","Watch for run requests and execute locally",()=>{},()=>js()).command("auth <subcommand>","Manage authentication",sb).command("projects <subcommand>","Inspect Ripplo projects",ib).command("hooks <subcommand>","Pause or resume Ripplo hooks",ob).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=>vs({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=>Es({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=>Rs({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=>ps({id:e.id,runs:e.runs})).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>Cs()).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=>Vi({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>Wi()).command("doctor","Check project health",()=>{},()=>is()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>Vs({format:e.format})).command("scope <subcommand>","Manage testing scope",nb).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(wa),demandOption:!0,type:"string"}),e=>tb(e.name)).strict().help().parse()}async function tb(e){let t=wa[e];t==null&&(process.stderr.write(`Unknown hook: ${e}
799
+ `),process.exit(1));let r=await rb(),n=r.trim()===""?{}:JSON.parse(r),o=await t.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function rb(){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)})}eb().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
800
+ `),process.exit(1)});function nb(e){return e.command("status","Print the current scope",t=>t.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),t=>Os({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=>Ls({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=>_s({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=>Us({ids:t.ids})).demandCommand(1)}function ob(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>ms()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>fs()).demandCommand(1)}function ib(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>xs()).demandCommand(1)}function sb(e){return e.command("login","Authenticate via device flow",()=>{},()=>oi()).command("status","Show authentication status",()=>{},()=>ii()).command("logout","Remove the saved token",()=>{},()=>{si()}).demandCommand(1)}function ab(){let e=process.cwd(),t=br(e);t!=null&&t!==e&&(process.chdir(t),process.stderr.write(`ripplo: resolved .ripplo/ at ${t}
801
+ `))}export{eb as main};
759
802
  /*! Bundled license information:
760
803
 
761
804
  mustache/mustache.mjs: