ripplo 0.4.1 → 0.4.2
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.
- package/README.md +4 -4
- package/dist/index.js +190 -175
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{execFileSync as
|
|
3
|
-
`)}function
|
|
4
|
-
`),n=
|
|
2
|
+
import{execFileSync as ba}from"child_process";import Sa from"fs";import pt from"path";function Xt(e){let t=ka(e);return t??kn(e)}function kn(e){let t=pt.dirname(e);return va(pt.join(e,".ripplo"))?e:t===e?null:kn(t)}function va(e){try{return Sa.statSync(e).isDirectory()}catch{return!1}}function ka(e){let t=Ra(["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 Ra(e,t){try{return ba("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import Pn from"fs";import gt from"path";import{config as Ca}from"dotenv";import{z as ft}from"zod";import Ke from"fs";import Zt from"path";import{z as mt}from"zod";var Rn=Zt.join(".ripplo","project.json"),Qt=[".env",".env.local"],xa=mt.object({envFiles:mt.array(mt.string().min(1)).optional(),projectId:mt.string().min(1)});function er(e){return Zt.join(e,Rn)}function tr(e){let t=er(e);if(!Ke.existsSync(t))throw new Error(`ripplo: missing ${Rn}. Run \`ripplo init\` to create it.`);let r=JSON.parse(Ke.readFileSync(t,"utf8")),n=xa.parse(r);return{envFiles:n.envFiles??Qt,projectId:n.projectId}}function rr(e){let t=er(e);if(Ke.existsSync(t))try{return tr(e)}catch{return}}function xn({cwd:e,envFiles:t,projectId:r}){let n=er(e);Ke.mkdirSync(Zt.dirname(n),{recursive:!0});let o={projectId:r};t!=null&&!Pa(t)&&(o.envFiles=[...t]),Ke.writeFileSync(n,JSON.stringify(o,null,2)+`
|
|
3
|
+
`)}function Pa(e){return e.length!==Qt.length?!1:e.every((t,r)=>t===Qt[r])}function Cn(e){let r=rr(e)?.envFiles??[".env",".env.local"],n=gt.join(e,".ripplo");r.forEach(o=>{let i=gt.resolve(n,o);Pn.existsSync(i)&&Ca({override:!0,path:i,quiet:!0})}),nr=void 0}var Ea=ft.object({RIPPLO_APP_URL:ft.url(),RIPPLO_ENGINE_URL:ft.url(),RIPPLO_WEBHOOK_SECRET:ft.string().min(1)}),nr;function $e(){return nr??=Ta(),nr}function Ta(){let e=Ea.safeParse(process.env);if(!e.success){let r=e.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
|
|
4
|
+
`),n=or(process.cwd()),o=n.map(s=>` ${s}`).join(`
|
|
5
5
|
`),i=n.length>0?`
|
|
6
6
|
|
|
7
7
|
Declared env file(s) not found at this path:
|
|
@@ -9,48 +9,48 @@ ${o}
|
|
|
9
9
|
If you're in a git worktree, the env file may not have been copied from the main checkout \u2014 recreate it (or symlink to a shared file outside the working tree).`:"";throw new Error(`ripplo: env config invalid:
|
|
10
10
|
${r}
|
|
11
11
|
|
|
12
|
-
Add missing values to the env file(s) declared in .ripplo/project.json.${i}`)}let t=e.data;return{appUrl:t.RIPPLO_APP_URL,engineUrl:t.RIPPLO_ENGINE_URL,webhookSecret:t.RIPPLO_WEBHOOK_SECRET}}function
|
|
13
|
-
`&&(d(),l="",c=0,r=!1);if(!h.scan(u))break;if(s=!0,
|
|
12
|
+
Add missing values to the env file(s) declared in .ripplo/project.json.${i}`)}let t=e.data;return{appUrl:t.RIPPLO_APP_URL,engineUrl:t.RIPPLO_ENGINE_URL,webhookSecret:t.RIPPLO_WEBHOOK_SECRET}}function or(e){let r=rr(e)?.envFiles??[],n=gt.join(e,".ripplo");return r.map(o=>gt.resolve(n,o)).filter(o=>!Pn.existsSync(o))}import rw from"yargs";import{hideBin as nw}from"yargs/helpers";import{graphql as ep}from"gql.tada";var Aa=Object.prototype.toString,je=Array.isArray||function(t){return Aa.call(t)==="[object Array]"};function sr(e){return typeof e=="function"}function $a(e){return je(e)?"array":typeof e}function ir(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function En(e,t){return e!=null&&typeof e=="object"&&t in e}function Ia(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var ja=RegExp.prototype.test;function Na(e,t){return ja.call(e,t)}var Oa=/\S/;function Da(e){return!Na(Oa,e)}var La={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function _a(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return La[r]})}var Ua=/\s*/,Va=/\s+/,Tn=/\s*=/,Fa=/\s*\}/,Ma=/#|\^|\/|>|\{|&|=|!/;function Ha(e,t){if(!e)return[];var r=!1,n=[],o=[],i=[],s=!1,a=!1,l="",c=0;function d(){if(s&&!a)for(;i.length;)delete o[i.pop()];else i=[];s=!1,a=!1}var u,f,b;function w(D){if(typeof D=="string"&&(D=D.split(Va,2)),!je(D)||D.length!==2)throw new Error("Invalid tags: "+D);u=new RegExp(ir(D[0])+"\\s*"),f=new RegExp("\\s*"+ir(D[1])),b=new RegExp("\\s*"+ir("}"+D[1]))}w(t||te.tags);for(var h=new Ye(e),v,E,_,B,O,U;!h.eos();){if(v=h.pos,_=h.scanUntil(u),_)for(var ie=0,Ae=_.length;ie<Ae;++ie)B=_.charAt(ie),Da(B)?(i.push(o.length),l+=B):(a=!0,r=!0,l+=" "),o.push(["text",B,v,v+1]),v+=1,B===`
|
|
13
|
+
`&&(d(),l="",c=0,r=!1);if(!h.scan(u))break;if(s=!0,E=h.scan(Ma)||"name",h.scan(Ua),E==="="?(_=h.scanUntil(Tn),h.scan(Tn),h.scanUntil(f)):E==="{"?(_=h.scanUntil(b),h.scan(Fa),h.scanUntil(f),E="&"):_=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(E==">"?O=[E,_,v,h.pos,l,c,r]:O=[E,_,v,h.pos],c++,o.push(O),E==="#"||E==="^")n.push(O);else if(E==="/"){if(U=n.pop(),!U)throw new Error('Unopened section "'+_+'" at '+v);if(U[1]!==_)throw new Error('Unclosed section "'+U[1]+'" at '+v)}else E==="name"||E==="{"||E==="&"?a=!0:E==="="&&w(_)}if(d(),U=n.pop(),U)throw new Error('Unclosed section "'+U[1]+'" at '+h.pos);return qa(Wa(o))}function Wa(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 Ye(e){this.string=e,this.tail=e,this.pos=0}Ye.prototype.eos=function(){return this.tail===""};Ye.prototype.scan=function(t){var r=this.tail.match(t);if(!r||r.index!==0)return"";var n=r[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};Ye.prototype.scanUntil=function(t){var r=this.tail.search(t),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};function Ie(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Ie.prototype.push=function(t){return new Ie(t,this)};Ie.prototype.lookup=function(t){var r=this.cache,n;if(r.hasOwnProperty(t))n=r[t];else{for(var o=this,i,s,a,l=!1;o;){if(t.indexOf(".")>0)for(i=o.view,s=t.split("."),a=0;i!=null&&a<s.length;)a===s.length-1&&(l=En(i,s[a])||Ia(i,s[a])),i=i[s[a++]];else i=o.view[t],l=En(o.view,t);if(l){n=i;break}o=o.parent}r[t]=n}return sr(n)&&(n=n.call(this.view)),n};function G(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}G.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};G.prototype.parse=function(t,r){var n=this.templateCache,o=t+":"+(r||te.tags).join(":"),i=typeof n<"u",s=i?n.get(o):void 0;return s==null&&(s=Ha(t,r),i&&n.set(o,s)),s};G.prototype.render=function(t,r,n,o){var i=this.getConfigTags(o),s=this.parse(t,i),a=r instanceof Ie?r:new Ie(r,void 0);return this.renderTokens(s,a,n,t,o)};G.prototype.renderTokens=function(t,r,n,o,i){for(var s="",a,l,c,d=0,u=t.length;d<u;++d)c=void 0,a=t[d],l=a[0],l==="#"?c=this.renderSection(a,r,n,o,i):l==="^"?c=this.renderInverted(a,r,n,o,i):l===">"?c=this.renderPartial(a,r,n,i):l==="&"?c=this.unescapedValue(a,r):l==="name"?c=this.escapedValue(a,r,i):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(s+=c);return s};G.prototype.renderSection=function(t,r,n,o,i){var s=this,a="",l=r.lookup(t[1]);function c(f){return s.render(f,r,n,i)}if(l){if(je(l))for(var d=0,u=l.length;d<u;++d)a+=this.renderTokens(t[4],r.push(l[d]),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}};G.prototype.renderInverted=function(t,r,n,o,i){var s=r.lookup(t[1]);if(!s||je(s)&&s.length===0)return this.renderTokens(t[4],r,n,o,i)};G.prototype.indentPartial=function(t,r,n){for(var o=r.replace(/[^ \t]/g,""),i=t.split(`
|
|
14
14
|
`),s=0;s<i.length;s++)i[s].length&&(s>0||!n)&&(i[s]=o+i[s]);return i.join(`
|
|
15
|
-
`)};
|
|
16
|
-
`):`${e.status}: ${e.title}`;return{specNode:e.specNode,stepResult:o,toolOutput:i}}var
|
|
17
|
-
${r.summary}`,verdict:r.verdict};return Promise.resolve(n)}};import{z as
|
|
15
|
+
`)};G.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],d=s;l==0&&c&&(d=this.indentPartial(s,c,a));var u=this.parse(d,i);return this.renderTokens(u,r,n,d,o)}}};G.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};G.prototype.escapedValue=function(t,r,n){var o=this.getConfigEscape(n)||te.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&o===te.escape?String(i):o(i)};G.prototype.rawValue=function(t){return t[1]};G.prototype.getConfigTags=function(t){return je(t)?t:t&&typeof t=="object"?t.tags:void 0};G.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!je(t))return t.escape};var te={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){Je.templateCache=e},get templateCache(){return Je.templateCache}},Je=new G;te.clearCache=function(){return Je.clearCache()};te.parse=function(t,r){return Je.parse(t,r)};te.render=function(t,r,n,o){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+$a(t)+'" was given as the first argument for mustache#render(template, view, partials)');return Je.render(t,r,n,o)};te.escape=_a;te.Scanner=Ye;te.Context=Ie;te.Writer=G;var An=te;function Xe({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,za({def:r,name:t})]))}var Ba={boolean:!1,number:0,string:""};function za({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 Qe({ref:e,variables:t}){if(e.type==="static")return e.value;let r=t[e.name];if(r==null||typeof r=="object")throw new Error(`Variable "${e.name}" is not defined`);return r}function K({ref:e,variables:t}){let r=String(Qe({ref:e,variables:t}));return ar({raw:r,variables:t})}function ar({raw:e,variables:t}){return An.render(e,t,{},{escape:r=>r})}function lr({ref:e,variables:t}){let r=Qe({ref:e,variables:t});if(typeof r=="number")return r;let n=Number(r);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${String(r)}" to number`);return n}function Ne({name:e,store:t,value:r}){return{...t,[e]:r}}function L({locator:e,page:t,variables:r}){switch(e.by){case"testId":return t.getByTestId($n(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:$n(e.name,r)})}}function $n(e,t){return t==null?e:ar({raw:e,variables:t})}async function In({node:e,page:t,timeout:r}){await L({locator:e.source,page:t,variables:void 0}).dragTo(L({locator:e.target,page:t,variables:void 0}),{timeout:r})}async function jn({node:e,page:t,timeout:r}){await L({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function Nn({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 On({node:e,page:t,variables:r}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let o=K({ref:e.value,variables:r}),i=JSON.stringify(o);return await t.evaluate(`navigator.clipboard.writeText(${i})`),{variables:r}}if(e.variable==null)throw new Error("clipboard read requires a variable name to store the result");let n=String(await t.evaluate("navigator.clipboard.readText()"));return{variables:Ne({name:e.variable,store:r,value:n})}}async function Dn({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function cr({node:e,page:t,timeout:r,variables:n}){switch(e.type){case"click":case"check":case"uncheck":case"clear":case"dblclick":case"focus":case"hover":case"scrollIntoView":return Ka({node:e,page:t,timeout:r,variables:n});case"rightClick":return await jn({node:e,page:t,timeout:r}),{variables:n};case"goto":{let o=K({ref:e.url,variables:n});return await t.goto(o,{timeout:r,waitUntil:"domcontentloaded"}),await t.waitForLoadState("load",{timeout:r}),await t.waitForFunction("document.body != null && document.body.childElementCount > 0 && (document.body.textContent?.trim().length ?? 0) > 0",void 0,{timeout:r}),await t.evaluate("new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })"),{variables:n}}case"fill":return Ya({node:e,page:t,timeout:r,variables:n});case"select":return Xa({node:e,page:t,timeout:r,variables:n});case"type":return Qa({node:e,page:t,timeout:r,variables:n});case"press":return await Ja({node:e,page:t,timeout:r}),{variables:n};case"drag":return await In({node:e,page:t,timeout:r}),{variables:n};case"upload":return Za({node:e,page:t,timeout:r,variables:n});case"extractText":return el({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=Qe({ref:e.value,variables:n});return{variables:Ne({name:e.variable,store:n,value:o})}}case"fail":throw new Error(e.message);case"setViewport":return await t.setViewportSize({height:e.height,width:e.width}),{variables:n};case"handleDialog":return Nn({node:e,page:t,variables:n});case"clipboard":return On({node:e,page:t,variables:n});case"setPermission":return await Dn({node:e,page:t}),{variables:n}}}var Ga={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function Ka({node:e,page:t,timeout:r,variables:n}){return await L({locator:e.locator,page:t,variables:n})[Ga[e.type]]({timeout:r}),{variables:n}}async function Ja({node:e,page:t,timeout:r}){e.locator==null?await t.keyboard.press(e.key):await L({locator:e.locator,page:t,variables:void 0}).press(e.key,{timeout:r})}async function Ya({node:e,page:t,timeout:r,variables:n}){let o=K({ref:e.value,variables:n});return await L({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function Xa({node:e,page:t,timeout:r,variables:n}){let o=K({ref:e.value,variables:n});return await L({locator:e.locator,page:t,variables:n}).selectOption(o,{timeout:r}),{variables:n}}async function Qa({node:e,page:t,timeout:r,variables:n}){let o=K({ref:e.value,variables:n});return await L({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function Za({node:e,page:t,timeout:r,variables:n}){return await L({locator:e.locator,page:t,variables:n}).setInputFiles(e.files,{timeout:r}),{variables:n}}async function el({node:e,page:t,timeout:r,variables:n}){let o=await L({locator:e.locator,page:t,variables:n}).textContent({timeout:r});if(o==null)throw new Error("extractText: element had no text content");return{variables:Ne({name:e.variable,store:n,value:o})}}import Kl from"@anthropic-ai/sdk";import{z as Ln}from"zod";import{z as sl}from"zod";async function we({page:e,runStartTime:t,targets:r}){let n=e.viewportSize();if(n==null)throw new Error("Page has no viewport set");return{annotations:await nl(r),snapshotTimestamp:Math.round(performance.now()-t),url:e.url(),viewportHeight:n.height,viewportWidth:n.width}}function tl(e){return"locator"in e}function rl(e){let t=globalThis.__ripploRrwebMirror?.getId(e);return t!=null&&t>0?t:void 0}async function nl(e){return(await Promise.all(e.map(r=>ol(r)))).filter(r=>r!=null)}async function ol(e){if(!tl(e))return{height:0,label:e.label,rrwebNodeId:void 0,type:e.type,width:0,x:0,y:0};if(!await e.locator.isVisible().catch(()=>!1))return;let r=await e.locator.boundingBox().catch(()=>null);if(r==null)return;let n=await e.locator.evaluate(rl).catch(()=>{})??void 0;return{height:Math.round(r.height),label:e.label,rrwebNodeId:n,type:e.type,width:Math.round(r.width),x:Math.round(r.x),y:Math.round(r.y)}}function yt({node:e,page:t}){if(e.type==="assertUrl")return[{label:e.type,type:"urlBar"}];if(e.type==="drag"){let o=L({locator:e.source,page:t,variables:void 0}),i=L({locator:e.target,page:t,variables:void 0});return[{label:"drag-source",locator:o,type:"action"},{label:"drag-target",locator:i,type:"action"}]}if(!il(e))return[];let r=e.type.startsWith("assert")?"assertion":"action",n=L({locator:e.locator,page:t,variables:void 0});return[{label:e.type,locator:n,type:r}]}function il(e){return"locator"in e&&e.locator!=null}function y({description:e,execute:t,name:r,schema:n}){let o=sl.toJSONSchema(n,{target:"draft-2020-12"});return{anthropicTool:{description:e,input_schema:{...o,type:"object"},name:r},name:r,async execute(i,s){let a=n.parse(s);return{...await Promise.resolve(t(i,a)),kind:"action"}}}}async function k(e){let t=e.specNode==null?[]:yt({node:e.specNode,page:e.page}),r=await we({page:e.page,runStartTime:e.runStartTime,targets:t}),n=[...e.assertions],o={annotations:r.annotations,assertions:n,detail:e.detail,duration:Math.round(e.duration),nodeId:`agent-step-${String(e.stepIndex)}`,nodeType:e.nodeType,recordingEndMs:void 0,recordingStartMs:void 0,snapshotTimestamp:r.snapshotTimestamp,status:e.status,stepIndex:e.stepIndex,title:e.title,url:r.url,viewportHeight:r.viewportHeight,viewportWidth:r.viewportWidth},i=n.length>0?n.map(s=>`${s.status}: ${s.description} \u2014 ${s.detail??""}`).join(`
|
|
16
|
+
`):`${e.status}: ${e.title}`;return{specNode:e.specNode,stepResult:o,toolOutput:i}}var al=Ln.object({selector:Ln.string().describe("CSS selector for the checkbox or radio button")}),_n=y({description:"Assert that a checkbox or radio button is checked",name:"assert_checked",schema:al,execute:async(e,t)=>{let r=performance.now(),n=await e.page.locator(t.selector).isChecked().catch(()=>!1),o=n?"passed":"failed",i=[{description:`Element ${t.selector} is checked`,detail:n?void 0:"Element is not checked",status:o}];return k({assertions:i,detail:n?"Element is checked":"Element is not checked",duration:performance.now()-r,nodeType:"assertChecked",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:o,stepIndex:e.stepIndex,title:`Assert checked: ${t.selector}`})}});import{z as Un}from"zod";var ll=Un.object({selector:Un.string().describe("CSS selector for the element to check focus on")}),Vn=y({description:"Assert that an element has keyboard focus. Use for accessibility tab-order testing.",name:"assert_focused",schema:ll,execute:async(e,t)=>{let r=performance.now(),o=!!await e.page.locator(t.selector).evaluate("(el) => document.activeElement === el").catch(()=>!1),i=o?"passed":"failed",s=[{description:`Element ${t.selector} is focused`,detail:o?void 0:"Element does not have focus",status:i}];return k({assertions:s,detail:o?"Element is focused":"Element does not have focus",duration:performance.now()-r,nodeType:"assertFocused",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:i,stepIndex:e.stepIndex,title:`Assert focused: ${t.selector}`})}});import{z as dr}from"zod";var cl=dr.object({expected:dr.string().describe("The expected text content"),selector:dr.string().describe("CSS selector for the element to check")}),Fn=y({description:"Assert that an element's text content matches the expected value",name:"assert_text",schema:cl,execute:async(e,t)=>{let r=performance.now(),n=await e.page.locator(t.selector).textContent({timeout:5e3}).catch(()=>null),o=n!=null&&n.includes(t.expected),i=o?"passed":"failed",s=[{description:`Text contains "${t.expected}"`,detail:`Actual: "${n??"(not found)"}"`,status:i}];return k({assertions:s,detail:o?`Text matches: "${t.expected}"`:`Expected "${t.expected}", got "${n??"(not found)"}"`,duration:performance.now()-r,nodeType:"assertText",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:i,stepIndex:e.stepIndex,title:`Assert text: ${t.selector}`})}});import{z as ur}from"zod";var dl=ur.object({expected:ur.string().describe("Expected page title or substring"),operator:ur.enum(["equals","contains","startsWith","endsWith"]).describe("Comparison operator").default("contains")}),Mn=y({description:"Assert that the page title matches an expected value",name:"assert_title",schema:dl,execute:async(e,t)=>{let r=performance.now(),n=await e.page.title(),o=ul({actual:n,expected:t.expected,operator:t.operator}),i=o?"passed":"failed",s=[{description:`Title ${t.operator} "${t.expected}"`,detail:o?void 0:`Got: "${n}"`,status:i}],a=`agent-step-${String(e.stepIndex)}`,l={expected:{type:"static",value:t.expected},id:a,operator:t.operator,type:"assertTitle"};return k({assertions:s,detail:o?"Title matches":`Expected title ${t.operator} "${t.expected}", got "${n}"`,duration:performance.now()-r,nodeType:"assertTitle",page:e.page,runStartTime:e.runStartTime,specNode:l,status:i,stepIndex:e.stepIndex,title:`Assert title ${t.operator} "${t.expected}"`})}});function ul({actual:e,expected:t,operator:r}){return r==="equals"?e===t:r==="contains"?e.includes(t):r==="startsWith"?e.startsWith(t):r==="endsWith"?e.endsWith(t):!1}import{z as Hn}from"zod";var pl=Hn.object({selector:Hn.string().describe("CSS selector for the element to check")}),Wn=y({description:"Assert that an element matching the selector is visible on the page",name:"assert_visible",schema:pl,execute:async(e,t)=>{let r=performance.now(),n=await e.page.locator(t.selector).isVisible().catch(()=>!1),o=n?"passed":"failed",i=[{description:`Element ${t.selector} is visible`,detail:n?"Element is visible":"Element is not visible",status:o}];return k({assertions:i,detail:n?"Element is visible":"Element is not visible",duration:performance.now()-r,nodeType:"assertVisible",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:o,stepIndex:e.stepIndex,title:`Assert visible: ${t.selector}`})}});import{z as qn}from"zod";var ml=qn.object({selector:qn.string().describe("CSS selector for the checkbox to check")}),Bn=y({description:"Check a checkbox matching the CSS selector",name:"check",schema:ml,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).check({timeout:5e3}),k({assertions:[],detail:`Checked ${t.selector}`,duration:performance.now()-r,nodeType:"check",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Check ${t.selector}`})}});import{z as zn}from"zod";var fl=zn.object({selector:zn.string().describe("CSS selector for the input to clear")}),Gn=y({description:"Clear the contents of an input field",name:"clear",schema:fl,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).clear({timeout:5e3}),k({assertions:[],detail:`Cleared ${t.selector}`,duration:performance.now()-r,nodeType:"clear",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Clear ${t.selector}`})}});import{z as Kn}from"zod";var gl=Kn.object({selector:Kn.string().describe("CSS selector for the element to click")}),Jn=y({description:"Click an element matching the CSS selector",name:"click",schema:gl,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).click({timeout:5e3}),k({assertions:[],detail:`Clicked ${t.selector}`,duration:performance.now()-r,nodeType:"click",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Click ${t.selector}`})}});import{z as pr}from"zod";var yl=pr.object({action:pr.enum(["read","write"]).describe("Whether to read from or write to the clipboard"),value:pr.string().optional().describe("Text to write (required for write action)")}),Yn=y({description:"Read from or write to the browser clipboard. For write, provide the text value. For read, the clipboard contents are returned.",name:"clipboard",schema:yl,execute:async(e,t)=>{let r=performance.now(),n=`agent-step-${String(e.stepIndex)}`;if(t.action==="write"){if(t.value==null)throw new Error("clipboard write requires a value");let s=JSON.stringify(t.value);await e.page.evaluate(`navigator.clipboard.writeText(${s})`);let a={action:"write",id:n,type:"clipboard",value:{type:"static",value:t.value}};return k({assertions:[],detail:`Wrote to clipboard: "${t.value}"`,duration:performance.now()-r,nodeType:"clipboard",page:e.page,runStartTime:e.runStartTime,specNode:a,status:"passed",stepIndex:e.stepIndex,title:"Clipboard write"})}let o=String(await e.page.evaluate("navigator.clipboard.readText()")),i={action:"read",id:n,type:"clipboard"};return k({assertions:[],detail:`Clipboard contents: "${o}"`,duration:performance.now()-r,nodeType:"clipboard",page:e.page,runStartTime:e.runStartTime,specNode:i,status:"passed",stepIndex:e.stepIndex,title:"Clipboard read"})}});import{z as ht}from"zod";var Xn=ht.object({summary:ht.string().describe("This is the ONLY output the user sees. If the agent profile specifies an Output format, follow those instructions exactly. Otherwise, provide a summary of your findings."),verdict:ht.enum(["pass","fail"]).describe("Whether the test passed or failed. If the agent profile defines Success Criteria, base this verdict on whether those criteria were met.")}),Qn={anthropicTool:{description:"Call this tool when you have finished your evaluation. If the agent profile defines an Output section, the summary MUST follow those output instructions exactly. Otherwise, summarize your findings.",input_schema:{...ht.toJSONSchema(Xn,{target:"draft-2020-12"}),type:"object"},name:"complete_test"},name:"complete_test",execute(e,t){let r=Xn.parse(t),n={kind:"verdict",summary:r.summary,toolOutput:`Verdict: ${r.verdict}
|
|
17
|
+
${r.summary}`,verdict:r.verdict};return Promise.resolve(n)}};import{z as Zn}from"zod";var hl=Zn.object({selector:Zn.string().describe("CSS selector for the element to extract text from")}),eo=y({description:"Extract the text content of an element matching the CSS selector. Returns the text so you can use it in assertions or decisions.",name:"extract_text",schema:hl,execute:async(e,t)=>{let r=performance.now(),o=await e.page.locator(t.selector).textContent({timeout:5e3})??"";return k({assertions:[],detail:`Extracted text: "${o}"`,duration:performance.now()-r,nodeType:"extractText",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Extract text from ${t.selector}`})}});import{z as mr}from"zod";var wl=mr.object({selector:mr.string().describe("CSS selector for the input element"),value:mr.string().describe("The text to type into the element")}),to=y({description:"Clear and type text into an input element matching the CSS selector",name:"fill",schema:wl,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).fill(t.value,{timeout:5e3}),k({assertions:[],detail:`Filled ${t.selector} with "${t.value}"`,duration:performance.now()-r,nodeType:"fill",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Fill ${t.selector}`})}});import{z as ro}from"zod";var bl=ro.object({level:ro.string().describe("Filter by log level: 'error', 'warning', 'log', 'info', 'debug', or 'all'").default("all")}),no=y({description:"Get console log messages from the browser. Optionally filter by level (error, warning, log, info, debug, all).",name:"get_console_logs",schema:bl,execute:(e,t)=>{let r=t.level==="all"?e.monitor.consoleEntries:e.monitor.consoleEntries.filter(o=>o.level===t.level);if(r.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No console ${t.level==="all"?"messages":t.level+" messages"} recorded.`};let n=r.map(o=>Sl(o)).join(`
|
|
18
18
|
`);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(r.length)} console messages:
|
|
19
|
-
${n}`}}});function
|
|
20
|
-
`),s=n.length>
|
|
21
|
-
(showing last ${String(
|
|
22
|
-
${i}`}}});import{z as
|
|
19
|
+
${n}`}}});function Sl(e){let t=e.url.length>0?` (${e.url})`:"";return`[${e.level.toUpperCase()}] ${e.text}${t}`}import{z as oo}from"zod";var fr=50,vl=oo.object({urlFilter:oo.string().describe("Optional regex to filter network entries by URL. Omit to see all.").default("")}),io=y({description:"Get a summary of network requests/responses. Shows method, URL, status code, and content type. Optionally filter by URL regex.",name:"get_network_log",schema:vl,execute:(e,t)=>{let r=t.urlFilter.length>0?new RegExp(t.urlFilter,"i"):void 0,n=r==null?e.monitor.networkEntries:e.monitor.networkEntries.filter(a=>r.test(a.url));if(n.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:"No network requests recorded."};let o=n.slice(-fr),i=o.map(a=>{let l=a.statusCode==null?"pending":String(a.statusCode),c=a.responseHeaders["content-type"]??"";return`${a.method} ${l} ${a.url} [${c}]`}).join(`
|
|
20
|
+
`),s=n.length>fr?`
|
|
21
|
+
(showing last ${String(fr)} of ${String(n.length)})`:"";return{specNode:void 0,stepResult:void 0,toolOutput:`${String(o.length)} network requests:${s}
|
|
22
|
+
${i}`}}});import{z as so}from"zod";var kl=so.object({urlPattern:so.string().describe("Regex pattern to match the request URL")}),ao=y({description:"Get the full response body for a specific network request matching the URL pattern. Returns the most recent match.",name:"get_network_response",schema:kl,execute:(e,t)=>{let r=new RegExp(t.urlPattern,"i"),n=e.monitor.networkEntries.filter(l=>r.test(l.url));if(n.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No network requests matching: ${t.urlPattern}`};let o=n.at(-1);if(o==null)return{specNode:void 0,stepResult:void 0,toolOutput:`No network requests matching: ${t.urlPattern}`};let i=o.statusCode==null?"pending":String(o.statusCode),s=Object.entries(o.responseHeaders).map(([l,c])=>` ${l}: ${c}`).join(`
|
|
23
23
|
`),a=o.responseBody??"(no body captured)";return{specNode:void 0,stepResult:void 0,toolOutput:`${o.method} ${i} ${o.url}
|
|
24
24
|
|
|
25
25
|
Response Headers:
|
|
26
26
|
${s}
|
|
27
27
|
|
|
28
28
|
Body:
|
|
29
|
-
${a}`}}});import{z as
|
|
29
|
+
${a}`}}});import{z as lo}from"zod";var Rl=lo.object({selector:lo.string().optional().describe("CSS selector to scope the tree to a subtree (defaults to full page)")}),co=y({description:"Get the accessibility tree (ARIA snapshot) of the current page or a specific element. Use this to verify ARIA roles, labels, states, and the semantic structure of the page.",name:"get_accessibility_tree",schema:Rl,execute:async(e,t)=>{let r=t.selector==null?e.page.locator(":root"):e.page.locator(t.selector);try{return{specNode:void 0,stepResult:void 0,toolOutput:await r.ariaSnapshot()}}catch{return{specNode:void 0,stepResult:void 0,toolOutput:"(unable to capture accessibility tree)"}}}});import{z as xl}from"zod";var Pl=xl.object({}),uo=y({description:"Get a text representation of the current page content for inspection",name:"get_page_content",schema:Pl,execute:async(e,t)=>{let r=await e.page.locator("body").textContent({timeout:5e3}),n=e.page.url(),o=await e.page.title();return{specNode:void 0,stepResult:void 0,toolOutput:`URL: ${n}
|
|
30
30
|
Title: ${o}
|
|
31
31
|
|
|
32
|
-
${r??""}`}}});import{z as
|
|
32
|
+
${r??""}`}}});import{z as Cl}from"zod";var El=Cl.object({}),po=y({description:"Get uncaught JavaScript exceptions (page errors) that have occurred. These are runtime errors thrown in the browser that were not caught by error handlers.",name:"get_page_errors",schema:El,execute:(e,t)=>{if(e.monitor.pageErrors.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:"No page errors recorded."};let r=e.monitor.pageErrors.map((n,o)=>`--- Error ${String(o+1)} ---
|
|
33
33
|
${n}`).join(`
|
|
34
34
|
|
|
35
35
|
`);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(e.monitor.pageErrors.length)} page errors:
|
|
36
36
|
|
|
37
|
-
${r}`}}});import{z as
|
|
37
|
+
${r}`}}});import{z as mo}from"zod";var Tl=mo.object({type:mo.enum(["all","cookies","localStorage","sessionStorage"]).describe("Which storage to retrieve").default("all")}),go=y({description:"Get browser storage state: cookies (with httpOnly, secure, sameSite flags), localStorage, and/or sessionStorage. Useful for verifying authentication state, security cookie flags, and stored data.",name:"get_storage",schema:Tl,execute:async(e,t)=>({specNode:void 0,stepResult:void 0,toolOutput:[...t.type==="all"||t.type==="cookies"?[await Al(e.page)]:[],...t.type==="all"||t.type==="localStorage"?[await fo(e.page,"localStorage")]:[],...t.type==="all"||t.type==="sessionStorage"?[await fo(e.page,"sessionStorage")]:[]].join(`
|
|
38
38
|
|
|
39
|
-
`)})});async function
|
|
39
|
+
`)})});async function Al(e){let t=await e.context().cookies();if(t.length===0)return`## Cookies
|
|
40
40
|
(none)`;let r=t.map(n=>` ${n.name}=${n.value} (domain=${n.domain}, httpOnly=${String(n.httpOnly)}, secure=${String(n.secure)}, sameSite=${n.sameSite})`);return`## Cookies (${String(t.length)})
|
|
41
41
|
${r.join(`
|
|
42
|
-
`)}`}async function
|
|
43
|
-
${String(r)}`}import{z as
|
|
42
|
+
`)}`}async function fo(e,t){let r=await e.evaluate(`JSON.stringify(Object.fromEntries(Object.entries(${t})))`);return`## ${t}
|
|
43
|
+
${String(r)}`}import{z as gr}from"zod";var $l=gr.object({action:gr.enum(["accept","dismiss"]).describe("Whether to accept or dismiss the dialog"),promptText:gr.string().optional().describe("Text to enter for prompt dialogs")}),yo=y({description:"Set up a handler for the next browser dialog (alert, confirm, prompt). Call this BEFORE the action that triggers the dialog.",name:"handle_dialog",schema:$l,execute:(e,t)=>{let r=performance.now();e.page.once("dialog",async i=>{t.action==="accept"?await i.accept(t.promptText??void 0):await i.dismiss()});let n=`agent-step-${String(e.stepIndex)}`,o={action:t.action,id:n,type:"handleDialog"};return k({assertions:[],detail:`Dialog handler set: ${t.action}`,duration:performance.now()-r,nodeType:"handleDialog",page:e.page,runStartTime:e.runStartTime,specNode:o,status:"passed",stepIndex:e.stepIndex,title:`Handle dialog: ${t.action}`})}});import{z as ho}from"zod";var Il=ho.object({selector:ho.string().describe("CSS selector for the element to hover over")}),wo=y({description:"Hover over an element matching the CSS selector",name:"hover",schema:Il,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).hover({timeout:5e3}),k({assertions:[],detail:`Hovered over ${t.selector}`,duration:performance.now()-r,nodeType:"hover",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Hover ${t.selector}`})}});import{z as yr}from"zod";var jl=yr.object({permission:yr.string().describe("Permission name (e.g. geolocation, notifications, camera, clipboard-read)"),state:yr.enum(["granted","prompt"]).describe("Permission state to set")}),bo=y({description:"Set a browser permission state (geolocation, notifications, camera, etc.)",name:"set_permission",schema:jl,execute:async(e,t)=>{let r=performance.now(),n=e.page.context();t.state==="granted"?await n.grantPermissions([t.permission]):await n.clearPermissions();let i={id:`agent-step-${String(e.stepIndex)}`,permission:t.permission,state:t.state,type:"setPermission"};return k({assertions:[],detail:`Set ${t.permission} to ${t.state}`,duration:performance.now()-r,nodeType:"setPermission",page:e.page,runStartTime:e.runStartTime,specNode:i,status:"passed",stepIndex:e.stepIndex,title:`Set permission: ${t.permission} \u2192 ${t.state}`})}});import{z as So}from"zod";var Nl=So.object({url:So.string().describe("The URL to navigate to")}),vo=y({description:"Navigate the browser to a URL",name:"navigate",schema:Nl,execute:async(e,t)=>{let r=performance.now();await e.page.goto(t.url,{waitUntil:"domcontentloaded"});let o={id:`agent-step-${String(e.stepIndex)}`,type:"goto",url:{type:"static",value:t.url}};return k({assertions:[],detail:`Navigated to ${t.url}`,duration:performance.now()-r,nodeType:"goto",page:e.page,runStartTime:e.runStartTime,specNode:o,status:"passed",stepIndex:e.stepIndex,title:`Navigate to ${t.url}`})}});import{z as ko}from"zod";var Ol=ko.object({key:ko.string().describe("Key to press, e.g. 'Enter', 'Tab', 'Escape'")}),Ro=y({description:"Press a keyboard key",name:"press",schema:Ol,execute:async(e,t)=>{let r=performance.now();await e.page.keyboard.press(t.key);let o={id:`agent-step-${String(e.stepIndex)}`,key:t.key,type:"press"};return k({assertions:[],detail:`Pressed ${t.key}`,duration:performance.now()-r,nodeType:"press",page:e.page,runStartTime:e.runStartTime,specNode:o,status:"passed",stepIndex:e.stepIndex,title:`Press ${t.key}`})}});import{z as hr}from"zod";var Dl=hr.object({height:hr.number().int().positive().describe("Viewport height in pixels"),width:hr.number().int().positive().describe("Viewport width in pixels")}),xo=y({description:"Resize the browser viewport to the specified dimensions. Use this to test responsive layouts at different screen sizes (e.g. mobile: 375x812, tablet: 768x1024, desktop: 1440x900).",name:"resize_viewport",schema:Dl,execute:async(e,t)=>{let r=performance.now();await e.page.setViewportSize({height:t.height,width:t.width});let n=`agent-step-${String(e.stepIndex)}`,o={height:t.height,id:n,type:"setViewport",width:t.width};return k({assertions:[],detail:`Resized viewport to ${String(t.width)}x${String(t.height)}`,duration:performance.now()-r,nodeType:"setViewport",page:e.page,runStartTime:e.runStartTime,specNode:o,status:"passed",stepIndex:e.stepIndex,title:`Resize viewport to ${String(t.width)}x${String(t.height)}`})}});import{z as Po}from"zod";var Ll=Po.object({selector:Po.string().describe("CSS selector for the element to right-click")}),Co=y({description:"Right-click an element to open the context menu",name:"right_click",schema:Ll,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).click({button:"right",timeout:5e3}),k({assertions:[],detail:`Right-clicked ${t.selector}`,duration:performance.now()-r,nodeType:"rightClick",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Right-click ${t.selector}`})}});import{z as Eo}from"zod";var _l=Eo.object({pattern:Eo.string().describe("Regex pattern to search console log messages")}),To=y({description:"Search console log messages for a regex pattern. Returns matching entries.",name:"search_console",schema:_l,execute:(e,t)=>{let r=new RegExp(t.pattern,"i"),n=e.monitor.consoleEntries.filter(i=>r.test(i.text));if(n.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No console messages matching: ${t.pattern}`};let o=n.map(i=>Ul(i)).join(`
|
|
44
44
|
`);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(n.length)} matching console messages:
|
|
45
|
-
${o}`}}});function
|
|
45
|
+
${o}`}}});function Ul(e){let t=e.url.length>0?` (${e.url})`:"";return`[${e.level.toUpperCase()}] ${e.text}${t}`}import{z as Ao}from"zod";var Vl=Ao.object({pattern:Ao.string().describe("Regex pattern to search across network request URLs and response bodies")}),$o=y({description:"Search network requests and response bodies for a regex pattern. Useful for finding API calls, tokens, or specific data in responses.",name:"search_network",schema:Vl,execute:(e,t)=>{let r=new RegExp(t.pattern,"i"),n=e.monitor.networkEntries.filter(i=>r.test(i.url)||i.responseBody!=null&&r.test(i.responseBody));if(n.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No network entries matching: ${t.pattern}`};let o=n.map(i=>{let s=i.statusCode==null?"pending":String(i.statusCode),a=r.test(i.url)?" [URL match]":"",l=i.responseBody!=null&&r.test(i.responseBody)?" [body match]":"";return`${i.method} ${s} ${i.url}${a}${l}`}).join(`
|
|
46
46
|
`);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(n.length)} matching network entries:
|
|
47
|
-
${o}`}}});import{z as
|
|
48
|
-
`),o=
|
|
47
|
+
${o}`}}});import{z as Io}from"zod";var Fl=20,Ml=2,Hl=Io.object({pattern:Io.string().describe("Regex pattern to search for in the page HTML")}),jo=y({description:"Search the current page's full HTML/DOM for a regex pattern. Returns matching lines with context. Useful for finding elements, attributes, text content, or hidden data without reading the entire page.",name:"search_page",schema:Hl,execute:async(e,t)=>{let n=(await e.page.content()).split(`
|
|
48
|
+
`),o=Wl({contextLines:Ml,lines:n,maxResults:Fl,pattern:t.pattern});return o.length===0?{specNode:void 0,stepResult:void 0,toolOutput:`No matches found for pattern: ${t.pattern}`}:{specNode:void 0,stepResult:void 0,toolOutput:o.join(`
|
|
49
49
|
---
|
|
50
|
-
`)}}});function
|
|
51
|
-
`);i.push(d)}),i}import{z as
|
|
52
|
-
${u.stack??""}`)}function c(u){let f=u.failure(),b=new
|
|
53
|
-
`);async function
|
|
50
|
+
`)}}});function Wl({contextLines:e,lines:t,maxResults:r,pattern:n}){let o=new RegExp(n,"i"),i=[];return t.forEach((s,a)=>{if(i.length>=r||!o.test(s))return;let l=Math.max(0,a-e),c=Math.min(t.length-1,a+e),d=t.slice(l,c+1).map((u,f)=>{let b=l+f+1;return`${l+f===a?">":" "} ${String(b)}: ${u}`}).join(`
|
|
51
|
+
`);i.push(d)}),i}import{z as wr}from"zod";var ql=wr.object({selector:wr.string().describe("CSS selector for the select element"),value:wr.string().describe("The option value to select")}),No=y({description:"Select an option from a dropdown/select element",name:"select",schema:ql,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).selectOption(t.value,{timeout:5e3}),k({assertions:[],detail:`Selected "${t.value}" in ${t.selector}`,duration:performance.now()-r,nodeType:"select",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Select ${t.value}`})}});import{z as Oo}from"zod";var Bl=Oo.object({selector:Oo.string().describe("CSS selector for the checkbox to uncheck")}),Do=y({description:"Uncheck a checkbox matching the CSS selector",name:"uncheck",schema:Bl,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).uncheck({timeout:5e3}),k({assertions:[],detail:`Unchecked ${t.selector}`,duration:performance.now()-r,nodeType:"uncheck",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Uncheck ${t.selector}`})}});var wt=class{method;requestHeaders;requestPostData;timestamp;url;responseBody=void 0;responseHeaders={};statusCode=void 0;constructor(t){this.method=t.method(),this.requestHeaders=t.headers(),this.requestPostData=t.postData()??void 0,this.timestamp=Date.now(),this.url=t.url()}applyResponse(t){this.statusCode=t.status(),this.responseHeaders=t.headers(),t.text().then(r=>{this.responseBody=r.length>1e5?`${r.slice(0,1e5)}... (truncated)`:r}).catch(()=>{this.responseBody="(unable to read body)"})}};function Ze(e){let t=[],r=[],n=[],o=new Map;function i(u){t.push({level:u.type(),text:u.text(),timestamp:Date.now(),url:u.location().url})}function s(u){let f=new wt(u);o.set(u,f),r.push(f)}function a(u){let f=o.get(u.request());f!=null&&(o.delete(u.request()),f.applyResponse(u))}function l(u){n.push(`${u.message}
|
|
52
|
+
${u.stack??""}`)}function c(u){let f=u.failure(),b=new wt(u);b.responseBody=`(request failed: ${f?.errorText??"unknown"})`,r.push(b)}e.on("console",i),e.on("request",s),e.on("response",a),e.on("pageerror",l),e.on("requestfailed",c);function d(){e.off("console",i),e.off("request",s),e.off("response",a),e.off("pageerror",l),e.off("requestfailed",c)}return{consoleEntries:t,detach:d,networkEntries:r,pageErrors:n}}var br=[vo,Jn,to,Ro,Bn,Do,No,wo,uo,jo,Gn,Co,yo,Yn,bo,Wn,Fn,Mn,_n,Vn,no,io,ao,po,co,go,To,$o,xo,eo,Qn],zl=new Map(br.map(e=>[e.name,e])),Sr=br.map(e=>e.anthropicTool),Lo=br.map(e=>`- **${e.name}**: ${e.anthropicTool.description??""}`).join(`
|
|
53
|
+
`);async function _o({input:e,monitor:t,name:r,page:n,runStartTime:o,stepIndex:i}){let s=zl.get(r);if(s==null)throw new Error(`Unknown agent tool: ${r}`);return s.execute({monitor:t,page:n,runStartTime:o,stepIndex:i},e)}import lv from"fs";import dv from"path";import Gl from"pino";var g=Gl({transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}});var Jl=50,Uo=16384;async function vr({baseUrl:e,executedPreconditions:t,extraVariables:r,onStep:n,page:o,runId:i,serverUrl:s,spec:a,systemPrompt:l,token:c,workflowContext:d}){let u=new Kl({apiKey:"ripplo",baseURL:`${s}/api/proxy/anthropic`,defaultHeaders:{Authorization:`Bearer ${c}`,"x-run-id":i}}),f=performance.now(),b=Ze(o);await nc({baseUrl:e,page:o});let w=Ql({extraVariables:r,spec:a}),h=ec({baseUrl:e,executedPreconditions:t,spec:a,systemPrompt:l,variables:w,workflowContext:d}),v=tc({baseUrl:e,spec:a,variables:w}),_=[{content:rc({page:o,startUrl:v}),role:"user"}],B=[],O=[],U={findings:"",stepIndex:0,verdict:void 0};U=await Yl({client:u,messages:_,monitor:b,onStep:n,page:o,runStartTime:f,specNodes:O,state:U,steps:B,system:h}),U.verdict==null&&(U=await Xl({client:u,messages:_,monitor:b,onStep:n,page:o,runStartTime:f,specNodes:O,state:U,steps:B,system:h}));let ie=ic(O);return{findings:U.findings,generatedSpec:ie,monitor:b,steps:B,verdict:U.verdict??"fail"}}function Vo({result:e,state:t}){return{findings:e.newFindings.length>0?e.newFindings:t.findings,stepIndex:e.nextStepIndex,verdict:e.verdict??t.verdict}}async function Yl({client:e,messages:t,monitor:r,onStep:n,page:o,runStartTime:i,specNodes:s,state:a,steps:l,system:c}){let d=a;for(let u=0;u<Jl;u++){g.info("Agent iteration %d",u+1);let f=await e.messages.create({max_tokens:Uo,messages:t,model:"server-controlled",system:c,tools:Sr}),b=await Fo({messages:t,monitor:r,onStep:n,page:o,response:f,runStartTime:i,specNodes:s,stepIndex:d.stepIndex,steps:l});if(d=Vo({result:b,state:d}),!b.continueLoop)break}return d}async function Xl({client:e,messages:t,monitor:r,onStep:n,page:o,runStartTime:i,specNodes:s,state:a,steps:l,system:c}){g.warn("Agent exited without calling complete_test \u2014 forcing completion"),t.push({content:"You must call the complete_test tool now with your verdict and summary. Do not perform any more actions \u2014 just call complete_test.",role:"user"});let d=await e.messages.create({max_tokens:Uo,messages:t,model:"server-controlled",system:c,tool_choice:{name:"complete_test",type:"tool"},tools:Sr}),u=await Fo({messages:t,monitor:r,onStep:n,page:o,response:d,runStartTime:i,specNodes:s,stepIndex:a.stepIndex,steps:l});return Vo({result:u,state:a})}function Ql({extraVariables:e,spec:t}){let r=Zl(e,t?.variableNamespaces);return{...Xe({defs:t?.variables}),...r}}function Zl(e,t){if(e==null||t==null)return{};let r=new Map;Object.entries(t).forEach(([o,i])=>{r.set(i,o)});let n={};return Object.entries(e).forEach(([o,i])=>{let s=r.get(o);Object.entries(i).forEach(([a,l])=>{n[s==null?a:`${s}.${a}`]=l})}),n}function ec({baseUrl:e,executedPreconditions:t,spec:r,systemPrompt:n,variables:o,workflowContext:i}){let s=i==null?"":[`
|
|
54
54
|
|
|
55
55
|
## Workflow Under Test`,`**Name:** ${i.name}`,`**Description:** ${i.description}`,`**Expected Outcome:** ${i.expectedOutcome}`,`
|
|
56
56
|
Focus your testing ONLY on this specific workflow. Do not test unrelated parts of the application.`].join(`
|
|
@@ -71,61 +71,61 @@ Do not repeat any of these steps.`,d=Object.entries(o),u=d.map(([b,w])=>`- **${b
|
|
|
71
71
|
|
|
72
72
|
## Resolved Variables
|
|
73
73
|
${u}`;return[`You are testing the application at: ${e}`,"Use the provided tools to navigate, interact with, and assert things about the page.","Use get_page_content to inspect the page when you need to understand what's on screen.","Follow the workflow steps to complete the task.",`
|
|
74
|
-
## Available Tools`,
|
|
74
|
+
## Available Tools`,Lo,s,c,a,f,`
|
|
75
75
|
## Agent Profile (HIGHEST PRIORITY \u2014 these instructions override any defaults above)`,n].join(`
|
|
76
|
-
`)}function
|
|
77
|
-
`),nextStepIndex:a,verdict:void 0};let u=[],f=a,b,w;for(let
|
|
78
|
-
`);return{continueLoop:b==null&&o.stop_reason==="tool_use",newFindings:h,nextStepIndex:f,verdict:b}}async function
|
|
76
|
+
`)}function tc({baseUrl:e,spec:t,variables:r}){if(t==null)return e;let n=t.nodes[t.entryNode];if(n==null||n.type!=="goto"||n.url.type!=="static")return e;let i=n.url.value.replaceAll(/\{\{(\w+)\}\}/g,(s,a)=>{let l=r[a];return l==null?`{{${a}}}`:typeof l=="object"?JSON.stringify(l):String(l)});return i.startsWith("http")?i:`${e}${i.startsWith("/")?"":"/"}${i}`}function rc({page:e,startUrl:t}){let r=e.url();return r!=="about:blank"&&r.length>0?`You are already on the page at ${r}. Begin testing from this page \u2014 do not navigate away unless the workflow requires it.`:`Navigate to ${t} and begin testing.`}async function nc({baseUrl:e,page:t}){let r=new URL(e).origin;await t.route("**/*",n=>{let o=n.request();return o.isNavigationRequest()&&new URL(o.url()).origin!==r?(g.warn("Blocked navigation to off-origin URL: %s",o.url()),n.abort("blockedbyclient")):n.continue()})}async function Fo({messages:e,monitor:t,onStep:r,page:n,response:o,runStartTime:i,specNodes:s,stepIndex:a,steps:l}){let c=o.content.filter(v=>v.type==="text").map(v=>v.text),d=o.content.filter(v=>v.type==="tool_use");if(d.length===0)return{continueLoop:!1,newFindings:c.join(`
|
|
77
|
+
`),nextStepIndex:a,verdict:void 0};let u=[],f=a,b,w;for(let v of d){let E=await oc({block:v,monitor:t,onStep:r,page:n,runStartTime:i,specNodes:s,stepIndex:f,steps:l});u.push(E.toolResult),f=E.nextStepIndex,E.verdict!=null&&(b=E.verdict,w=E.summary)}e.push({content:o.content,role:"assistant"},{content:u,role:"user"});let h=w??c.join(`
|
|
78
|
+
`);return{continueLoop:b==null&&o.stop_reason==="tool_use",newFindings:h,nextStepIndex:f,verdict:b}}async function oc({block:e,monitor:t,onStep:r,page:n,runStartTime:o,specNodes:i,stepIndex:s,steps:a}){try{let l=await _o({input:e.input,monitor:t,name:e.name,page:n,runStartTime:o,stepIndex:s}),c={content:l.toolOutput,tool_use_id:e.id,type:"tool_result"};return l.kind==="verdict"?(g.info(" [%d] %s \u2014 verdict: %s",s,e.name,l.verdict),{nextStepIndex:s,summary:l.summary,toolResult:c,verdict:l.verdict}):(l.specNode!=null&&i.push(l.specNode),l.stepResult!=null?(a.push(l.stepResult),r?.(l.stepResult),g.info(" [%d] %s \u2014 %s",s,e.name,l.stepResult.status),{nextStepIndex:s+1,summary:void 0,toolResult:c,verdict:void 0}):(g.info(" [%d] %s \u2014 info",s,e.name),{nextStepIndex:s,summary:void 0,toolResult:c,verdict:void 0}))}catch(l){let c=l instanceof Error?l.message:"Unknown error";g.error(" [%d] %s \u2014 error: %s",s,e.name,c);let d=await we({page:n,runStartTime:o,targets:[]}),u={annotations:d.annotations,assertions:[],detail:`Error: ${c}`,duration:0,nodeId:`agent-step-${String(s)}`,nodeType:"click",recordingEndMs:void 0,recordingStartMs:void 0,snapshotTimestamp:d.snapshotTimestamp,status:"failed",stepIndex:s,title:`${e.name} (error)`,url:d.url,viewportHeight:d.viewportHeight,viewportWidth:d.viewportWidth};return a.push(u),r?.(u),{nextStepIndex:s+1,summary:void 0,toolResult:{content:`Error: ${c}`,is_error:!0,tool_use_id:e.id,type:"tool_result"},verdict:void 0}}}function ic(e){if(e.length===0)return{entryNode:"",nodes:{}};let t={};e.forEach((n,o)=>{let i=e[o+1],s=i==null?n:{...n,next:i.id};t[n.id]=s});let r=e[0];if(r==null)throw new Error("Expected at least one spec node after length check");return{entryNode:r.id,nodes:t}}function kr({description:e,output:t,successCriteria:r}){let n=[`## Agent Identity
|
|
79
79
|
${e}`];t!=null&&t.length>0&&n.push(`## Output
|
|
80
80
|
${t}`),r!=null&&r.length>0&&n.push(`## Success Criteria
|
|
81
|
-
${r}`);let o=["## Completing Your Evaluation",'When you finish your evaluation, you MUST call the `complete_test` tool with your verdict ("pass" or "fail") and a `summary` string.',
|
|
81
|
+
${r}`);let o=["## Completing Your Evaluation",'When you finish your evaluation, you MUST call the `complete_test` tool with your verdict ("pass" or "fail") and a `summary` string.',sc({hasSuccessCriteria:r!=null&&r.length>0}),ac({hasOutput:t!=null&&t.length>0})];return n.push(o.join(`
|
|
82
82
|
`)),n.join(`
|
|
83
83
|
|
|
84
|
-
`)}function
|
|
84
|
+
`)}function sc({hasSuccessCriteria:e}){return e?"Base your verdict strictly on the Success Criteria defined above. A test passes ONLY if all success criteria are met, and fails if any criterion is not met. Individual step failures during exploration do not necessarily mean the test failed, but the success criteria are the ultimate authority for your verdict.":"Base your verdict on whether the workflow worked correctly. Individual step failures during exploration do not necessarily mean the test failed."}function ac({hasOutput:e}){return e?'The `summary` parameter is the ONLY output the user will see. You MUST use the `summary` field for EXACTLY the output described in the "Output" section above \u2014 nothing else. Do not describe what you did, do not list steps, do not add a test summary. The `summary` must contain ONLY what the Output section asks for, word for word if it specifies exact text.':"Include a brief summary of what you found in the `summary` parameter."}import{execFile as lc}from"child_process";import{createRequire as cc}from"module";import Mo from"fs";import Ho from"path";import{chromium as Wo}from"playwright";async function Ce({headed:e}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";try{return await Wo.launch({headless:!e})}catch(t){throw dc(t)?new Error(`Playwright browsers are not installed. Run:
|
|
85
85
|
|
|
86
86
|
npx playwright install chromium
|
|
87
|
-
`):t}}async function
|
|
87
|
+
`):t}}async function Rr(){let e=Wo.executablePath();if(Mo.existsSync(e))return;g.info("Chromium not found. Installing via Playwright...");let t=cc(import.meta.url),r=Ho.dirname(t.resolve("playwright/package.json")),n=Ho.join(r,"cli.js");if(await new Promise((o,i)=>{lc(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!Mo.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
|
|
88
88
|
|
|
89
89
|
npx playwright install chromium
|
|
90
|
-
`);g.info("\u2713 Chromium installed")}function
|
|
90
|
+
`);g.info("\u2713 Chromium installed")}function dc(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{mkdir as xr,writeFile as se}from"fs/promises";import J from"path";async function bt({context:e,page:t,runId:r,stepIndex:n,stepResult:o}){try{let i=J.join(process.cwd(),".ripplo","debug",r,"steps",String(n));await xr(i,{recursive:!0});let s={annotations:o.annotations,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,viewportHeight:o.viewportHeight,viewportWidth:o.viewportWidth};await Promise.all([se(J.join(i,"info.json"),JSON.stringify(s,null,2)),uc({context:e,page:t,stepDir:i})])}catch(i){let s=i instanceof Error?i.message:String(i);g.warn("Failed to write step debug data for step %d: %s",n,s)}}async function uc({context:e,page:t,stepDir:r}){let[n,o,i,s]=await Promise.all([t.content().catch(()=>"(unable to capture DOM)"),pc(t),mc({context:e,page:t}),t.screenshot({fullPage:!1}).catch(()=>{})]);await Promise.all([se(J.join(r,"dom.html"),n),se(J.join(r,"accessibility-tree.txt"),o),se(J.join(r,"storage.json"),JSON.stringify(i,null,2)),s==null?Promise.resolve():se(J.join(r,"screenshot.png"),s)])}async function pc(e){try{return await e.locator(":root").ariaSnapshot()}catch{return"(unable to capture accessibility tree)"}}async function mc({context:e,page:t}){let[r,n]=await Promise.all([t.evaluate(()=>({localStorage:Object.fromEntries(Array.from({length:localStorage.length},(o,i)=>{let s=localStorage.key(i);return s==null?void 0:[s,localStorage.getItem(s)??""]}).filter(o=>o!=null)),sessionStorage:Object.fromEntries(Array.from({length:sessionStorage.length},(o,i)=>{let s=sessionStorage.key(i);return s==null?void 0:[s,sessionStorage.getItem(s)??""]}).filter(o=>o!=null))})).catch(()=>({localStorage:{},sessionStorage:{}})),e.cookies().catch(()=>[])]);return{cookies:n,localStorage:r.localStorage,sessionStorage:r.sessionStorage}}async function St({monitor:e,runId:t,steps:r,summary:n}){try{let o=J.join(process.cwd(),".ripplo","debug",t);await xr(o,{recursive:!0}),await Promise.all([se(J.join(o,"summary.txt"),fc({steps:r,summary:n})),se(J.join(o,"console.log"),gc(e.consoleEntries)),se(J.join(o,"network.jsonl"),yc(e.networkEntries)),se(J.join(o,"page-errors.log"),e.pageErrors.join(`
|
|
91
91
|
---
|
|
92
|
-
`))]),g.info("Debug artifacts written to .ripplo/debug/%s/",t)}catch(o){let i=o instanceof Error?o.message:String(o);g.warn("Failed to write run debug summary: %s",i)}}function
|
|
93
|
-
`)}function
|
|
94
|
-
`)}function
|
|
95
|
-
`)}async function
|
|
92
|
+
`))]),g.info("Debug artifacts written to .ripplo/debug/%s/",t)}catch(o){let i=o instanceof Error?o.message:String(o);g.warn("Failed to write run debug summary: %s",i)}}function fc({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(`
|
|
93
|
+
`)}function gc(e){return e.map(t=>`[${new Date(t.timestamp).toISOString()}] [${t.level.toUpperCase()}] (${t.url}) ${t.text}`).join(`
|
|
94
|
+
`)}function yc(e){return e.map(t=>JSON.stringify(t)).join(`
|
|
95
|
+
`)}async function qo({error:e,runId:t,stack:r,workflowName:n}){try{let o=J.join(process.cwd(),".ripplo","debug",t);await xr(o,{recursive:!0});let i=r==null?e:`${e}
|
|
96
96
|
|
|
97
97
|
${r}`,s=[`Run ID: ${t}`,`Workflow: ${n}`,"Status: failed","",`Error: ${e}`,"",r==null?"":`Stack trace:
|
|
98
98
|
${r}`].join(`
|
|
99
|
-
`);await Promise.all([se(J.join(o,"error.txt"),i),se(J.join(o,"summary.txt"),s)]),g.info("Debug error artifacts written to .ripplo/debug/%s/",t)}catch(o){let i=o instanceof Error?o.message:String(o);g.warn("Failed to write error debug artifacts: %s",i)}}import{readFileSync as
|
|
100
|
-
`),
|
|
101
|
-
`+
|
|
102
|
-
`),w={body:
|
|
99
|
+
`);await Promise.all([se(J.join(o,"error.txt"),i),se(J.join(o,"summary.txt"),s)]),g.info("Debug error artifacts written to .ripplo/debug/%s/",t)}catch(o){let i=o instanceof Error?o.message:String(o);g.warn("Failed to write error debug artifacts: %s",i)}}import{readFileSync as hc}from"fs";import{createRequire as wc}from"module";import Bo from"path";import{gzipSync as bc}from"zlib";var Sc=wc(import.meta.url),vc=Sc.resolve("rrweb"),kc=Bo.join(Bo.dirname(vc),"rrweb.umd.min.cjs"),Rc=hc(kc,"utf8"),xc=[";(function() {"," try {"," if (window.__ripploRrwebLoaded) return;"," window.__ripploRrwebLoaded = true;"," window.__ripploRrwebBuffer = [];"," window.__ripploRrwebDrain = function() {"," var out = window.__ripploRrwebBuffer;"," window.__ripploRrwebBuffer = [];"," return out;"," };"," var r = window.rrweb;"," if (r == null || r.record == null) {"," console.warn('[ripplo] rrweb global not found');"," return;"," }"," function startRecording() {"," if (window.__ripploRrwebStartedAt != null) return;"," window.__ripploRrwebStartedAt = Date.now();"," var stop = r.record({"," emit: function(event) { window.__ripploRrwebBuffer.push(event); },"," recordCanvas: false,"," recordCrossOriginIframes: false,"," });"," if (r.record.mirror) window.__ripploRrwebMirror = r.record.mirror;"," 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(`
|
|
100
|
+
`),Pc=Rc+`
|
|
101
|
+
`+xc;function Cc(){return globalThis.__ripploRrwebStartedAt}function Ec(){globalThis.__ripploRrwebStart?.()}function Tc(){globalThis.__ripploRrwebStop?.()}function Ac(){return globalThis.__ripploRrwebDrain?.()??[]}async function vt(e){let t,r=0;async function n(){await e.addScriptTag({content:Pc}).catch(()=>{})}await n(),e.on("load",()=>{n()});async function o(){await e.evaluate(Ec).catch(()=>{});let l=await e.evaluate(Cc).catch(()=>{});typeof l=="number"&&(t??=l)}function i(){if(t!=null)return Date.now()-t}async function s(){let l=await e.evaluate(Ac).catch(()=>[]),c=l[0],d=l.at(-1);if(c==null||d==null)return;t??=c.timestamp;let u=t,f=l.map(h=>JSON.stringify(h)).join(`
|
|
102
|
+
`),w={body:bc(Buffer.from(f,"utf8")),chunkIndex:r,endTimestamp:d.timestamp-u,eventCount:l.length,startTimestamp:c.timestamp-u};return r+=1,w}async function a(){await e.evaluate(Tc).catch(()=>{})}return{currentOffsetMs:i,detach:a,start:o,takeChunk:s}}async function Pr({baseUrl:e,cookies:t,executedPreconditions:r,extraVariables:n,headed:o,runId:i,serverUrl:s,spec:a,streaming:l,systemPrompt:c,token:d,workflowContext:u}){let f=await Ce({headed:o}),b=await f.newContext({baseURL:e});t.length>0&&(await b.addCookies([...t]),g.info("Injected %d cookies from preconditions",t.length));let w=await b.newPage(),h=await vt(w);async function v(){let B=await h.takeChunk();B!=null&&l.enqueueRecordingChunk(B)}let E=setInterval(()=>{v()},2e3);await h.start();try{let B=function(le){let Ge={...le,recordingEndMs:h.currentOffsetMs(),recordingStartMs:le.recordingStartMs??h.currentOffsetMs()};l.enqueueStep(Ge),l.flushSteps(),bt({context:b,page:w,runId:i,stepIndex:Ge.stepIndex,stepResult:Ge})};var _=B;let O=await vr({baseUrl:e,executedPreconditions:r,extraVariables:n,onStep:B,page:w,runId:i,serverUrl:s,spec:a,systemPrompt:c,token:d,workflowContext:u}),U=O.verdict==="pass"?"passed":"failed";await l.complete({statusOverride:U,steps:O.steps,summary:O.findings});let ie=O.steps.filter(le=>le.status==="passed").length,Ae=O.steps.filter(le=>le.status==="failed").length,D={duration:O.steps.reduce((le,Ge)=>le+Ge.duration,0),failCount:Ae,passCount:ie,runId:i,status:U,workflowName:u.name};await St({monitor:O.monitor,runId:i,steps:O.steps,summary:D}),g.info("Agent test complete: %d passed, %d failed",ie,Ae),g.info(`
|
|
103
103
|
=== Agent Summary ===
|
|
104
|
-
%s`,
|
|
104
|
+
%s`,O.findings)}finally{clearInterval(E),await h.detach(),await v(),await f.close()}}async function Cr({expected:e,locator:t,operator:r,timeout:n}){let o=await t.textContent({timeout:n});return et({actual:o??"",expected:e,label:"Text",operator:r})}function kt({expected:e,operator:t,url:r}){return et({actual:r,expected:e,label:"URL",operator:t})}async function Er({expected:e,locator:t,operator:r}){let n=await t.count();return Zo({actual:n,expected:e,label:"Count",operator:r})}async function Tr({expected:e,locator:t,operator:r,timeout:n}){let o=await t.inputValue({timeout:n});return et({actual:o,expected:e,label:"Value",operator:r})}async function Ar({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),{description:"Element is visible",detail:void 0,status:"passed"}}catch{return{description:"Element is visible",detail:"Element not visible",status:"failed"}}}async function $r({locator:e,timeout:t}){try{return await e.waitFor({state:"hidden",timeout:t}),{description:"Element is not visible",detail:void 0,status:"passed"}}catch{return{description:"Element is not visible",detail:"Element still visible",status:"failed"}}}async function zo({attribute:e,expected:t,locator:r,operator:n,timeout:o}){let i=await r.getAttribute(e,{timeout:o});return et({actual:i??"",expected:t,label:`Attribute "${e}"`,operator:n})}async function Go({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isEnabled()?{description:"Element is enabled",detail:void 0,status:"passed"}:{description:"Element is enabled",detail:"Element is disabled",status:"failed"}}catch{return{description:"Element is enabled",detail:"Element not found",status:"failed"}}}async function Ko({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isDisabled()?{description:"Element is disabled",detail:void 0,status:"passed"}:{description:"Element is disabled",detail:"Element is enabled",status:"failed"}}catch{return{description:"Element is disabled",detail:"Element not found",status:"failed"}}}async function Jo({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isChecked()?{description:"Element is checked",detail:void 0,status:"passed"}:{description:"Element is checked",detail:"Element is not checked",status:"failed"}}catch{return{description:"Element is checked",detail:"Element not found",status:"failed"}}}async function Yo({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isChecked()?{description:"Element is not checked",detail:"Element is checked",status:"failed"}:{description:"Element is not checked",detail:void 0,status:"passed"}}catch{return{description:"Element is not checked",detail:"Element not found",status:"failed"}}}async function Xo({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),!await e.evaluate("(el) => document.activeElement === el")?{description:"Element is focused",detail:"Element is not focused",status:"failed"}:{description:"Element is focused",detail:void 0,status:"passed"}}catch{return{description:"Element is focused",detail:"Element not found",status:"failed"}}}async function Qo({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),!!await e.evaluate("(el) => document.activeElement === el")?{description:"Element is not focused",detail:"Element is focused",status:"failed"}:{description:"Element is not focused",detail:void 0,status:"passed"}}catch{return{description:"Element is not focused",detail:"Element not found",status:"failed"}}}function et(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=$c(e),n=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:n,status:r?"passed":"failed"}}function $c({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 Zo(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=Ic(e),n=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:n,status:r?"passed":"failed"}}function Ic({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{readdir as _c,rm as Uc,stat as Vc}from"fs/promises";import Gv from"os";import ri from"path";import{graphql as Fc}from"gql.tada";import{print as jc}from"graphql";var Nc=15e3;async function S(e){let t=jc(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(Nc)})}catch(s){let a=s instanceof Error?s.message:String(s);throw new Error(`Failed to connect to Ripplo server at ${e.config.ripploServerUrl}. Make sure \`npx ripplo\` is running and your internet connection is active. Details: ${a}`)}let i=await Oc({res:o,url:n});if(!Dc(i))throw new Error("Invalid GraphQL response");if(Lc(i))throw new Error(i.errors.map(s=>s.message).join(", "));if(i.data==null)throw new Error("No data returned from server");return i.data}async function Oc({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 Dc(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function Lc(e){return Array.isArray(e.errors)&&e.errors.length>0}var ei=ri.join(process.cwd(),".ripplo","debug"),ti=360*60*1e3,Qv=Fc(`
|
|
105
105
|
mutation RevokeCurrentCliToken {
|
|
106
106
|
revokeCurrentCliToken
|
|
107
107
|
}
|
|
108
|
-
`);async function
|
|
109
|
-
`))}}import
|
|
110
|
-
`),t}function
|
|
111
|
-
`,{mode:384})}function
|
|
112
|
-
\u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function
|
|
113
|
-
Load \`/ripplo:setup\` skill for instructions on engine endpoint + webhook secret wiring.`,status:"failed"}:t.kind==="pass"?{description:`observer "${e}"`,detail:n.pollCount>1?`passed after ${String(n.pollCount)} polls (${
|
|
114
|
-
Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function _d({apiUrl:e,observer:t,params:r,webhookSecret:n}){let o=JSON.stringify({observer:t,params:r});try{let i=await fetch(`${e}/execute-observer`,{body:o,headers:{"Content-Type":"application/json",...ve({body:o,secret:n})},method:"PUT",signal:AbortSignal.timeout(jd)});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=Ld.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 g.error("observer request failed: %s",s),{kind:"transport-error",reason:s}}}function Ud({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function di(e){return`${String(Math.round(performance.now()-e))}ms`}async function Vd(e){return new Promise(t=>setTimeout(t,e))}async function Y({fn:e,label:t}){let r=performance.now(),n=await e();return g.info("%s: %dms",t,Math.round(performance.now()-r)),n}var Fd=1e4;async function Wr({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return Wd({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function Md({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function Wd({currentId:e,failFast:t,getRecordingOffsetMs:r,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],d=l,u=e;for(;u!=null;){let f=a.nodes[u];if(f==null)throw new Error(`Node "${u}" not found in spec`);let b=u,w=f.label??`${f.type} (${u})`;g.info("Executing node: %s [%s]",w,f.type);let h=await Hd({getRecordingOffsetMs:r,node:f,nodeId:b,observerTransport:n,page:i,runStartTime:s,variables:d});if(Md({onStep:o,steps:[h],target:c}),d=h.variables,t&&h.status==="failed")break;u=f.next}return{steps:c,variables:d}}async function Hd({getRecordingOffsetMs:e,node:t,nodeId:r,observerTransport:n,page:o,runStartTime:i,variables:s}){let a=performance.now(),l=e?.(),c=t.label??`${t.type} (${t.id})`,d=Fd,u=ft({node:t,page:o});try{let f=await qd({node:t,observerTransport:n,page:o,timeout:d,variables:s}),b=Math.round(performance.now()-a),w=f.assertions.some(C=>C.status==="failed"),h=await Y({label:`Snapshot [${c}]`,fn:()=>he({page:o,runStartTime:i,targets:u})}),S=e?.();return{annotations:h.annotations,assertions:f.assertions,detail:void 0,duration:b,nodeId:r,nodeType:t.type,recordingEndMs:S,recordingStartMs:l,snapshotTimestamp:h.snapshotTimestamp,status:w?"failed":"passed",stepIndex:0,title:c,url:h.url,variables:f.variables,viewportHeight:h.viewportHeight,viewportWidth:h.viewportWidth}}catch(f){let b=Math.round(performance.now()-a),w=f instanceof Error?f.message:String(f),h=await Y({label:`Snapshot [${c}] (error)`,fn:()=>he({page:o,runStartTime:i,targets:u})}),S=e?.();return{annotations:h.annotations,assertions:[],detail:w,duration:b,nodeId:r,nodeType:t.type,recordingEndMs:S,recordingStartMs:l,snapshotTimestamp:h.snapshotTimestamp,status:"failed",stepIndex:0,title:c,url:h.url,variables:s,viewportHeight:h.viewportHeight,viewportWidth:h.viewportWidth}}}async function qd({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(Bd(e)){let s=await sr({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await Gd({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function Bd(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 zd(e){return e.type.startsWith("assert")}async function Gd({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!zd(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 Kd({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=G({ref:i.expected,variables:o});return[await Rr({expected:s,locator:D({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=G({ref:i.expected,variables:o});return[St({expected:s,operator:i.operator,url:r.url()})]}case"assertTitle":{let s=G({ref:i.expected,variables:o});return[St({expected:s,operator:i.operator,url:await r.title()})]}case"assertCount":{let s=ir({ref:i.expected,variables:o});return[await xr({expected:s,locator:D({locator:i.locator,page:r,variables:o}),operator:i.operator})]}case"assertValue":{let s=G({ref:i.expected,variables:o});return[await Pr({expected:s,locator:D({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=G({ref:i.expected,variables:o});return[await qo({attribute:i.attribute,expected:s,locator:D({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertObserver":{if(t==null)return[{description:`observer "${i.observer}"`,detail:"observer transport not configured \u2014 set engineUrl + webhookSecret in ripplo.config",status:"failed"}];let s={};return Object.entries(i.params).forEach(([a,l])=>{s[a]=G({ref:l,variables:o})}),[await ci({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var Jd={assertChecked:Go,assertDisabled:zo,assertEnabled:Bo,assertFocused:Ko,assertNotChecked:Jo,assertNotFocused:Yo,assertNotVisible:Cr,assertVisible:Er};async function Kd({assertNode:e,page:t,timeout:r,variables:n}){let o=Jd[e.type];return[await o({locator:D({locator:e.locator,page:t,variables:n}),timeout:r})]}async function Hr({baseUrl:e,browser:t,cookies:r,extraVariables:n,observerTransport:o,onRecordingChunk:i,onStep:s,runId:a,spec:l}){let c=await t.newContext({baseURL:e});g.info("Browser context created"),r.length>0&&await c.addCookies(r);let d=await c.newPage();g.info("Page created");let u=Xe(d),f=await bt(d);async function b(){let N=await f.takeChunk();N!=null&&i?.(N)}let w=setInterval(()=>{b()},2e3),h=[],S=!1;function C(N){s?.(N),S||(S=!0,f.start()),h.push(ht({context:c,page:d,runId:a,stepIndex:N.stepIndex,stepResult:N}))}let _=Yd(n,l.variableNamespaces),q={...Ke({defs:l.variables}),..._};g.info("Starting graph execution (entry: %s)",l.entryNode);let j=await Wr({failFast:!0,getRecordingOffsetMs:f.currentOffsetMs,observerTransport:o,onStep:C,page:d,spec:l,variables:q});await Promise.allSettled(h);let U=j.steps.filter(N=>N.status==="passed").length,ie=j.steps.filter(N=>N.status==="failed").length,Te={duration:j.steps.reduce((N,le)=>N+le.duration,0),failCount:ie,passCount:U,runId:a,status:ie>0?"failed":"passed",workflowName:""};return await wt({monitor:u,runId:a,steps:j.steps,summary:Te}),clearInterval(w),await f.detach(),await b(),await c.close(),j.steps}function Yd(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}import{parseSetCookie as Xd}from"set-cookie-parser";import{z as Z}from"zod";var ui=3e4,Qd=Z.object({data:Z.record(Z.string(),Z.record(Z.string(),Z.string())),error:Z.string().optional(),executed:Z.array(Z.string()),runId:Z.string(),success:Z.boolean()});async function qr({project:e,webhookSecret:t,workflowSlug:r}){let n={apiUrl:void 0,cookies:[],data:{},executed:[]},o=e.workflows.find(a=>a.slug===r);if(o==null)return n;let i=e.engineBaseUrl.length===0?void 0:e.engineBaseUrl,s=o.preconditions;return s.length===0?{...n,apiUrl:i}:i==null?n:pi({apiUrl:i,preconditionNames:s,webhookSecret:t})}async function Br({apiUrl:e,cookies:t,data:r,executed:n,webhookSecret:o}){if(n.length!==0)try{let i=JSON.stringify({data:r,preconditions:n}),s=await fetch(`${e}/teardown-preconditions`,{body:i,headers:{"Content-Type":"application/json",...ru({cookies:t}),...ve({body:i,secret:o})},method:"PUT",signal:AbortSignal.timeout(ui)});s.ok||g.error("Teardown returned %s",String(s.status))}catch{g.error("Teardown request failed")}}async function pi({apiUrl:e,preconditionNames:t,webhookSecret:r}){let n=performance.now(),o=JSON.stringify({preconditions:t}),i=await fetch(`${e}/execute-preconditions`,{body:o,headers:{"Content-Type":"application/json",...ve({body:o,secret:r})},method:"PUT",signal:AbortSignal.timeout(ui)});if(!i.ok){let c=await eu(i);throw new Error(`execute-preconditions returned ${String(i.status)}: ${c}`)}let s=await i.json(),a=Qd.safeParse(s);if(!a.success)throw new Error(`execute-preconditions response has invalid shape: ${a.error.message}`);if(!a.data.success){let c=a.data.error??"no error detail";throw new Error(`Precondition batch failed: ${c}`)}let l=nu({domain:new URL(e).hostname,res:i});return g.info("Preconditions resolved: %s (%dms)",a.data.executed.join(", "),Math.round(performance.now()-n)),{apiUrl:e,cookies:l,data:a.data.data,executed:a.data.executed}}var Zd=Z.object({error:Z.string()});async function eu(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=tu(t),n=r==null?null:Zd.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function tu(e){try{return JSON.parse(e)}catch{return null}}function ru({cookies:e}){return e.length===0?{}:{Cookie:e.map(r=>`${r.name}=${r.value}`).join("; ")}}function nu({domain:e,res:t}){let r=t.headers.getSetCookie();return Xd(r,{decodeValues:!1}).map(o=>ou({cookie:o,domain:e}))}function ou({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=su({raw:e.sameSite})),e.expires!=null?r.expires=Math.floor(e.expires.getTime()/1e3):e.maxAge!=null&&(r.expires=Math.floor(Date.now()/1e3)+e.maxAge),r}var iu={lax:"Lax",none:"None",strict:"Strict"};function su({raw:e}){return iu[e.toLowerCase()]??"Lax"}async function zr({engineBaseUrl:e,preconditionNames:t,webhookSecret:r}){let n=e.length===0?void 0:e;return n==null||t.length===0?{apiUrl:n,cookies:[],data:{},executed:[]}:pi({apiUrl:n,preconditionNames:t,webhookSecret:r})}import{graphql as $t}from"gql.tada";async function Gr({agentProfileId:e,config:t,runId:r}){let n=await k({config:t,document:cu,variables:{agentProfileId:e??null,platform:"chromium",runId:r}});if(n.startRun==null)throw new Error("Failed to start run");let o=n.startRun.id,i=[];function s(d){let u=lu({config:t,runResultId:o,steps:[d]}).catch(f=>{g.error(f,"Failed to submit step %d",d.stepIndex)});i.push(u)}function a(d){let u=au({chunk:d,config:t,runResultId:o}).catch(f=>{g.error(f,"Failed to submit recording chunk %d",d.chunkIndex)});i.push(u)}async function l(){await Promise.all(i)}async function c({statusOverride:d,steps:u,summary:f}){await Y({label:`flushSteps (${String(i.length)} steps)`,fn:()=>Promise.all(i)});let b=u.filter(C=>C.status==="passed").length,w=u.filter(C=>C.status==="failed").length,h=u.reduce((C,_)=>C+_.duration,0),S=d??(w>0?"failed":"passed");await Y({label:"completeRun",fn:()=>k({config:t,document:pu,variables:{duration:h,failCount:w,passCount:b,runResultId:o,status:S,summary:f??null,warnCount:0}})})}return{complete:c,enqueueRecordingChunk:a,enqueueStep:s,flushSteps:l,runResultId:o}}async function au({chunk:e,config:t,runResultId:r}){await k({config:t,document:uu,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runResultId:r,startTimestamp:e.startTimestamp}}})}async function lu({config:e,runResultId:t,steps:r}){let n=r.map(o=>({annotations:o.annotations.map(i=>({height:i.height,label:i.label,rrwebNodeId:i.rrwebNodeId??null,type:i.type,width:i.width,x:i.x,y:i.y})),assertions:o.assertions.map(i=>({description:i.description,detail:i.detail,status:i.status})),detail:o.detail,duration:o.duration,nodeType:o.nodeType,recordingEndMs:o.recordingEndMs??null,recordingStartMs:o.recordingStartMs??null,snapshotTimestamp:o.snapshotTimestamp,status:o.status,stepIndex:o.stepIndex,title:o.title,url:o.url,viewportHeight:o.viewportHeight,viewportWidth:o.viewportWidth}));await k({config:e,document:du,variables:{runResultId:t,steps:n}})}var cu=$t(`
|
|
108
|
+
`);async function Ir({maxRuns:e}){try{let r=(await _c(ei,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let d=ri.join(ei,c.name),u=await Vc(d);return{dirPath:d,mtime:u.mtimeMs}})),i=o.filter(c=>n-c.mtime>ti),a=o.filter(c=>n-c.mtime<=ti).toSorted((c,d)=>d.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>Uc(c.dirPath,{force:!0,recursive:!0}))),g.info("Pruned %d old debug run(s)",l.length)}catch{g.warn("Debug run pruning failed, ignoring")}}var Mc=5e3;async function jr({appUrl:e}){try{await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(Mc)})}catch(t){let r=t instanceof Error?t.message:String(t);throw g.debug("App URL reachability check failed: %s",r),new Error([`Could not reach your dev server at ${e}.`,"","Troubleshooting:",` 1. Make sure your app is running at ${e}`," 2. Check RIPPLO_APP_URL in the env file declared in .ripplo/project.json"," 3. If you're in a git worktree, RIPPLO_APP_URL and RIPPLO_ENGINE_URL must point at this worktree's dev server port (not main's)"].join(`
|
|
109
|
+
`))}}import ot from"fs";import Ee from"fs";import Hc from"os";import tt from"path";var Wc=".local",qc=".ripplo";function Nr(e){return tt.join(e,".ripplo",Wc)}function rt(e){let t=Nr(e);Ee.existsSync(t)||Ee.mkdirSync(t,{recursive:!0});let r=tt.join(t,".gitignore");return Ee.existsSync(r)||Ee.writeFileSync(r,`*
|
|
110
|
+
`),t}function nt(e,t){return tt.join(Nr(e),t)}function Or(){return tt.join(Hc.homedir(),qc)}function Dr(){let e=Or();return Ee.existsSync(e)?Ee.chmodSync(e,448):Ee.mkdirSync(e,{mode:448,recursive:!0}),e}function be(e){return tt.join(Or(),e)}function re(){let e=process.env.RIPPLO_TOKEN;if(e!=null&&e.trim().length>0)return e.trim();let t=be("token");if(!ot.existsSync(t))return null;let r=ot.readFileSync(t,"utf8").trim();return r.length===0?null:r}function Lr(e){Dr(),ot.writeFileSync(be("token"),e+`
|
|
111
|
+
`,{mode:384})}function _r(){let e=be("token");return ot.existsSync(e)?(ot.unlinkSync(e),!0):!1}import{z as me}from"zod";import{z as Rt}from"zod";var Bc=Rt.object({__codec:Rt.string().min(1),data:Rt.unknown(),version:Rt.number().int().positive()}),xt=class extends Error{codec;currentVersion;gotVersion;constructor(t){super(`Unsupported ${t.codec} version ${String(t.gotVersion)} (current ${String(t.currentVersion)}). Upgrade Ripplo or rebuild with a compatible CLI.`),this.name="CodecVersionError",this.codec=t.codec,this.currentVersion=t.currentVersion,this.gotVersion=t.gotVersion}},Pt=class extends Error{constructor(t){super(`Codec mismatch: expected "${t.expected}", got "${t.got}"`),this.name="CodecMismatchError"}};function Ct(e){return ni({legacy:void 0,migrators:[],name:e,schemas:[]})}function ni(e){return{initial:t=>Ur(t,{...e,schemas:[t]}),legacy:t=>ni({...e,legacy:t})}}function Ur(e,t){return{build:()=>zc(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 zc(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Gc(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Gc(e,t,r){let{data:n,version:o}=Kc(t,r),i=oi(t,n,o);return e.parse(i)}function Kc(e,t){let r=Bc.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new Pt({expected:e.name,got:r.data.__codec});return{data:r.data.data,version:r.data.version}}if(e.legacy!=null&&e.legacy.detect(t))return{data:t,version:e.legacy.assumedVersion};throw new Error(`Cannot decode "${e.name}": value is not a codec envelope and no legacy detector matched.`)}function oi(e,t,r){let n=e.schemas.length;if(r>n)throw new xt({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 oi(e,s(i),r+1)}import{z as li}from"zod";import{z as Oe}from"zod";var Vr=Oe.object({depends:Oe.array(Oe.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:Oe.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Oe.array(Oe.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 p}from"zod";import{z as Se}from"zod";var Jc=Se.object({by:Se.literal("testId"),value:Se.string().min(1)}),Yc=Se.object({by:Se.literal("role"),name:Se.string().optional(),role:Se.string().min(1)}),T=Se.discriminatedUnion("by",[Jc,Yc]);import{z as ii}from"zod";var ve=ii.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Et=ii.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as M}from"zod";var Xc=M.object({type:M.literal("static"),value:M.union([M.string(),M.number(),M.boolean()])}),Fr=M.object({name:M.string().min(1),type:M.literal("variable")}),Tt=M.discriminatedUnion("type",[Xc,Fr]),Y=M.discriminatedUnion("type",[M.object({type:M.literal("static"),value:M.string()}),Fr]),At=M.discriminatedUnion("type",[M.object({type:M.literal("static"),value:M.number().int().nonnegative()}),Fr]);import{z as Q}from"zod";var $t=Q.discriminatedUnion("type",[Q.object({default:Q.string().optional(),type:Q.literal("string")}),Q.object({default:Q.number().optional(),type:Q.literal("number")}),Q.object({default:Q.boolean().optional(),type:Q.literal("boolean")}),Q.object({key:Q.string().min(1),type:Q.literal("env")})]);var P={id:p.string().min(1).max(200),label:p.string().max(500).optional(),next:p.string().max(200).optional(),uiOnly:p.boolean().optional()},si=500,Qc=p.object({...P,type:p.literal("goto"),url:Y}),Zc=p.object({...P,locator:T,type:p.literal("click")}),ed=p.object({...P,locator:T,type:p.literal("fill"),value:Y}),td=p.object({...P,locator:T,type:p.literal("select"),value:Y}),rd=p.object({...P,locator:T,type:p.literal("hover")}),nd=p.object({...P,key:p.string().min(1),locator:T.optional(),type:p.literal("press")}),od=p.object({...P,locator:T,type:p.literal("check")}),id=p.object({...P,locator:T,type:p.literal("uncheck")}),sd=p.object({...P,height:p.number().int().positive(),type:p.literal("setViewport"),width:p.number().int().positive()}),ad=p.object({...P,message:p.string().min(1),type:p.literal("fail")}),ld=p.object({...P,type:p.literal("setVariable"),value:Tt,variable:p.string().min(1)}),cd=p.object({...P,locator:T,type:p.literal("extractText"),variable:p.string().min(1)}),dd=p.object({...P,files:p.array(p.string()).min(1),locator:T,type:p.literal("upload")}),ud=p.object({...P,locator:T,type:p.literal("dblclick")}),pd=p.object({...P,source:T,target:T,type:p.literal("drag")}),md=p.object({...P,locator:T,type:p.literal("scrollIntoView")}),fd=p.object({...P,locator:T,type:p.literal("type"),value:Y}),gd=p.object({...P,locator:T,type:p.literal("focus")}),yd=p.object({...P,locator:T,type:p.literal("clear")}),hd=p.object({...P,locator:T,type:p.literal("rightClick")}),wd=p.object({...P,action:p.enum(["accept","dismiss"]),promptText:p.string().optional(),type:p.literal("handleDialog")}),bd=p.object({...P,action:p.enum(["read","write"]),type:p.literal("clipboard"),value:Y.optional(),variable:p.string().min(1).optional()}),Sd=p.object({...P,permission:p.string().min(1),state:p.enum(["granted","prompt"]),type:p.literal("setPermission")}),vd=p.object({...P,locator:T,type:p.literal("assertVisible")}),kd=p.object({...P,locator:T,type:p.literal("assertNotVisible")}),Rd=p.object({...P,expected:Y,locator:T,operator:ve,type:p.literal("assertText")}),xd=p.object({...P,expected:Y,operator:ve,type:p.literal("assertUrl")}),Pd=p.object({...P,expected:At,locator:T,operator:Et,type:p.literal("assertCount")}),Cd=p.object({...P,expected:Y,locator:T,operator:ve,type:p.literal("assertValue")}),Ed=p.object({...P,attribute:p.string().min(1),expected:Y,locator:T,operator:ve,type:p.literal("assertAttribute")}),Td=p.object({...P,locator:T,type:p.literal("assertEnabled")}),Ad=p.object({...P,locator:T,type:p.literal("assertDisabled")}),$d=p.object({...P,expected:Y,operator:ve,type:p.literal("assertTitle")}),Id=p.object({...P,locator:T,type:p.literal("assertChecked")}),jd=p.object({...P,locator:T,type:p.literal("assertNotChecked")}),Nd=p.object({...P,locator:T,type:p.literal("assertFocused")}),Od=p.object({...P,locator:T,type:p.literal("assertNotFocused")}),Dd=p.object({...P,budget:p.enum(["fast","slow","async"]),observer:p.string().min(1).max(200),params:p.record(p.string().max(200),Y),type:p.literal("assertObserver")}),ai=p.discriminatedUnion("type",[Qc,Zc,ed,td,rd,nd,od,id,vd,kd,Rd,xd,Pd,Cd,Ed,Td,Ad,sd,ad,ld,cd,dd,ud,pd,md,fd,gd,yd,hd,wd,bd,Sd,$d,Id,jd,Nd,Od,Dd]),It=p.object({entryNode:p.string().min(1).max(200),nodes:p.record(p.string().max(200),ai).refine(e=>Object.keys(e).length<=si,`Workflow has more than ${String(si)} nodes`),uiOnly:p.boolean().optional(),variableNamespaces:p.record(p.string().max(200),p.string().max(500)).optional(),variables:p.record(p.string().max(200),$t).optional()});var Ld=li.record(li.string().max(200),Vr),_d={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},Ud={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Mr=Ct("workflow-spec").legacy(_d).initial(It).build(),Vd=Ct("precondition-map").legacy(Ud).initial(Ld).build();import{z as Hr}from"zod";var ci=["fast","slow","async"],Fd=Hr.object({budget:Hr.enum(ci).describe("Polling budget tier: fast | slow | async"),description:Hr.string().min(1).describe("Human-readable description of what this observer checks")}).describe("A named backend state observer. Tests assert against it with assert.backend(observer, params). Implementation lives on the user's server.");import{graphql as Dt,readFragment as Nt}from"gql.tada";import{z as ne}from"zod";import di from"crypto";import{Webhook as Md}from"standardwebhooks";function ke({body:e,secret:t}){let r=new Md(t),n=`msg_${di.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_${di.randomBytes(24).toString("base64")}`}var Hd=15e4,Wd={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},qd=ne.discriminatedUnion("kind",[ne.object({kind:ne.literal("pass")}),ne.object({kind:ne.literal("retry"),reason:ne.string()}),ne.object({kind:ne.literal("fail"),reason:ne.string()})]),Bd=ne.object({error:ne.string().optional(),outcome:qd.optional(),success:ne.boolean()});async function ui({apiUrl:e,budget:t,observer:r,params:n,webhookSecret:o}){let i=Wd[t],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await Gd({apiUrl:e,observer:r,params:n,webhookSecret:o}),c=zd({observer:r,outcome:l,start:s,state:a});if(c!=null)return c;let d=i.timeoutMs-(performance.now()-s);if(d<=0)break;let u=Math.min(Kd({backoff:i.backoffMs,pollCount:a.pollCount}),d);await Jd(u)}return{description:`observer "${r}"`,detail:`budget "${t}" exhausted after ${String(a.pollCount)} poll(s) (${pi(s)}); last: ${a.lastReason??"no retry reason"}
|
|
112
|
+
\u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function zd({observer:e,outcome:t,start:r,state:n}){return t.kind==="transport-error"?{description:`observer "${e}"`,detail:`transport error after ${String(n.pollCount)} poll(s): ${t.reason}
|
|
113
|
+
Load \`/ripplo:setup\` skill for instructions on engine endpoint + webhook secret wiring.`,status:"failed"}:t.kind==="pass"?{description:`observer "${e}"`,detail:n.pollCount>1?`passed after ${String(n.pollCount)} polls (${pi(r)})`:void 0,status:"passed"}:t.kind==="fail"?{description:`observer "${e}"`,detail:`failed (invariant): ${t.reason} (after ${String(n.pollCount)} poll(s)) \u2014 ctx.fail stops polling immediately and is reserved for invariant violations (wrong shape, contradictory/forbidden state). For transient conditions like "not yet committed", "status not yet X", or "row not found", use ctx.retry(reason) so the runtime keeps polling until the budget expires.
|
|
114
|
+
Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function Gd({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(Hd)});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=Bd.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 g.error("observer request failed: %s",s),{kind:"transport-error",reason:s}}}function Kd({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function pi(e){return`${String(Math.round(performance.now()-e))}ms`}async function Jd(e){return new Promise(t=>setTimeout(t,e))}async function X({fn:e,label:t}){let r=performance.now(),n=await e();return g.info("%s: %dms",t,Math.round(performance.now()-r)),n}var Yd=1e4;async function qr({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return Qd({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function Xd({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function Qd({currentId:e,failFast:t,getRecordingOffsetMs:r,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],d=l,u=e;for(;u!=null;){let f=a.nodes[u];if(f==null)throw new Error(`Node "${u}" not found in spec`);let b=u,w=f.label??`${f.type} (${u})`;g.info("Executing node: %s [%s]",w,f.type);let h=await Zd({getRecordingOffsetMs:r,node:f,nodeId:b,observerTransport:n,page:i,runStartTime:s,variables:d});if(Xd({onStep:o,steps:[h],target:c}),d=h.variables,t&&h.status==="failed")break;u=f.next}return{steps:c,variables:d}}async function Zd({getRecordingOffsetMs:e,node:t,nodeId:r,observerTransport:n,page:o,runStartTime:i,variables:s}){let a=performance.now(),l=e?.(),c=t.label??`${t.type} (${t.id})`,d=Yd,u=yt({node:t,page:o});try{let f=await eu({node:t,observerTransport:n,page:o,timeout:d,variables:s}),b=Math.round(performance.now()-a),w=f.assertions.some(E=>E.status==="failed"),h=await X({label:`Snapshot [${c}]`,fn:()=>we({page:o,runStartTime:i,targets:u})}),v=e?.();return{annotations:h.annotations,assertions:f.assertions,detail:void 0,duration:b,nodeId:r,nodeType:t.type,recordingEndMs:v,recordingStartMs:l,snapshotTimestamp:h.snapshotTimestamp,status:w?"failed":"passed",stepIndex:0,title:c,url:h.url,variables:f.variables,viewportHeight:h.viewportHeight,viewportWidth:h.viewportWidth}}catch(f){let b=Math.round(performance.now()-a),w=f instanceof Error?f.message:String(f),h=await X({label:`Snapshot [${c}] (error)`,fn:()=>we({page:o,runStartTime:i,targets:u})}),v=e?.();return{annotations:h.annotations,assertions:[],detail:w,duration:b,nodeId:r,nodeType:t.type,recordingEndMs:v,recordingStartMs:l,snapshotTimestamp:h.snapshotTimestamp,status:"failed",stepIndex:0,title:c,url:h.url,variables:s,viewportHeight:h.viewportHeight,viewportWidth:h.viewportWidth}}}async function eu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(tu(e)){let s=await cr({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await nu({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function tu(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 ru(e){return e.type.startsWith("assert")}async function nu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!ru(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 iu({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=K({ref:i.expected,variables:o});return[await Cr({expected:s,locator:L({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=K({ref:i.expected,variables:o});return[kt({expected:s,operator:i.operator,url:r.url()})]}case"assertTitle":{let s=K({ref:i.expected,variables:o});return[kt({expected:s,operator:i.operator,url:await r.title()})]}case"assertCount":{let s=lr({ref:i.expected,variables:o});return[await Er({expected:s,locator:L({locator:i.locator,page:r,variables:o}),operator:i.operator})]}case"assertValue":{let s=K({ref:i.expected,variables:o});return[await Tr({expected:s,locator:L({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=K({ref:i.expected,variables:o});return[await zo({attribute:i.attribute,expected:s,locator:L({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]=K({ref:l,variables:o})}),[await ui({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var ou={assertChecked:Jo,assertDisabled:Ko,assertEnabled:Go,assertFocused:Xo,assertNotChecked:Yo,assertNotFocused:Qo,assertNotVisible:$r,assertVisible:Ar};async function iu({assertNode:e,page:t,timeout:r,variables:n}){let o=ou[e.type];return[await o({locator:L({locator:e.locator,page:t,variables:n}),timeout:r})]}async function Br({baseUrl:e,browser:t,cookies:r,extraVariables:n,observerTransport:o,onRecordingChunk:i,onStep:s,runId:a,spec:l}){let c=await t.newContext({baseURL:e});g.info("Browser context created"),r.length>0&&await c.addCookies(r);let d=await c.newPage();g.info("Page created");let u=Ze(d),f=await vt(d);async function b(){let D=await f.takeChunk();D!=null&&i?.(D)}let w=setInterval(()=>{b()},2e3),h=[],v=!1;function E(D){s?.(D),v||(v=!0,f.start()),h.push(bt({context:c,page:d,runId:a,stepIndex:D.stepIndex,stepResult:D}))}let _=su(n,l.variableNamespaces),B={...Xe({defs:l.variables}),..._};g.info("Starting graph execution (entry: %s)",l.entryNode);let O=await qr({failFast:!0,getRecordingOffsetMs:f.currentOffsetMs,observerTransport:o,onStep:E,page:d,spec:l,variables:B});await Promise.allSettled(h);let U=O.steps.filter(D=>D.status==="passed").length,ie=O.steps.filter(D=>D.status==="failed").length,Ae={duration:O.steps.reduce((D,le)=>D+le.duration,0),failCount:ie,passCount:U,runId:a,status:ie>0?"failed":"passed",workflowName:""};return await St({monitor:u,runId:a,steps:O.steps,summary:Ae}),clearInterval(w),await f.detach(),await b(),await c.close(),O.steps}function su(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}import{parseSetCookie as au}from"set-cookie-parser";import{z as Z}from"zod";var mi=3e4,lu=Z.object({data:Z.record(Z.string(),Z.record(Z.string(),Z.string())),error:Z.string().optional(),executed:Z.array(Z.string()),runId:Z.string(),success:Z.boolean()});async function zr({project:e,webhookSecret:t,workflowSlug:r}){let n={apiUrl:void 0,cookies:[],data:{},executed:[]},o=e.workflows.find(a=>a.slug===r);if(o==null)return n;let i=e.engineBaseUrl.length===0?void 0:e.engineBaseUrl,s=o.preconditions;return s.length===0?{...n,apiUrl:i}:i==null?n:fi({apiUrl:i,preconditionNames:s,webhookSecret:t})}async function Gr({apiUrl:e,cookies:t,data:r,executed:n,webhookSecret:o}){if(n.length!==0)try{let i=JSON.stringify({data:r,preconditions:n}),s=await fetch(`${e}/teardown-preconditions`,{body:i,headers:{"Content-Type":"application/json",...pu({cookies:t}),...ke({body:i,secret:o})},method:"PUT",signal:AbortSignal.timeout(mi)});s.ok||g.error("Teardown returned %s",String(s.status))}catch{g.error("Teardown request failed")}}async function fi({apiUrl:e,preconditionNames:t,webhookSecret:r}){let n=performance.now(),o=JSON.stringify({preconditions:t}),i=await fetch(`${e}/execute-preconditions`,{body:o,headers:{"Content-Type":"application/json",...ke({body:o,secret:r})},method:"PUT",signal:AbortSignal.timeout(mi)});if(!i.ok){let c=await du(i);throw new Error(`execute-preconditions returned ${String(i.status)}: ${c}`)}let s=await i.json(),a=lu.safeParse(s);if(!a.success)throw new Error(`execute-preconditions response has invalid shape: ${a.error.message}`);if(!a.data.success){let c=a.data.error??"no error detail";throw new Error(`Precondition batch failed: ${c}`)}let l=mu({domain:new URL(e).hostname,res:i});return g.info("Preconditions resolved: %s (%dms)",a.data.executed.join(", "),Math.round(performance.now()-n)),{apiUrl:e,cookies:l,data:a.data.data,executed:a.data.executed}}var cu=Z.object({error:Z.string()});async function du(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=uu(t),n=r==null?null:cu.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function uu(e){try{return JSON.parse(e)}catch{return null}}function pu({cookies:e}){return e.length===0?{}:{Cookie:e.map(r=>`${r.name}=${r.value}`).join("; ")}}function mu({domain:e,res:t}){let r=t.headers.getSetCookie();return au(r,{decodeValues:!1}).map(o=>fu({cookie:o,domain:e}))}function fu({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=yu({raw:e.sameSite})),e.expires!=null?r.expires=Math.floor(e.expires.getTime()/1e3):e.maxAge!=null&&(r.expires=Math.floor(Date.now()/1e3)+e.maxAge),r}var gu={lax:"Lax",none:"None",strict:"Strict"};function yu({raw:e}){return gu[e.toLowerCase()]??"Lax"}async function Kr({engineBaseUrl:e,preconditionNames:t,webhookSecret:r}){let n=e.length===0?void 0:e;return n==null||t.length===0?{apiUrl:n,cookies:[],data:{},executed:[]}:fi({apiUrl:n,preconditionNames:t,webhookSecret:r})}import{graphql as jt}from"gql.tada";async function Jr({agentProfileId:e,config:t,runId:r}){let n=await S({config:t,document:bu,variables:{agentProfileId:e??null,platform:"chromium",runId:r}});if(n.startRun==null)throw new Error("Failed to start run");let o=n.startRun.id,i=[];function s(d){let u=wu({config:t,runResultId:o,steps:[d]}).catch(f=>{g.error(f,"Failed to submit step %d",d.stepIndex)});i.push(u)}function a(d){let u=hu({chunk:d,config:t,runResultId:o}).catch(f=>{g.error(f,"Failed to submit recording chunk %d",d.chunkIndex)});i.push(u)}async function l(){await Promise.all(i)}async function c({statusOverride:d,steps:u,summary:f}){await X({label:`flushSteps (${String(i.length)} steps)`,fn:()=>Promise.all(i)});let b=u.filter(E=>E.status==="passed").length,w=u.filter(E=>E.status==="failed").length,h=u.reduce((E,_)=>E+_.duration,0),v=d??(w>0?"failed":"passed");await X({label:"completeRun",fn:()=>S({config:t,document:ku,variables:{duration:h,failCount:w,passCount:b,runResultId:o,status:v,summary:f??null,warnCount:0}})})}return{complete:c,enqueueRecordingChunk:a,enqueueStep:s,flushSteps:l,runResultId:o}}async function hu({chunk:e,config:t,runResultId:r}){await S({config:t,document:vu,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runResultId:r,startTimestamp:e.startTimestamp}}})}async function wu({config:e,runResultId:t,steps:r}){let n=r.map(o=>({annotations:o.annotations.map(i=>({height:i.height,label:i.label,rrwebNodeId:i.rrwebNodeId??null,type:i.type,width:i.width,x:i.x,y:i.y})),assertions:o.assertions.map(i=>({description:i.description,detail:i.detail,status:i.status})),detail:o.detail,duration:o.duration,nodeType:o.nodeType,recordingEndMs:o.recordingEndMs??null,recordingStartMs:o.recordingStartMs??null,snapshotTimestamp:o.snapshotTimestamp,status:o.status,stepIndex:o.stepIndex,title:o.title,url:o.url,viewportHeight:o.viewportHeight,viewportWidth:o.viewportWidth}));await S({config:e,document:Su,variables:{runResultId:t,steps:n}})}var bu=jt(`
|
|
115
115
|
mutation StartRunCLI($runId: String!, $platform: String!, $agentProfileId: String) {
|
|
116
116
|
startRun(runId: $runId, platform: $platform, agentProfileId: $agentProfileId) {
|
|
117
117
|
id
|
|
118
118
|
}
|
|
119
119
|
}
|
|
120
|
-
`),
|
|
120
|
+
`),Su=jt(`
|
|
121
121
|
mutation SubmitRunStepsCLI($runResultId: String!, $steps: [StepInput!]!) {
|
|
122
122
|
submitRunSteps(runResultId: $runResultId, steps: $steps)
|
|
123
123
|
}
|
|
124
|
-
`),
|
|
124
|
+
`),vu=jt(`
|
|
125
125
|
mutation SubmitRunRecordingChunkCLI($input: SubmitRunRecordingChunkInput!) {
|
|
126
126
|
submitRunRecordingChunk(input: $input)
|
|
127
127
|
}
|
|
128
|
-
`),
|
|
128
|
+
`),ku=jt(`
|
|
129
129
|
mutation CompleteRunCLI(
|
|
130
130
|
$runResultId: String!
|
|
131
131
|
$status: String!
|
|
@@ -148,7 +148,7 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
|
|
|
148
148
|
status
|
|
149
149
|
}
|
|
150
150
|
}
|
|
151
|
-
`);var
|
|
151
|
+
`);var Ru=12e4,Ot=Dt(`
|
|
152
152
|
fragment WorkflowRun on Workflow {
|
|
153
153
|
id
|
|
154
154
|
slug
|
|
@@ -160,7 +160,7 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
|
|
|
160
160
|
preconditionName
|
|
161
161
|
}
|
|
162
162
|
}
|
|
163
|
-
`),
|
|
163
|
+
`),gi=Dt(`
|
|
164
164
|
fragment ProjectRun on Project {
|
|
165
165
|
id
|
|
166
166
|
cloudBaseUrl
|
|
@@ -169,13 +169,13 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
|
|
|
169
169
|
...WorkflowRun
|
|
170
170
|
}
|
|
171
171
|
}
|
|
172
|
-
`,[
|
|
172
|
+
`,[Ot]),xu=Dt(`
|
|
173
173
|
query ProjectRun($projectId: String!) {
|
|
174
174
|
project(id: $projectId) {
|
|
175
175
|
...ProjectRun
|
|
176
176
|
}
|
|
177
177
|
}
|
|
178
|
-
`,[
|
|
178
|
+
`,[gi]),Pu=Dt(`
|
|
179
179
|
query AgentProfileRun($id: String!) {
|
|
180
180
|
agentProfile(id: $id) {
|
|
181
181
|
id
|
|
@@ -185,30 +185,30 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
|
|
|
185
185
|
successCriteria
|
|
186
186
|
}
|
|
187
187
|
}
|
|
188
|
-
`);async function
|
|
188
|
+
`);async function Yr({agentProfileDescription:e,agentProfileId:t,baseUrl:r,browser:n,config:o,headed:i,preconditionNames:s,runId:a,webhookSecret:l,workflowId:c}){let d="unknown",u,f,b=!1;try{b=n==null,f=Cu({externalBrowser:n,headed:i});let w=s==null?void 0:X({label:"Preconditions resolved",fn:()=>Kr({engineBaseUrl:o.engineUrl,preconditionNames:s,webhookSecret:l})}),[{project:h,workflow:v},E]=await Promise.all([X({label:"Run context resolved",fn:()=>Nu({config:o,workflowId:c})}),X({label:"Streaming run started",fn:()=>Jr({agentProfileId:t,config:o,runId:a})}),jr({appUrl:r})]);d=v.name,u=E;let _=Du(v.spec);g.info("Executing workflow: %s",v.name),await Uu(Tu({agentProfileDescription:e,agentProfileId:t,baseUrl:r,browserPromise:f,config:o,headed:i,ownsBrowser:b,preconditionPromise:w,project:h,runId:a,specData:_,streaming:u,webhookSecret:l,workflow:v}),_u())}catch(w){throw await Eu({browserPromise:f,error:w,ownsBrowser:b,runId:a,streaming:u,workflowName:d}),w}}function Cu({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):X({label:"Browser launched",fn:()=>Ce({headed:t})})}async function Eu({browserPromise:e,error:t,ownsBrowser:r,runId:n,streaming:o,workflowName:i}){let s=t instanceof Error?t.message:String(t),a=t instanceof Error?t.stack:void 0;await qo({error:s,runId:n,stack:a,workflowName:i}),o!=null&&await o.complete({statusOverride:"failed",steps:[],summary:s}).catch(()=>{}),r&&e!=null&&await(await e.catch(()=>{}))?.close()}async function Tu({agentProfileDescription:e,agentProfileId:t,baseUrl:r,browserPromise:n,config:o,headed:i,ownsBrowser:s,preconditionPromise:a,project:l,runId:c,specData:d,streaming:u,webhookSecret:f,workflow:b}){let w=a??X({label:"Preconditions resolved",fn:()=>zr({project:Iu(l),webhookSecret:f,workflowSlug:b.slug})}),[h,v]=await Promise.all([w,n]);if(t!=null){s&&await v.close(),await Au({agentProfileDescription:e,agentProfileId:t,baseUrl:r,config:o,headed:i,preconditionResult:h,runId:c,specData:d,streaming:u,webhookSecret:f,workflow:b});return}await ju({baseUrl:r,browser:v,preconditionResult:h,runId:c,specData:d,streaming:u,webhookSecret:f})}async function Au({agentProfileDescription:e,agentProfileId:t,baseUrl:r,config:n,headed:o,preconditionResult:i,runId:s,specData:a,streaming:l,webhookSecret:c,workflow:d}){let u=e!=null&&e.length>0?e:await Ou({config:n,profileId:t});await Pr({baseUrl:r,cookies:i.cookies,executedPreconditions:i.executed,extraVariables:i.data,headed:o,runId:s,serverUrl:n.ripploServerUrl,spec:a,streaming:l,systemPrompt:u,token:n.token,workflowContext:{description:d.name,expectedOutcome:d.name,name:d.name}}),await yi({preconditionResult:i,webhookSecret:c})}var $u=me.object({preconditions:me.array(me.string()),requiresKeys:me.array(me.object({namespace:me.string(),preconditionName:me.string()})),slug:me.string()});function Iu(e){let t=(e.workflows??[]).map(r=>{let n=Nt(Ot,r);return $u.parse(n)});return{engineBaseUrl:e.engineBaseUrl,workflows:t}}async function ju({baseUrl:e,browser:t,preconditionResult:r,runId:n,specData:o,streaming:i,webhookSecret:s}){let a=await X({label:"Spec executed",fn:()=>Br({baseUrl:e,browser:t,cookies:r.cookies,extraVariables:r.data,observerTransport:r.apiUrl==null?void 0:{apiUrl:r.apiUrl,webhookSecret:s},onRecordingChunk:i.enqueueRecordingChunk,onStep:i.enqueueStep,runId:n,spec:o})});await yi({preconditionResult:r,webhookSecret:s}),await i.complete({statusOverride:void 0,steps:a,summary:void 0});let l=a.filter(d=>d.status==="passed").length,c=a.filter(d=>d.status==="failed").length;g.info("Run complete: %d passed, %d failed",l,c)}async function yi({preconditionResult:e,webhookSecret:t}){e.apiUrl!=null&&await Gr({apiUrl:e.apiUrl,cookies:e.cookies,data:e.data,executed:e.executed,webhookSecret:t})}async function Nu({config:e,workflowId:t}){let r=await S({config:e,document:xu,variables:{projectId:e.projectId}});if(r.project==null)throw new Error("Project not found");let o={...Nt(gi,r.project),...e.engineUrl.length>0?{engineBaseUrl:e.engineUrl}:{}},s=(o.workflows??[]).find(l=>Nt(Ot,l).id===t);if(s==null)throw new Error(`Workflow ${t} not found`);let a=Nt(Ot,s);return{project:o,workflow:a}}async function Ou({config:e,profileId:t}){let r=await S({config:e,document:Pu,variables:{id:t}});if(r.agentProfile==null)throw new Error(`Agent profile not found: ${t}`);let n=r.agentProfile,o=n.description;if(o==null||o.length===0)throw new Error(`Agent profile "${n.name}" has no description`);return g.info("Using agent profile: %s",n.name),kr({description:o,output:n.output??void 0,successCriteria:n.successCriteria??void 0})}function Du(e){if(e==null)throw new Error("Workflow has no spec");return Mr.decode(e)}var Lu=me.coerce.number().int().positive().catch(Ru);function _u(){return Lu.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function Uu(e,t){let r,n=new Promise((o,i)=>{r=setTimeout(()=>{i(new Error(`Run timed out after ${String(t)}ms`))},t)});try{await Promise.race([e,n])}finally{r!=null&&clearTimeout(r)}}import{exec as qu}from"child_process";import{createAuthClient as Vu}from"better-auth/client";import{deviceAuthorizationClient as Fu}from"better-auth/client/plugins";function hi({baseURL:e}){return Vu({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[Fu()]})}import{z as wi}from"zod";var Mu="https://ripplo.ai",Hu={dev:"https://ripplo-dev.up.railway.app"};function fe(){let e=process.argv.findIndex(o=>o.startsWith("--env"));if(e===-1)return it().RIPPLO_SERVER_URL;let t=process.argv[e];if(t==null)return it().RIPPLO_SERVER_URL;let r=t.includes("=")?t.split("=")[1]:process.argv[e+1];if(r==null)return it().RIPPLO_SERVER_URL;let n=Hu[r];if(n==null)throw new Error(`Unknown env "${r}". Use "dev" \u2014 or set RIPPLO_SERVER_URL.`);return n}var Wu=wi.object({RIPPLO_SERVER_URL:wi.string().min(1).default(Mu)}),bi;function it(){return bi??=Wu.parse(process.env),bi}var Bu=5e3,Si="ripplo-cli";async function vi({onDeviceCode:e,url:t}){let r=t??it().RIPPLO_SERVER_URL,n=hi({baseURL:r}),o=await n.device.code({client_id:Si});if(o.error!=null)throw new Error(`Failed to request device code: ${o.error.error_description}`);let{device_code:i,user_code:s,verification_uri_complete:a}=o.data;e({userCode:s,verificationUrl:a}),Xu(a);let l=await zu({authClient:n,deviceCode:i});return Lr(l),l}async function zu({authClient:e,deviceCode:t}){for(;;){await Ju(Bu);let r=await e.device.token({client_id:Si,device_code:t,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(r.data?.access_token!=null)return r.data.access_token;if(r.error==null)continue;if(!Ku(r.error.error))throw new Error(`Authorization failed: ${r.error.error_description}`)}}var Gu=new Set(["authorization_pending","slow_down"]);function Ku(e){return Gu.has(e)}function Ju(e){return new Promise(t=>{setTimeout(t,e)})}function Yu(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function Xu(e){let t=Yu();qu(`${t} "${e}"`,()=>{})}function De({serverUrl:e,token:t}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:t,webhookSecret:""}}import Qu from"fs";import Zu from"path";function $(e){return Qu.existsSync(Zu.join(e,".ripplo"))}var tp=ep(`
|
|
189
189
|
query AuthViewer {
|
|
190
190
|
currentUser {
|
|
191
191
|
name
|
|
192
192
|
email
|
|
193
193
|
}
|
|
194
194
|
}
|
|
195
|
-
`);async function
|
|
195
|
+
`);async function ki(){let e=fe(),t=re();if(t!=null){let s=await Xr({serverUrl:e,token:t});if(s!=null){process.stdout.write(`Already signed in as ${s.email}. Run \`ripplo auth logout\` to switch.
|
|
196
196
|
`);return}process.stdout.write(`Your saved session expired \u2014 let's sign you back in.
|
|
197
197
|
|
|
198
|
-
`)}let r=await
|
|
198
|
+
`)}let r=await vi({url:e,onDeviceCode:s=>{process.stdout.write(`Opening your browser to finish sign-in.
|
|
199
199
|
`),process.stdout.write(`If it didn't open, visit: ${s.verificationUrl}
|
|
200
200
|
`),process.stdout.write(`Verification code: ${s.userCode}
|
|
201
201
|
|
|
202
202
|
`),process.stdout.write(`Waiting for you to approve...
|
|
203
|
-
`)}}),n=await
|
|
203
|
+
`)}}),n=await Xr({serverUrl:e,token:r}),o=$(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
|
|
204
204
|
`),process.stdout.write(n==null?`${i}.
|
|
205
|
-
`:`${i}, ${
|
|
206
|
-
`),process.stdout.write(`Session saved to ${
|
|
207
|
-
`),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
|
|
208
|
-
`)}function
|
|
209
|
-
`);return}process.stdout.write(`Removed ${
|
|
210
|
-
`)}import
|
|
211
|
-
`}async function Lt({cwd:e}){let t=Qr.join(e,ce),r=await tm(t);return r==null?null:Yu($i,r)}async function de({cwd:e,result:t}){let r=Ii(t),n=Qr.join(e,ce);await Xr.mkdir(Qr.dirname(n),{recursive:!0}),await Xr.writeFile(n,en(r),"utf8")}function Dt({compiled:e,existing:t}){if(t==null)return"missing";let r=en(Ii(e)),n=en(t);return r===n?"match":"stale"}async function tm(e){try{return await Xr.readFile(e,"utf8")}catch(t){if(rm(t)&&t.code==="ENOENT")return null;throw t}}function rm(e){return e instanceof Error&&"code"in e}function nm(e){return function(r,n){return n===e||!om(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function om(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import Vt from"fs";import an from"path";var nn=["**/src/**","**/app/**","**/apps/**","**/pages/**","**/routes/**","**/components/**","**/server/**","**/api/**","**/backend/**","**/features/**","**/modules/**","**/views/**","**/ui/**","**/hooks/**","**/contexts/**","**/providers/**","**/controllers/**","**/handlers/**","**/resolvers/**","**/services/**","**/middleware/**","**/lib/**"],Re=["**/*.gen.*","**/generated/**","**/*.d.ts","**/*.test.*","**/*.spec.*","**/node_modules/**","**/dist/**","**/build/**",".ripplo/**","**/*.md","**/.next/**","**/.turbo/**","**/.vercel/**","**/.svelte-kit/**","**/.nuxt/**","**/.astro/**","**/coverage/**","**/storybook-static/**","**/*.stories.*","**/*.story.*","**/cli/**","**/scripts/**","**/tools/**","**/__tests__/**","**/__mocks__/**","**/__fixtures__/**","**/*.config.*","**/*.setup.*","**/public/**","**/static/**","**/assets/**","**/migrations/**","**/prisma/migrations/**","**/scripts/**"];function ji(e){return e.data}function Ni(e){return{as(t){return{data:{label:t,node:e}}}}}function _t(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();im(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=>sm(a,t));return{observers:i,preconditions:o,tests:s}}function im(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 sm(e,t){let r=e.id,{accessedKeys:n,vars:o}=lm(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[am(i),...s],l=cm(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 u=um(e.requires,t);return{additionalChecks:[],coverage:e.coverage,description:e.description,expectedOutcome:e.expectedOutcome,implemented:e.implemented,name:e.name,preconditions:u,requiresKeys:{...e.requiresKeys},slug:r,spec:l,warnings:c}}function am(e){return Ni({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function lm(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 cm(e,t,r,n){let o={};e.forEach((a,l)=>{let c=`step-${String(l)}`,d=l<e.length-1?`step-${String(l+1)}`:void 0;o[c]=dm(a,c,d)});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 dm(e,t,r){let{label:n,node:o}=ji(e);return{...o,id:t,label:n,next:r}}function um(e,t){let r=new Map(t.map(s=>[s.name,s])),n=[],o=new Set;function i(s){o.has(s)||(o.add(s),r.get(s)?.dependsOn.forEach(a=>{i(a)}),n.push(s))}return e.forEach(s=>{i(s)}),n}import{Webhook as Bx,WebhookVerificationError as zx}from"standardwebhooks";import{z as $}from"zod";var Jx=$.object({preconditions:$.array($.string().min(1))}),Kx=$.object({data:$.record($.string(),$.record($.string(),$.string())),preconditions:$.array($.string().min(1))}),Yx=$.object({observer:$.string().min(1).max(200),params:$.record($.string().max(200),$.string())}),pm=$.discriminatedUnion("kind",[$.object({kind:$.literal("pass")}),$.object({kind:$.literal("retry"),reason:$.string()}),$.object({kind:$.literal("fail"),reason:$.string()})]),Xx=$.object({error:$.string().optional(),outcome:pm.optional(),success:$.boolean()});function De(e){let t=[];return e.tests.forEach(r=>{let n=mm(r),o=i=>{t.push({...i,test:r.slug})};Lm.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function mm(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 gm(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&Li(o.value)){let i=o.value.value;!Di(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 ym(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 bm(e,t,r){let n=0;e.forEach(o=>{_e(o)?n=0:(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 Sm(e,t,r){if(e.length===0)return;let n=e.at(-1);n!=null&&!_e(n)&&r({message:"Last step is an action, not an assertion \u2014 expectedOutcome should be verified by assertions at the end",rule:"assert-matches-outcome",step:n.label??n.id})}function vm(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function Li(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function Di(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 _e(e){return e.type.startsWith("assert")}var Rm=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function xm(e){return Rm.has(e.type)}function Pm(e,t,r){!t.implemented||e.length===0||e.some(n=>_e(n))||r({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function Em(e,t,r){if(!t.implemented||e.length<=3)return;let n=e.filter(i=>_e(i)).length;if(n===0)return;let o=n/e.length;if(o<.15){let i=Math.round(o*100);r({message:`Only ${String(n)}/${String(e.length)} steps are assertions (${String(i)}%) \u2014 add more verification between actions`,rule:"low-assertion-ratio",step:void 0})}}function on(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 Cm(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=on(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&on(c)===i)==null||s.some(c=>xm(c)||_e(c)&&on(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 Tm=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 sn(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!Tm.has(t))}function Am(e){let t=e.label==null?[]:sn(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,...sn(n)]}function $m(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(sn(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>_e(s));if(o.length===0)return;o.some(s=>Am(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 Im=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function Oi(e){if(e.type==="upload"||e.type==="handleDialog"&&e.action==="accept")return!0;if(e.type!=="click")return!1;let t=e.locator,r=t.by==="role"?t.name??"":t.value;return Im.test(r)}function jm(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!Oi(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(d=>Oi(d)),a=s===-1?i.length:s;i.slice(0,a).some(d=>d.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 Nm(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])=>Li(a)&&Di(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 Om(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(u=>u[1]).filter(u=>u!=null&&!n.has(u)))];if(l.length===0)return;let c=l.map(u=>`{{${u}}}`).join(", "),d=[...new Set(l.map(u=>u.split(".")[0]??u))].join(", ");r({message:`"${i.label??i.id}" contains literal template string(s) ${c} \u2014 destructure the proxy in .steps(({ ${d} }) => \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 Lm=[fm,gm,Om,ym,hm,wm,bm,Sm,vm,Pm,Em,Cm,$m,jm,Nm];import af from"picomatch";import{execFileSync as Dm,spawnSync as _m}from"child_process";function oe(e,t){return Dm("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function _i(e,t){let r=_m("git",["show",e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(r.status===0)return r.stdout;if(r.status===128)return null;throw new Error(`git show ${e} failed (${String(r.status)}): ${r.stderr}`)}import R from"typescript";import*as Ui from"remeda";var Vi=[["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"]],Um=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),Vm=[[/(?:^|[a-z])Button$/,"click"],[/(?:^|[a-z])(?:Link|NavLink|Anchor)$/,"navigate"],[/(?:^|[a-z])(?:Textarea|TextArea|Input|Field|SearchBox)$/,"input"],[/(?:^|[a-z])(?:Select|Combobox|ComboBox|Dropdown)$/,"select"],[/(?:^|[a-z])Form$/,"submit"]];function Ut({filePath:e,source:t}){let r=R.createSourceFile(e,t,R.ScriptTarget.Latest,!0,R.ScriptKind.TSX);return r.statements.flatMap(n=>Fm({filePath:e,sf:r,stmt:n}))}function Fm({filePath:e,sf:t,stmt:r}){let n=Wm(r);if(n==null||Mm(n))return[];let o=Fi(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return Ui.uniqueBy(o,i=>i.id)}function Mm(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function Wm(e){if(R.isExportAssignment(e))return Hm(e.expression);if(!qm(e))return null;if(R.isFunctionDeclaration(e)||R.isClassDeclaration(e))return e.name?.text??null;if(R.isVariableStatement(e)){let t=e.declarationList.declarations[0];return t!=null&&R.isIdentifier(t.name)?t.name.text:null}return null}function Hm(e){return R.isIdentifier(e)?e.text:(R.isFunctionExpression(e)||R.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function qm(e){if(!R.canHaveModifiers(e))return!1;let t=R.getModifiers(e);return t!=null&&t.some(r=>r.kind===R.SyntaxKind.ExportKeyword)}function Fi(e,t){let r=Bm(e,t),n=e.getChildren(t).flatMap(o=>Fi(o,t));return r==null?n:[r,...n]}function Bm(e,t){let r=zm(e);if(r==null)return null;let n=Gm(r);if(n==null)return null;let o=Qm(r,n);return o==null?null:{kind:n,label:o,line:sf(t,e.getStart(t))}}function zm(e){return R.isJsxSelfClosingElement(e)&&R.isIdentifier(e.tagName)?{attrs:e.attributes,children:[],tag:e.tagName.text}:R.isJsxElement(e)&&R.isIdentifier(e.openingElement.tagName)?{attrs:e.openingElement.attributes,children:e.children,tag:e.openingElement.tagName.text}:null}function Gm({attrs:e,tag:t}){let r=ue(e,"role");return r!=null?Um.get(r)??null:Km(t,e)??Ym(t)??Xm(e)}var Jm=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 Km(e,t){return Jm.get(e)?.(t)??null}function Ym(e){return/^[A-Z]/.test(e)?Vm.find(([t])=>t.test(e))?.[1]??null:null}function Xm(e){return Vi.find(([t])=>tf(e,t))?.[1]??null}function Qm({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")??(Zm(r)?void 0:of(t))??ef(e,n)}function Zm(e){return e==="input"||e==="textarea"||e==="select"}function ef(e,t){let r=Vi.find(([,o])=>o===t)?.[0];if(r==null)return;let n=rf(e,r);if(n!=null){if(R.isIdentifier(n))return n.text;if(R.isArrowFunction(n)||R.isFunctionExpression(n))return Mi(n.body)}}function Mi(e){if(R.isCallExpression(e)){let t=e.expression;return R.isIdentifier(t)?t.text:R.isPropertyAccessExpression(t)?t.name.text:void 0}return R.forEachChild(e,Mi)}function tf(e,t){return e.properties.some(r=>R.isJsxAttribute(r)&&R.isIdentifier(r.name)&&r.name.text===t)}function Wi(e,t){return e.properties.find(r=>R.isJsxAttribute(r)&&R.isIdentifier(r.name)&&r.name.text===t)}function ue(e,t){let r=Wi(e,t);return r==null?void 0:nf(r.initializer)}function rf(e,t){let r=Wi(e,t);if(!(r?.initializer==null||!R.isJsxExpression(r.initializer)))return r.initializer.expression}function nf(e){if(e==null)return"";if(R.isStringLiteral(e))return e.text;if(R.isJsxExpression(e))return qi(e.expression)}function of(e){let t=e.flatMap(r=>Hi(r)).join(" ").trim();return t.length===0?void 0:t}function Hi(e){if(R.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(R.isJsxExpression(e)){let t=qi(e.expression);return t==null?[]:[t]}return R.isJsxElement(e)?e.children.flatMap(t=>Hi(t)):[]}function qi(e){if(e!=null){if(R.isStringLiteral(e)||R.isNoSubstitutionTemplateLiteral(e))return e.text;if(R.isCallExpression(e)&&e.arguments.length===1){let t=e.arguments[0];if(t!=null&&(R.isStringLiteral(t)||R.isNoSubstitutionTemplateLiteral(t)))return t.text}}}function sf(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var lf=an.join(".ripplo","coverage.d.ts");function Ue({cwd:e}){cf({cwd:e,ignorePaths:Re})}function cf({cwd:e,ignorePaths:t}){let r=Ve({cwd:e,ignorePaths:t});pf({content:uf(r),cwd:e})}function Ve({cwd:e,ignorePaths:t}){let n=df({cwd:e,ignorePaths:t}).flatMap(o=>ln({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function df({cwd:e,ignorePaths:t}){let r=oe(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=af([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o))}function ln({cwd:e,file:t}){let r=Vt.readFileSync(an.join(e,t),"utf8");return Ut({filePath:t,source:r}).map(n=>n.id)}function uf(e){let t=`// GENERATED \u2014 do not edit
|
|
205
|
+
`:`${i}, ${rp(n)}.
|
|
206
|
+
`),process.stdout.write(`Session saved to ${be("token")}.
|
|
207
|
+
`),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 Xr({serverUrl:e,token:t}){try{let n=(await S({config:De({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 Ri(){let e=re();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let t=fe(),r=await Xr({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})
|
|
208
|
+
`)}function xi(){if(!_r()){process.stdout.write(`No token to remove.
|
|
209
|
+
`);return}process.stdout.write(`Removed ${be("token")}
|
|
210
|
+
`)}import Zr from"fs/promises";import en from"path";import{z as Lt}from"zod";import{z as Pi}from"zod";import{z as Le}from"zod";import{z as m}from"zod";import{z as Re}from"zod";import{z as $i}from"zod";import{z as H}from"zod";import{z as ee}from"zod";import{z as Qr}from"zod";import{z}from"zod";var np=Lt.object({__codec:Lt.string().min(1),data:Lt.unknown(),version:Lt.number().int().positive()}),op=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}},ip=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function nn(e){return Ei({legacy:void 0,migrators:[],name:e,schemas:[]})}function sp(e,t){let r=JSON.parse(t);return e.decode(r)}function Ei(e){return{initial:t=>tn(t,{...e,schemas:[t]}),legacy:t=>Ei({...e,legacy:t})}}function tn(e,t){return{build:()=>ap(e,t),legacy:r=>tn(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return tn(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function ap(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>lp(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function lp(e,t,r){let{data:n,version:o}=cp(t,r),i=Ti(t,n,o);return e.parse(i)}function cp(e,t){let r=np.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new ip({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 Ti(e,t,r){let n=e.schemas.length;if(r>n)throw new op({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 Ti(e,s(i),r+1)}var Ai=Le.object({depends:Le.array(Le.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:Le.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Le.array(Le.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name."),dp=Re.object({by:Re.literal("testId"),value:Re.string().min(1)}),up=Re.object({by:Re.literal("role"),name:Re.string().optional(),role:Re.string().min(1)}),A=Re.discriminatedUnion("by",[dp,up]),st=$i.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),pp=$i.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),mp=H.object({type:H.literal("static"),value:H.union([H.string(),H.number(),H.boolean()])}),on=H.object({name:H.string().min(1),type:H.literal("variable")}),fp=H.discriminatedUnion("type",[mp,on]),ae=H.discriminatedUnion("type",[H.object({type:H.literal("static"),value:H.string()}),on]),gp=H.discriminatedUnion("type",[H.object({type:H.literal("static"),value:H.number().int().nonnegative()}),on]),yp=ee.discriminatedUnion("type",[ee.object({default:ee.string().optional(),type:ee.literal("string")}),ee.object({default:ee.number().optional(),type:ee.literal("number")}),ee.object({default:ee.boolean().optional(),type:ee.literal("boolean")}),ee.object({key:ee.string().min(1),type:ee.literal("env")})]),C={id:m.string().min(1).max(200),label:m.string().max(500).optional(),next:m.string().max(200).optional(),uiOnly:m.boolean().optional()},Ci=500,hp=m.object({...C,type:m.literal("goto"),url:ae}),wp=m.object({...C,locator:A,type:m.literal("click")}),bp=m.object({...C,locator:A,type:m.literal("fill"),value:ae}),Sp=m.object({...C,locator:A,type:m.literal("select"),value:ae}),vp=m.object({...C,locator:A,type:m.literal("hover")}),kp=m.object({...C,key:m.string().min(1),locator:A.optional(),type:m.literal("press")}),Rp=m.object({...C,locator:A,type:m.literal("check")}),xp=m.object({...C,locator:A,type:m.literal("uncheck")}),Pp=m.object({...C,height:m.number().int().positive(),type:m.literal("setViewport"),width:m.number().int().positive()}),Cp=m.object({...C,message:m.string().min(1),type:m.literal("fail")}),Ep=m.object({...C,type:m.literal("setVariable"),value:fp,variable:m.string().min(1)}),Tp=m.object({...C,locator:A,type:m.literal("extractText"),variable:m.string().min(1)}),Ap=m.object({...C,files:m.array(m.string()).min(1),locator:A,type:m.literal("upload")}),$p=m.object({...C,locator:A,type:m.literal("dblclick")}),Ip=m.object({...C,source:A,target:A,type:m.literal("drag")}),jp=m.object({...C,locator:A,type:m.literal("scrollIntoView")}),Np=m.object({...C,locator:A,type:m.literal("type"),value:ae}),Op=m.object({...C,locator:A,type:m.literal("focus")}),Dp=m.object({...C,locator:A,type:m.literal("clear")}),Lp=m.object({...C,locator:A,type:m.literal("rightClick")}),_p=m.object({...C,action:m.enum(["accept","dismiss"]),promptText:m.string().optional(),type:m.literal("handleDialog")}),Up=m.object({...C,action:m.enum(["read","write"]),type:m.literal("clipboard"),value:ae.optional(),variable:m.string().min(1).optional()}),Vp=m.object({...C,permission:m.string().min(1),state:m.enum(["granted","prompt"]),type:m.literal("setPermission")}),Fp=m.object({...C,locator:A,type:m.literal("assertVisible")}),Mp=m.object({...C,locator:A,type:m.literal("assertNotVisible")}),Hp=m.object({...C,expected:ae,locator:A,operator:st,type:m.literal("assertText")}),Wp=m.object({...C,expected:ae,operator:st,type:m.literal("assertUrl")}),qp=m.object({...C,expected:gp,locator:A,operator:pp,type:m.literal("assertCount")}),Bp=m.object({...C,expected:ae,locator:A,operator:st,type:m.literal("assertValue")}),zp=m.object({...C,attribute:m.string().min(1),expected:ae,locator:A,operator:st,type:m.literal("assertAttribute")}),Gp=m.object({...C,locator:A,type:m.literal("assertEnabled")}),Kp=m.object({...C,locator:A,type:m.literal("assertDisabled")}),Jp=m.object({...C,expected:ae,operator:st,type:m.literal("assertTitle")}),Yp=m.object({...C,locator:A,type:m.literal("assertChecked")}),Xp=m.object({...C,locator:A,type:m.literal("assertNotChecked")}),Qp=m.object({...C,locator:A,type:m.literal("assertFocused")}),Zp=m.object({...C,locator:A,type:m.literal("assertNotFocused")}),em=m.object({...C,budget:m.enum(["fast","slow","async"]),observer:m.string().min(1).max(200),params:m.record(m.string().max(200),ae),type:m.literal("assertObserver")}),tm=m.discriminatedUnion("type",[hp,wp,bp,Sp,vp,kp,Rp,xp,Fp,Mp,Hp,Wp,qp,Bp,zp,Gp,Kp,Pp,Cp,Ep,Tp,Ap,$p,Ip,jp,Np,Op,Dp,Lp,_p,Up,Vp,Jp,Yp,Xp,Qp,Zp,em]),Ii=m.object({entryNode:m.string().min(1).max(200),nodes:m.record(m.string().max(200),tm).refine(e=>Object.keys(e).length<=Ci,`Workflow has more than ${String(Ci)} nodes`),uiOnly:m.boolean().optional(),variableNamespaces:m.record(m.string().max(200),m.string().max(500)).optional(),variables:m.record(m.string().max(200),yp).optional()}),rm=Pi.record(Pi.string().max(200),Ai),nm={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},om={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},eP=nn("workflow-spec").legacy(nm).initial(Ii).build(),tP=nn("precondition-map").legacy(om).initial(rm).build(),im=["fast","slow","async"],sm=Qr.object({budget:Qr.enum(im).describe("Polling budget tier: fast | slow | async"),description:Qr.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."),ce=".ripplo/ripplo.lock",am=5e3,lm=z.record(z.string().max(200),z.string().max(200)),cm=z.object({coverage:z.array(z.string().max(500)).max(2e3).default([]),expectedOutcome:z.string().max(2e3),name:z.string().max(200),preconditions:z.array(z.string().max(200)).max(1e3),requiresKeys:lm,slug:z.string().max(200),spec:Ii}),dm=z.object({observers:z.record(z.string().max(200),sm),preconditions:z.record(z.string().max(200),Ai),tests:z.array(cm).max(am)}),ji=nn("ripplo-lockfile").initial(dm).build();function Ni(e){return{observers:e.observers,preconditions:e.preconditions,tests:e.tests.filter(t=>t.implemented).map(t=>({coverage:[...t.coverage],expectedOutcome:t.expectedOutcome,name:t.name,preconditions:[...t.preconditions],requiresKeys:{...t.requiresKeys},slug:t.slug,spec:t.spec}))}}function rn(e){let t=ji.encode(e);return`${JSON.stringify(t,mm(t),2)}
|
|
211
|
+
`}async function _t({cwd:e}){let t=en.join(e,ce),r=await um(t);return r==null?null:sp(ji,r)}async function de({cwd:e,result:t}){let r=Ni(t),n=en.join(e,ce);await Zr.mkdir(en.dirname(n),{recursive:!0}),await Zr.writeFile(n,rn(r),"utf8")}function Ut({compiled:e,existing:t}){if(t==null)return"missing";let r=rn(Ni(e)),n=rn(t);return r===n?"match":"stale"}async function um(e){try{return await Zr.readFile(e,"utf8")}catch(t){if(pm(t)&&t.code==="ENOENT")return null;throw t}}function pm(e){return e instanceof Error&&"code"in e}function mm(e){return function(r,n){return n===e||!fm(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function fm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import Mt from"fs";import cn 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/**"],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 Oi(e){return e.data}function Di(e){return{as(t){return{data:{label:t,node:e}}}}}function Vt(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();gm(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=>ym(a,t));return{observers:i,preconditions:o,tests:s}}function gm(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 ym(e,t){let r=e.id,{accessedKeys:n,vars:o}=wm(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[hm(i),...s],l=bm(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 u=vm(e.requires,t);return{additionalChecks:[],coverage:e.coverage,description:e.description,expectedOutcome:e.expectedOutcome,implemented:e.implemented,name:e.name,preconditions:u,requiresKeys:{...e.requiresKeys},slug:r,spec:l,warnings:c}}function hm(e){return Di({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function wm(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 bm(e,t,r,n){let o={};e.forEach((a,l)=>{let c=`step-${String(l)}`,d=l<e.length-1?`step-${String(l+1)}`:void 0;o[c]=Sm(a,c,d)});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 Sm(e,t,r){let{label:n,node:o}=Oi(e);return{...o,id:t,label:n,next:r}}function vm(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 pP,WebhookVerificationError as mP}from"standardwebhooks";import{z as I}from"zod";var gP=I.object({preconditions:I.array(I.string().min(1))}),yP=I.object({data:I.record(I.string(),I.record(I.string(),I.string())),preconditions:I.array(I.string().min(1))}),hP=I.object({observer:I.string().min(1).max(200),params:I.record(I.string().max(200),I.string())}),km=I.discriminatedUnion("kind",[I.object({kind:I.literal("pass")}),I.object({kind:I.literal("retry"),reason:I.string()}),I.object({kind:I.literal("fail"),reason:I.string()})]),wP=I.object({error:I.string().optional(),outcome:km.optional(),success:I.boolean()});function _e(e){let t=[];return e.tests.forEach(r=>{let n=Rm(r),o=i=>{t.push({...i,test:r.slug})};Bm.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function Rm(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 xm(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 Pm(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&_i(o.value)){let i=o.value.value;!Ui(i)&&jm(i)&&r({message:`fill() uses hardcoded value "${i}" \u2014 consider using precondition data via {{namespace.key}}`,rule:"no-hardcoded-data",step:o.label??o.id})}})}function Cm(e,t,r){if(Object.keys(t.spec.variables??{}).length===0)return;e.some(i=>JSON.stringify(i).includes("{{"))||r({message:"Test requires preconditions but steps() never references precondition data \u2014 destructure and use it",rule:"prefer-precondition-data",step:void 0})}function Em(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 Tm(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 Am(e,t,r){let n=0;e.forEach(o=>{Ue(o)?n=0:(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 $m(e,t,r){if(e.length===0)return;let n=e.at(-1);n!=null&&!Ue(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 Im(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function _i(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function Ui(e){return e.includes("{{")}function jm(e){return e.includes("@")||/\b[a-f0-9]{8,}\b/.test(e)||/^(test|ripplo|example|sample|demo)/i.test(e)}function Ue(e){return e.type.startsWith("assert")}var Nm=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function Om(e){return Nm.has(e.type)}function Dm(e,t,r){!t.implemented||e.length===0||e.some(n=>Ue(n))||r({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function Lm(e,t,r){if(!t.implemented||e.length<=3)return;let n=e.filter(i=>Ue(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 an(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 _m(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=an(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&an(c)===i)==null||s.some(c=>Om(c)||Ue(c)&&an(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 Um=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 ln(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!Um.has(t))}function Vm(e){let t=e.label==null?[]:ln(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,...ln(n)]}function Fm(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(ln(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>Ue(s));if(o.length===0)return;o.some(s=>Vm(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 Mm=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function Li(e){if(e.type==="upload"||e.type==="handleDialog"&&e.action==="accept")return!0;if(e.type!=="click")return!1;let t=e.locator,r=t.by==="role"?t.name??"":t.value;return Mm.test(r)}function Hm(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!Li(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(d=>Li(d)),a=s===-1?i.length:s;i.slice(0,a).some(d=>d.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 Wm(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])=>_i(a)&&Ui(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 qm(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(u=>u[1]).filter(u=>u!=null&&!n.has(u)))];if(l.length===0)return;let c=l.map(u=>`{{${u}}}`).join(", "),d=[...new Set(l.map(u=>u.split(".")[0]??u))].join(", ");r({message:`"${i.label??i.id}" contains literal template string(s) ${c} \u2014 destructure the proxy in .steps(({ ${d} }) => \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 Bm=[xm,Pm,qm,Cm,Em,Tm,Am,$m,Im,Dm,Lm,_m,Fm,Hm,Wm];import hf from"picomatch";import{execFileSync as zm,spawnSync as Gm}from"child_process";function oe(e,t){return zm("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function Vi(e,t){let r=Gm("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 R from"typescript";import*as Fi from"remeda";var Mi=[["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"]],Km=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),Jm=[[/(?:^|[a-z])Button$/,"click"],[/(?:^|[a-z])(?:Link|NavLink|Anchor)$/,"navigate"],[/(?:^|[a-z])(?:Textarea|TextArea|Input|Field|SearchBox)$/,"input"],[/(?:^|[a-z])(?:Select|Combobox|ComboBox|Dropdown)$/,"select"],[/(?:^|[a-z])Form$/,"submit"]];function Ft({filePath:e,source:t}){let r=R.createSourceFile(e,t,R.ScriptTarget.Latest,!0,R.ScriptKind.TSX);return r.statements.flatMap(n=>Ym({filePath:e,sf:r,stmt:n}))}function Ym({filePath:e,sf:t,stmt:r}){let n=Qm(r);if(n==null||Xm(n))return[];let o=Hi(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return Fi.uniqueBy(o,i=>i.id)}function Xm(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function Qm(e){if(R.isExportAssignment(e))return Zm(e.expression);if(!ef(e))return null;if(R.isFunctionDeclaration(e)||R.isClassDeclaration(e))return e.name?.text??null;if(R.isVariableStatement(e)){let t=e.declarationList.declarations[0];return t!=null&&R.isIdentifier(t.name)?t.name.text:null}return null}function Zm(e){return R.isIdentifier(e)?e.text:(R.isFunctionExpression(e)||R.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function ef(e){if(!R.canHaveModifiers(e))return!1;let t=R.getModifiers(e);return t!=null&&t.some(r=>r.kind===R.SyntaxKind.ExportKeyword)}function Hi(e,t){let r=tf(e,t),n=e.getChildren(t).flatMap(o=>Hi(o,t));return r==null?n:[r,...n]}function tf(e,t){let r=rf(e);if(r==null)return null;let n=nf(r);if(n==null)return null;let o=cf(r,n);return o==null?null:{kind:n,label:o,line:yf(t,e.getStart(t))}}function rf(e){return R.isJsxSelfClosingElement(e)&&R.isIdentifier(e.tagName)?{attrs:e.attributes,children:[],tag:e.tagName.text}:R.isJsxElement(e)&&R.isIdentifier(e.openingElement.tagName)?{attrs:e.openingElement.attributes,children:e.children,tag:e.openingElement.tagName.text}:null}function nf({attrs:e,tag:t}){let r=ue(e,"role");return r!=null?Km.get(r)??null:sf(t,e)??af(t)??lf(e)}var of=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 sf(e,t){return of.get(e)?.(t)??null}function af(e){return/^[A-Z]/.test(e)?Jm.find(([t])=>t.test(e))?.[1]??null:null}function lf(e){return Mi.find(([t])=>pf(e,t))?.[1]??null}function cf({attrs:e,children:t,tag:r},n){return n==="navigate"?ue(e,"href")??ue(e,"to"):ue(e,"aria-label")??ue(e,"label")??ue(e,"title")??ue(e,"name")??ue(e,"placeholder")??(df(r)?void 0:gf(t))??uf(e,n)}function df(e){return e==="input"||e==="textarea"||e==="select"}function uf(e,t){let r=Mi.find(([,o])=>o===t)?.[0];if(r==null)return;let n=mf(e,r);if(n!=null){if(R.isIdentifier(n))return n.text;if(R.isArrowFunction(n)||R.isFunctionExpression(n))return Wi(n.body)}}function Wi(e){if(R.isCallExpression(e)){let t=e.expression;return R.isIdentifier(t)?t.text:R.isPropertyAccessExpression(t)?t.name.text:void 0}return R.forEachChild(e,Wi)}function pf(e,t){return e.properties.some(r=>R.isJsxAttribute(r)&&R.isIdentifier(r.name)&&r.name.text===t)}function qi(e,t){return e.properties.find(r=>R.isJsxAttribute(r)&&R.isIdentifier(r.name)&&r.name.text===t)}function ue(e,t){let r=qi(e,t);return r==null?void 0:ff(r.initializer)}function mf(e,t){let r=qi(e,t);if(!(r?.initializer==null||!R.isJsxExpression(r.initializer)))return r.initializer.expression}function ff(e){if(e==null)return"";if(R.isStringLiteral(e))return e.text;if(R.isJsxExpression(e))return zi(e.expression)}function gf(e){let t=e.flatMap(r=>Bi(r)).join(" ").trim();return t.length===0?void 0:t}function Bi(e){if(R.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(R.isJsxExpression(e)){let t=zi(e.expression);return t==null?[]:[t]}return R.isJsxElement(e)?e.children.flatMap(t=>Bi(t)):[]}function zi(e){if(e!=null){if(R.isStringLiteral(e)||R.isNoSubstitutionTemplateLiteral(e))return e.text;if(R.isCallExpression(e)&&e.arguments.length===1){let t=e.arguments[0];if(t!=null&&(R.isStringLiteral(t)||R.isNoSubstitutionTemplateLiteral(t)))return t.text}}}function yf(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var wf=cn.join(".ripplo","coverage.d.ts");function Ve({cwd:e}){bf({cwd:e,ignorePaths:xe})}function bf({cwd:e,ignorePaths:t}){let r=Fe({cwd:e,ignorePaths:t});kf({content:vf(r),cwd:e})}function Fe({cwd:e,ignorePaths:t}){let n=Sf({cwd:e,ignorePaths:t}).flatMap(o=>dn({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function Sf({cwd:e,ignorePaths:t}){let r=oe(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=hf([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o))}function dn({cwd:e,file:t}){let r=Mt.readFileSync(cn.join(e,t),"utf8");return Ft({filePath:t,source:r}).map(n=>n.id)}function vf(e){let t=`// GENERATED \u2014 do not edit
|
|
212
212
|
import "@ripplo/testing";
|
|
213
213
|
|
|
214
214
|
declare module "@ripplo/testing" {
|
|
@@ -219,32 +219,41 @@ declare module "@ripplo/testing" {
|
|
|
219
219
|
`:`${t}${r}
|
|
220
220
|
}
|
|
221
221
|
}
|
|
222
|
-
`}function
|
|
223
|
-
`),process.stderr.write(`${
|
|
224
|
-
`),process.exit(1)),e.check){let n=await
|
|
222
|
+
`}function kf({content:e,cwd:t}){let r=cn.join(t,wf);Mt.existsSync(r)&&Mt.readFileSync(r,"utf8")===e||Mt.writeFileSync(r,e)}import Rf from"path";import{createJiti as xf}from"jiti";var Pf=["getObservers","getPreconditions","getTests","getUnimplemented"];function Cf(e){return e==null||typeof e!="object"?!1:Pf.every(t=>typeof Reflect.get(e,t)=="function")}function Ef(e){return e===null?"null":Array.isArray(e)?"array":typeof e}async function j(e){let t=Rf.join(e,".ripplo","index.ts");try{let n=await xf(import.meta.url,{moduleCache:!1}).import(t),o=n!=null&&typeof n=="object"&&"default"in n?Reflect.get(n,"default"):n;if(!Cf(o))return{error:`${t} must default-export a RipploBuilder (got ${Ef(o)})`,ok:!1};let i=Vt(o);return{builder:o,ok:!0,result:i}}catch(r){return{error:r instanceof Error?r.message:String(r),ok:!1}}}function x(e,t){return t==null?`Load \`/ripplo:${e}\` skill for instructions.`:`Load \`/ripplo:${e}\` skill for instructions on ${t}.`}function Gi(e){return e.length===1?x(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 Ki(e){let t=process.cwd(),r=await j(t);if(r.ok||(process.stderr.write(`Compilation failed: ${r.error}
|
|
223
|
+
`),process.stderr.write(`${x("create","DSL authoring + lint rules")}
|
|
224
|
+
`),process.exit(1)),e.check){let n=await _t({cwd:t}),o=Ut({compiled:r.result,existing:n});if(o==="match"){process.stdout.write(`${ce} is up to date
|
|
225
225
|
`);return}let i=o==="missing"?"missing":"out of date";process.stderr.write(`${ce} is ${i} \u2014 run \`ripplo compile\` and commit the result
|
|
226
|
-
`),process.stderr.write(`${
|
|
227
|
-
`),process.exit(1)}await de({cwd:t,result:r.result}),
|
|
228
|
-
`)}import
|
|
229
|
-
`),
|
|
230
|
-
`),o.length>0&&(
|
|
226
|
+
`),process.stderr.write(`${x("setup")}
|
|
227
|
+
`),process.exit(1)}await de({cwd:t,result:r.result}),Ve({cwd:t}),process.stdout.write(`wrote ${ce}
|
|
228
|
+
`)}import ge from"process";import Tf from"fs";import Af from"path";import $f from"picomatch";function Ji({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Fe({cwd:t,ignorePaths:r})),o=Qi(e),i=If({cwd:t,ignorePaths:r});return Xi({acknowledged:o,allStatements:n,unacked:i})}function Yi({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Fe({cwd:t,ignorePaths:r})),o=Qi(e);return Xi({acknowledged:o,allStatements:n,unacked:n})}function Xi({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 Qi(e){return new Set(e.tests.flatMap(t=>t.coverage))}function If({cwd:e,ignorePaths:t}){let r=jf({cwd:e,ignorePaths:t}),n=new Set(r.flatMap(i=>Nf({cwd:e,file:i}))),o=new Set(r.flatMap(i=>Of({cwd:e,file:i})?dn({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function jf({cwd:e,ignorePaths:t}){let r=oe(["diff","--name-only","HEAD","-z"],e),n=oe(["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 Nf({cwd:e,file:t}){let r=Vi(`HEAD:${t}`,e);return r==null?[]:Ft({filePath:t,source:r}).map(n=>n.id)}function Of({cwd:e,file:t}){return Tf.existsSync(Af.join(e,t))}async function Zi(){let e=ge.cwd(),t=await j(e);t.ok||(ge.stderr.write(`Compilation failed: ${t.error}
|
|
229
|
+
`),ge.exit(1));let r=Fe({cwd:e,ignorePaths:xe}),n=Yi({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;ge.stdout.write(`Coverage: ${String(s)}/${String(r.length)} statements acknowledged
|
|
230
|
+
`),o.length>0&&(ge.stdout.write(`
|
|
231
231
|
Unacknowledged (${String(o.length)}):
|
|
232
|
-
`),o.forEach(a=>
|
|
233
|
-
`))),i.length>0&&(
|
|
232
|
+
`),o.forEach(a=>ge.stdout.write(` ${a.id}
|
|
233
|
+
`))),i.length>0&&(ge.stdout.write(`
|
|
234
234
|
Stale claims (${String(i.length)}):
|
|
235
|
-
`),i.forEach(a=>
|
|
236
|
-
`))),n.length>0&&
|
|
235
|
+
`),i.forEach(a=>ge.stdout.write(` ${a.id}
|
|
236
|
+
`))),n.length>0&&ge.exit(1)}import mn from"fs";import Ff from"path";import{chromium as Mf}from"playwright";import{graphql as Lf}from"gql.tada";import es from"fs";import un from"path";function ts(e){let t=es.realpathSync(e),r=t,n=un.dirname(r);for(;n!==r;){if(es.existsSync(un.join(r,".git")))return r;r=n,n=un.dirname(r)}return t}function W(e){let t=tr(e),r=$e(),n=re();if(n==null)throw new Error("ripplo: not authenticated. Run `ripplo auth login`.");return{appUrl:r.appUrl,cwd:ts(e),engineUrl:r.engineUrl,projectId:t.projectId,ripploServerUrl:fe(),token:n,webhookSecret:r.webhookSecret}}import at from"fs";var Df="dev.pid";function rs(e){return nt(e,Df)}function Me(e){let t=rs(e);if(!at.existsSync(t))return!1;let r=at.readFileSync(t,"utf8").trim(),n=Number.parseInt(r,10);if(!Number.isFinite(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch{return!1}}function ns(e){rt(e);let t=rs(e);at.writeFileSync(t,String(process.pid));let r=!1;return()=>{if(!r){r=!0;try{let n=at.readFileSync(t,"utf8").trim();Number.parseInt(n,10)===process.pid&&at.unlinkSync(t)}catch{}}}}var _f=Lf(`
|
|
237
|
+
query DevSessionCheckHealth($projectId: String!, $cwd: String!) {
|
|
238
|
+
project(id: $projectId) {
|
|
239
|
+
id
|
|
240
|
+
devSession(cwd: $cwd) {
|
|
241
|
+
id
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
`);function os(e){switch(e.status){case"active":return"\u2713 Dev session: ripplo watch is live for this directory";case"starting":return"! Dev session: `ripplo watch` is running locally but hasn't registered with the server yet. Wait a few seconds and re-run `npx ripplo doctor`. If it persists, check the watch process output for auth/network errors.";case"missing":return"\u2717 Dev session: no active ripplo watch. Start `npx ripplo watch` as a background process (separate from your app's dev server). Without it, `ripplo run` will refuse to dispatch and scope/coverage hooks won't arm."}}async function is(e){let t=Me(e),r;try{r=W(e)}catch{return{status:t?"starting":"missing",type:"dev-session"}}return(await S({config:r,document:_f,variables:{cwd:r.cwd,projectId:r.projectId}}).catch(()=>null))?.project?.devSession!=null?{status:"active",type:"dev-session"}:{status:t?"starting":"missing",type:"dev-session"}}import Uf from"fs";import Vf from"path";async function ss(e){let t=Vf.join(e,".ripplo","index.ts");if(!Uf.existsSync(t))return{appUrl:void 0,engineUrl:void 0,errors:[{message:".ripplo/index.ts not found",path:""}],valid:!1,warnings:[]};let r=await j(e);if(!r.ok)return{appUrl:void 0,engineUrl:void 0,errors:[{message:r.error,path:".ripplo/"}],valid:!1,warnings:[]};try{let n=$e();return{appUrl:n.appUrl,engineUrl:n.engineUrl,errors:[],valid:!0,warnings:[]}}catch(n){return{appUrl:void 0,engineUrl:void 0,errors:[{message:n instanceof Error?n.message:String(n),path:""}],valid:!1,warnings:[]}}}async function pn(e){try{await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return}catch{return`appUrl (${e}) is not responding. Make sure your dev server is running on that port.`}}async function as({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}}function ls(e){switch(e.type){case"settings":return!e.valid;case"env-files":return e.missing.length>0;case"token":return!e.exists;case"dev-server":return!e.reachable;case"dev-session":return e.status!=="active";case"preconditions":return e.count>0&&!e.configured;case"engine-endpoint":return!e.reachable;case"adapter-enabled":return e.status!=="enabled";case"webhook-verification":return!e.rejectsUnsigned;case"preconditions-validation":return!e.valid;case"workflows":return e.invalidNames.length>0;case"browser":return!e.installed;case"lockfile":return e.status!=="match";case"pre-commit-hook":return!e.installed}}async function cs(e){let t=await qf(e),r={missing:or(e),type:"env-files"},n=Bf(),o=zf(),i=await j(e),s=Gf(i),a=Yf(i),l=await Hf(e,i),c=Wf(e),d=await Xf(t,i);return[t,r,n,...d,s,a,l,c,o]}async function Hf(e,t){if(!t.ok)return{status:"missing",type:"lockfile"};let r=await _t({cwd:e});return{status:Ut({compiled:t.result,existing:r}),type:"lockfile"}}function Wf(e){let t=Ff.join(e,".git","hooks","pre-commit");return mn.existsSync(t)?{installed:mn.readFileSync(t,"utf8").includes("ripplo compile --check"),type:"pre-commit-hook"}:{installed:!1,type:"pre-commit-hook"}}async function qf(e){let t=await ss(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}}function Bf(){let e=re();return{exists:e!=null&&e.length>0,type:"token"}}function zf(){let e=Mf.executablePath();return{installed:mn.existsSync(e),type:"browser"}}function Gf(e){if(!e.ok)return{errorCount:1,errors:[{message:e.error,path:""}],found:!1,type:"preconditions-validation",valid:!1};let t=Kf(e.result.preconditions,e.result.tests);return{errorCount:t.length,errors:t,found:!0,type:"preconditions-validation",valid:t.length===0}}function Kf(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}`})})}),Jf(e).forEach(o=>{r.push({message:o,path:"preconditions"})}),r}function Jf(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 Yf(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 Xf(e,t){if(!e.valid||!t.ok)return[];let r;try{let a=$e();r={appUrl:a.appUrl,engineUrl:a.engineUrl,webhookSecret:a.webhookSecret}}catch{return[]}let n=[],o=await pn(r.appUrl)==null;n.push({appUrl:r.appUrl,reachable:o,type:"dev-server"});let i=await is(process.cwd());n.push(i);let s=await Qf(r,t);return n.push(...s),n}async function Qf(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=tg(e.appUrl,e.engineUrl);if(i==null)return[o];let s=await pn(i)==null,a=[];if(a.push({configured:!0,count:r,endpointReachable:s,type:"preconditions"}),ds(e.engineUrl)&&a.push({reachable:s,type:"engine-endpoint",url:i}),!s)return a;let l=await as({appUrl:e.appUrl,engineUrl:e.engineUrl});a.push({rejectsUnsigned:l==null,type:"webhook-verification"});let c=await Zf({engineUrl:i,webhookSecret:e.webhookSecret});return a.push({status:c,type:"adapter-enabled",url:i}),a}async function Zf({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 eg(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 ds(e){return e.startsWith("http://")||e.startsWith("https://")}function tg(e,t){return ds(t)?t:`${e}${t}`}function us(e){switch(e.type){case"settings":return og(e);case"env-files":return ig(e);case"token":return sg(e);case"dev-server":return ag(e);case"dev-session":return os(e);case"preconditions":return dg(e);case"webhook-verification":return lg(e);case"preconditions-validation":return ug(e);case"workflows":return pg(e);case"browser":return cg(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 eg(e);case"lockfile":return rg(e);case"pre-commit-hook":return ng(e)}}function rg(e){switch(e.status){case"match":return`\u2713 Lockfile: ${ce} is up to date`;case"missing":return`\u2717 Lockfile: ${ce} is missing \u2014 run \`ripplo compile\` and commit it`;case"stale":return`\u2717 Lockfile: ${ce} is out of date \u2014 run \`ripplo compile\` and commit it`}}function ng(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 og(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function ig(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
|
|
237
246
|
${e.missing.map(r=>` ${r}`).join(`
|
|
238
247
|
`)}
|
|
239
|
-
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
|
|
248
|
+
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 sg(e){return e.exists?"\u2713 Auth: Token found":"\u2717 Auth: No token found. Run `ripplo` to authenticate."}function ag(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 lg(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 cg(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function dg(e){return e.count===0?"! Preconditions: None defined":e.configured?e.endpointReachable===void 0?`! Preconditions: ${String(e.count)} defined (could not verify endpoint)`:`\u2713 Preconditions: ${String(e.count)} defined, endpoint configured`:`\u2717 Preconditions: ${String(e.count)} defined but RIPPLO_ENGINE_URL is not set in your env file`}function ug(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"}
|
|
240
249
|
${t.join(`
|
|
241
|
-
`)}`}function
|
|
250
|
+
`)}`}function pg(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=>mg(r));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
|
|
242
251
|
${t.join(`
|
|
243
|
-
`)}`}function
|
|
252
|
+
`)}`}function mg(e){let t=e.errors.map(r=>" - "+(r.path===""?"":r.path+": ")+r.message);return" "+e.name+`:
|
|
244
253
|
`+t.join(`
|
|
245
|
-
`)}async function
|
|
254
|
+
`)}async function ps(){let e=process.cwd(),t=await cs(e),r=t.map(o=>us(o));process.stdout.write(r.join(`
|
|
246
255
|
`)+`
|
|
247
|
-
`);let n=t.some(o=>
|
|
256
|
+
`);let n=t.some(o=>ls(o));process.exit(n?1:0)}import{graphql as Wt,readFragment as vg}from"gql.tada";import gg from"crypto";import{graphql as yg}from"gql.tada";import fn from"fs";import gn from"path";function Ht(e){try{let t=gn.join(fg(e),"HEAD"),r=fn.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 fg(e){let t=gn.join(e,".git");if(fn.statSync(t).isDirectory())return t;let n=fn.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 gn.resolve(e,i)}var hg=yg(`
|
|
248
257
|
mutation SyncDevSession(
|
|
249
258
|
$projectId: String!
|
|
250
259
|
$cwd: String!
|
|
@@ -262,12 +271,12 @@ ${t.join(`
|
|
|
262
271
|
id
|
|
263
272
|
}
|
|
264
273
|
}
|
|
265
|
-
`);async function
|
|
274
|
+
`);async function lt(e){let t=wg(e.compiled);return Sg({config:e.config,cwd:e.cwd,payload:t})}async function Te(e,t){let r=await j(e);if(!r.ok)throw new Error(`DSL compilation failed: ${r.error}`);let n=await lt({compiled:r.result,config:t,cwd:e});return{compiled:r.result,devSessionId:n.devSessionId}}function wg(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,spec:t.implemented?JSON.stringify(t.spec):null}))}}function bg(e){return gg.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function Sg({config:e,cwd:t,payload:r}){let n=bg(r),o=Ht(t),i=await S({config:e,document:hg,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,spec:s.spec??null}))}});if(i.syncDevSession==null)throw new Error("syncDevSession returned null");return{devSessionId:i.syncDevSession.id,hash:n}}import ms from"figures";var ct={cross:ms.cross,tick:ms.tick};var gs=Wt(`
|
|
266
275
|
fragment WorkflowIdMCP on Workflow {
|
|
267
276
|
id
|
|
268
277
|
slug
|
|
269
278
|
}
|
|
270
|
-
`),
|
|
279
|
+
`),kg=Wt(`
|
|
271
280
|
query ProjectWorkflowIdsMCP($projectId: String!, $cwd: String!) {
|
|
272
281
|
project(id: $projectId) {
|
|
273
282
|
id
|
|
@@ -279,14 +288,14 @@ ${t.join(`
|
|
|
279
288
|
}
|
|
280
289
|
}
|
|
281
290
|
}
|
|
282
|
-
`,[
|
|
291
|
+
`,[gs]),Rg=Wt(`
|
|
283
292
|
mutation CreateRunMCP($workflowId: String!, $platforms: [String!]!, $concurrency: Int!) {
|
|
284
293
|
createRun(workflowId: $workflowId, platforms: $platforms, concurrency: $concurrency) {
|
|
285
294
|
id
|
|
286
295
|
status
|
|
287
296
|
}
|
|
288
297
|
}
|
|
289
|
-
`),
|
|
298
|
+
`),xg=Wt(`
|
|
290
299
|
query RunStatusMCP($id: String!) {
|
|
291
300
|
run(id: $id) {
|
|
292
301
|
id
|
|
@@ -313,21 +322,21 @@ ${t.join(`
|
|
|
313
322
|
}
|
|
314
323
|
}
|
|
315
324
|
}
|
|
316
|
-
`);async function
|
|
317
|
-
${
|
|
325
|
+
`);async function qt({config:e,ids:t}){let r=await Pg({config:e,ids:t}),n=await Promise.all(r.map(async s=>{try{let a=await $g({config:e,workflowId:s.workflowId});return{entry:s,ok:!0,runId:a}}catch(a){let l=a instanceof Error?a.message:String(a);return{entry:s,message:l,ok:!1}}})),o=await Promise.all(n.map(async s=>{if(!s.ok)return{id:s.entry.id,runId:"",summary:`ERROR creating run: ${s.message}
|
|
326
|
+
${x("setup","check auth + config")}`};let{entry:a,runId:l}=s;try{let c=await jg({config:e,runId:l}),d=Ag({config:e,id:a.id,runId:l}),u=`.ripplo/debug/${l}/`;return{id:a.id,runId:l,summary:`View run: ${d}
|
|
318
327
|
Debug artifacts: ${u}
|
|
319
|
-
${
|
|
328
|
+
${x("debug","read summary.txt, accessibility-tree, network.jsonl before guessing")}
|
|
320
329
|
|
|
321
330
|
${c}`}}catch(c){let d=c instanceof Error?c.message:String(c);return{id:a.id,runId:l,summary:`ERROR polling run ${l}: ${d}
|
|
322
|
-
${
|
|
331
|
+
${x("debug")}`}}})),i=o.map(s=>`**${s.id}:**
|
|
323
332
|
${s.summary}`).join(`
|
|
324
333
|
|
|
325
334
|
---
|
|
326
335
|
|
|
327
|
-
`);return{results:o,summary:i}}async function
|
|
336
|
+
`);return{results:o,summary:i}}async function Pg({config:e,ids:t}){let r=await Te(e.cwd,e),n=await S({config:e,document:kg,variables:{cwd:e.cwd,projectId:e.projectId}});if(n.project==null)throw new Error("Project not found");if(n.project.devSession==null)throw new Error("No active dev session. Start one by running `ripplo` (or `npx ripplo`) in your terminal, then try again.");let o=(n.project.workflows??[]).map(s=>vg(gs,s));if(t.length===0)return o.map(s=>({id:s.slug,workflowId:s.id}));let i=r.compiled.tests.map(s=>s.slug);return t.map(s=>{let a=o.find(l=>l.slug===s);if(a==null)throw new Error(Cg({compiledSlugs:i,slug:s}));return{id:s,workflowId:a.id}})}function Cg({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=Eg({compiledSlugs:e,limit:3,slug:t}),n=r.length>0?`
|
|
328
337
|
Did you mean: ${r.join(", ")}?`:"";return`Test "${t}" is not registered in this dev session.${n}
|
|
329
|
-
Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function
|
|
330
|
-
`)}function
|
|
338
|
+
Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function Eg({compiledSlugs:e,limit:t,slug:r}){let n=new Set(r.split("-"));return e.map(i=>({candidate:i,score:Tg(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,t).map(i=>i.candidate)}function Tg(e,t){return t.split("-").filter(r=>e.has(r)).length}function Ag({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 $g({config:e,workflowId:t}){let r=await S({config:e,document:Rg,variables:{concurrency:1,platforms:["chromium"],workflowId:t}});if(r.createRun==null)throw new Error("Failed to create run");return r.createRun.id}var Ig=2e3,fs=150;async function jg({config:e,runId:t}){let r=0;for(;r<fs;){await Og(Ig),r+=1;let o=(await S({config:e,document:xg,variables:{id:t}})).run;if(o==null)throw new Error(`Run ${t} not found`);if(!(o.status==="pending"||o.status==="running"))return Ng({results:o.results??[],runId:t,status:o.status})}return`Run ${t} timed out after polling ${String(fs)} times.`}function Ng({results:e,runId:t,status:r}){let n=[`Run ${t}: ${r.toUpperCase()}`];return e.forEach(o=>{n.push(` ${o.status}: ${String(o.passCount)} passed, ${String(o.failCount)} failed (${String(o.duration??0)}ms)`),o.summary!=null&&n.push(` Summary: ${o.summary}`),o.traceEntries.forEach(i=>{let s=i.status==="passed"?ct.tick:ct.cross,a=i.detail==null?"":` \u2014 ${i.detail}`;n.push(` ${s} ${i.title} (${String(i.duration)}ms)${a}`),i.assertions.forEach(l=>{let c=l.status==="passed"?ct.tick:ct.cross,d=l.detail==null?"":` \u2014 ${l.detail}`;n.push(` ${c} ${l.description}${d}`)})})}),n.join(`
|
|
339
|
+
`)}function Og(e){return new Promise(t=>{setTimeout(t,e)})}import{graphql as Dg}from"gql.tada";var Lg=Dg(`
|
|
331
340
|
query DevSessionCheckPreflight($projectId: String!, $cwd: String!) {
|
|
332
341
|
project(id: $projectId) {
|
|
333
342
|
id
|
|
@@ -336,30 +345,36 @@ Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on
|
|
|
336
345
|
}
|
|
337
346
|
}
|
|
338
347
|
}
|
|
339
|
-
`);function
|
|
340
|
-
`),process.stderr.write(`${
|
|
341
|
-
`),process.exit(1)}}async function
|
|
342
|
-
`),process.exit(1))}async function
|
|
343
|
-
`);let n=await Promise.allSettled(Array.from({length:t},()=>
|
|
348
|
+
`);function ye(){try{return W(process.cwd())}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
|
|
349
|
+
`),process.stderr.write(`${x("setup")}
|
|
350
|
+
`),process.exit(1)}}async function he(e){(await S({config:e,document:Lg,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(`${x("setup")}
|
|
351
|
+
`),process.exit(1))}async function ys({id:e,runs:t}){let r=ye();await he(r),process.stdout.write(`flake-detect "${e}" x${String(t)}...
|
|
352
|
+
`);let n=await Promise.allSettled(Array.from({length:t},()=>qt({config:r,ids:[e]}))),o=0,i=0,s=new Map;n.forEach(l=>{if(l.status==="rejected"){i++;let d=l.reason instanceof Error?l.reason.message:"unknown error";s.set(d,(s.get(d)??0)+1);return}let c=l.value.results[0];if(c==null){i++;return}if(c.summary.includes("FAILED")||c.summary.includes("ERROR")){i++;let d=c.summary.split(`
|
|
344
353
|
`).find(u=>u.includes("FAILED")||u.includes("ERROR"))??"unknown failure";s.set(d,(s.get(d)??0)+1)}else o++});let a=t>0?i/t*100:0;process.stdout.write(`${String(o)} passed / ${String(i)} failed (${a.toFixed(1)}% flake)
|
|
345
354
|
`),s.size>0&&s.forEach((l,c)=>{process.stdout.write(` ${String(l)}x: ${c}
|
|
346
|
-
`)}),i>0&&process.stderr.write(`${
|
|
347
|
-
`),process.exit(i>0?1:0)}import
|
|
348
|
-
|
|
355
|
+
`)}),i>0&&process.stderr.write(`${x("flake-detect","parallel safety + race conditions")}
|
|
356
|
+
`),process.exit(i>0?1:0)}import Bt from"fs";import{graphql as Ug}from"gql.tada";import _g from"fs";function pe(e){return nt(e,"hooks-paused")}function V(e){return _g.existsSync(pe(e))?!1:Me(e)}var Vg=Ug(`
|
|
357
|
+
mutation CliSetHooksPaused($projectId: String!, $paused: Boolean!) {
|
|
358
|
+
setHooksPaused(projectId: $projectId, paused: $paused)
|
|
359
|
+
}
|
|
360
|
+
`);async function hs(){process.stdin.isTTY||(process.stderr.write("`ripplo hooks pause` must be invoked interactively from a terminal \u2014 refusing non-TTY invocation. Bypassing the gate is a human decision, not an agent decision.\n"),process.exit(1));let e=process.cwd();rt(e);let t=pe(e);if(Bt.existsSync(t)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}Bt.writeFileSync(t,""),await bs(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function ws(){let e=process.cwd(),t=pe(e);if(!Bt.existsSync(t)){process.stdout.write(`Hooks already active.
|
|
361
|
+
`);return}Bt.unlinkSync(t),await bs(e,!1),process.stdout.write(`Hooks resumed.
|
|
362
|
+
`)}async function bs(e,t){let r;try{r=W(e)}catch{return}await S({config:r,document:Vg,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import He from"fs";import We from"path";import{input as ks,select as Rs}from"@inquirer/prompts";import{graphql as iy}from"gql.tada";import{exec as Fg}from"child_process";import F from"fs";import q from"path";import{promisify as Mg}from"util";var Hg=["@ripplo/testing"],Ss=".ripplo/ripplo.lock linguist-generated=true",Wg=[".ripplo/debug/",".ripplo/.local/"],qg=Mg(Fg);async function vs({cwd:e,onStep:t}){t("Scaffolding project files..."),Qg({cwd:e}),t("Updating .gitignore..."),Zg(e),t("Marking ripplo.lock as generated..."),Gg(e),t("Installing dependencies...");let r=await Bg(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 zg(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await Rr(),n}async function Bg(e){let t=Kg({cwd:e,pm:Xg(e)});g.info("Installing dependencies: %s",t);try{return await qg(t,{cwd:e}),{ok:!0}}catch(r){let n=r instanceof Error?r.message.split(`
|
|
363
|
+
`)[0]??r.message:String(r);return g.warn("Install failed (%s): %s",t,n),{cmd:t,ok:!1,reason:n}}}async function zg(e){try{let t=await j(e);if(!t.ok)return;await de({cwd:e,result:t.result});return}catch(t){return`Couldn't compile initial lockfile: ${t instanceof Error?t.message:String(t)}.`}}function Gg(e){let t=q.join(e,".gitattributes"),r=F.existsSync(t)?F.readFileSync(t,"utf8"):"";if(r.includes(Ss))return;let n=r.length===0||r.endsWith(`
|
|
349
364
|
`)?"":`
|
|
350
|
-
`;F.writeFileSync(t,`${r}${n}${
|
|
351
|
-
`)}function
|
|
365
|
+
`;F.writeFileSync(t,`${r}${n}${Ss}
|
|
366
|
+
`)}function Kg({cwd:e,pm:t}){let r=Hg.join(" ");return t==="pnpm"?Jg(e)?`pnpm add -wD ${r}`:`pnpm add -D ${r}`:t==="yarn"?Yg(e)?`yarn add -WD ${r}`:`yarn add -D ${r}`:t==="bun"?`bun add -d ${r}`:`npm install -D ${r}`}function Jg(e){return F.existsSync(q.join(e,"pnpm-workspace.yaml"))||F.existsSync(q.join(e,"pnpm-workspace.yml"))}function Yg(e){let t=q.join(e,"package.json");if(!F.existsSync(t))return!1;try{let r=JSON.parse(F.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 Xg(e){return F.existsSync(q.join(e,"pnpm-lock.yaml"))?"pnpm":F.existsSync(q.join(e,"yarn.lock"))?"yarn":F.existsSync(q.join(e,"bun.lockb"))||F.existsSync(q.join(e,"bun.lock"))?"bun":"npm"}function Qg({cwd:e}){let t=q.join(e,".ripplo"),r=q.join(t,"tests"),n=q.join(t,"preconditions"),o=q.join(t,"observers");F.mkdirSync(r,{recursive:!0}),F.mkdirSync(n,{recursive:!0}),F.mkdirSync(o,{recursive:!0}),dt(q.join(t,"index.ts"),ey),dt(q.join(n,"index.ts"),ty),dt(q.join(o,"index.ts"),ry),dt(q.join(r,"index.ts"),ny),dt(q.join(t,"tsconfig.json"),oy)}function dt(e,t){F.existsSync(e)||F.writeFileSync(e,t)}function Zg(e){let t=q.join(e,".gitignore");if(!F.existsSync(t))return;let r=F.readFileSync(t,"utf8"),n=Wg.filter(i=>!r.includes(i));if(n.length===0)return;let o=r.endsWith(`
|
|
352
367
|
`)?"":`
|
|
353
368
|
`;F.writeFileSync(t,r+o+n.join(`
|
|
354
369
|
`)+`
|
|
355
|
-
`)}var
|
|
370
|
+
`)}var ey=`import { createRipplo } from "@ripplo/testing";
|
|
356
371
|
import { preconditions } from "./preconditions/index.js";
|
|
357
372
|
import { observers } from "./observers/index.js";
|
|
358
373
|
import { tests } from "./tests/index.js";
|
|
359
374
|
|
|
360
375
|
export { preconditions, observers, tests };
|
|
361
376
|
export default createRipplo({ preconditions, observers, tests });
|
|
362
|
-
`,
|
|
377
|
+
`,ty=`// Declare preconditions with \`precondition(name)\` from @ripplo/testing and collect them
|
|
363
378
|
// in the \`preconditions\` registry below. Every handle in this registry must be implemented
|
|
364
379
|
// in your app server's \`createEngine(ripplo, { preconditions: {...}, observers: {...} })\` call.
|
|
365
380
|
//
|
|
@@ -373,7 +388,7 @@ export default createRipplo({ preconditions, observers, tests });
|
|
|
373
388
|
// export const preconditions = { authLoggedIn };
|
|
374
389
|
|
|
375
390
|
export const preconditions = {};
|
|
376
|
-
`,
|
|
391
|
+
`,ry=`// Declare observers with \`observer(name)\` from @ripplo/testing and collect them in
|
|
377
392
|
// the \`observers\` registry below. Use them in tests via \`assert.backend(handle, params)\`.
|
|
378
393
|
//
|
|
379
394
|
// Example:
|
|
@@ -386,7 +401,7 @@ export const preconditions = {};
|
|
|
386
401
|
// export const observers = { orgNameIs };
|
|
387
402
|
|
|
388
403
|
export const observers = {};
|
|
389
|
-
`,
|
|
404
|
+
`,ny=`// Each test file under ./tests exports a TestDefinition. Import them here and add them
|
|
390
405
|
// to the \`tests\` array \u2014 that's what \`createRipplo({ ..., tests })\` receives.
|
|
391
406
|
//
|
|
392
407
|
// Example:
|
|
@@ -394,7 +409,7 @@ export const observers = {};
|
|
|
394
409
|
// export const tests = [myTest] as const;
|
|
395
410
|
|
|
396
411
|
export const tests = [] as const;
|
|
397
|
-
`,
|
|
412
|
+
`,oy=`{
|
|
398
413
|
"compilerOptions": {
|
|
399
414
|
"strict": true,
|
|
400
415
|
"noUncheckedIndexedAccess": true,
|
|
@@ -410,60 +425,60 @@ export const tests = [] as const;
|
|
|
410
425
|
"include": ["*.ts", "coverage.d.ts", "observers/**/*.ts", "preconditions/**/*.ts", "tests/**/*.ts"],
|
|
411
426
|
"exclude": ["node_modules"]
|
|
412
427
|
}
|
|
413
|
-
`;var
|
|
428
|
+
`;var sy=iy(`
|
|
414
429
|
query InitProjects {
|
|
415
430
|
projects {
|
|
416
431
|
id
|
|
417
432
|
name
|
|
418
433
|
}
|
|
419
434
|
}
|
|
420
|
-
`),
|
|
421
|
-
`),process.exit(1));let o=await
|
|
435
|
+
`),yn=["../.env.local","../.env"];async function xs(e=cy()){let t=process.cwd(),r=re();r==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let n=fe();ay(t)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${t}. Delete it first if you want to re-init.
|
|
436
|
+
`),process.exit(1));let o=await ly({serverUrl:n,token:r});o.length===0&&(process.stdout.write("No projects found. Create one in the dashboard first, then re-run `ripplo init`.\n"),process.exit(1));let i=await uy(o,e.projectId),s=await py(t,e.envFile),a=await my(e.appUrl),l=dy(a,e.engineUrl),c=We.resolve(We.join(t,".ripplo"),s);xn({cwd:t,envFiles:[s],projectId:i}),yy({appUrl:a,engineUrl:l,filePath:c});let d=await vs({cwd:t,onStep:u=>{process.stdout.write(` ${u}
|
|
422
437
|
`)}});if(d.length>0){process.stdout.write(`Done with warnings:
|
|
423
438
|
`),d.forEach(u=>{process.stdout.write(` - ${u.message}
|
|
424
439
|
`),u.manualCommand!=null&&process.stdout.write(` run: ${u.manualCommand}
|
|
425
|
-
`)});return}process.stdout.write("Ready.
|
|
426
|
-
`),process.exit(1)}return t}return`${e.replace(/\/$/,"")}/ripplo`}async function
|
|
440
|
+
`)});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 ay(e){return He.existsSync(We.join(e,".ripplo","index.ts"))}async function ly({serverUrl:e,token:t}){return((await S({config:De({serverUrl:e,token:t}),document:sy,variables:void 0})).projects??[]).map(n=>({id:n.id,name:n.name}))}function cy(){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}
|
|
441
|
+
`),process.exit(1)}return t}return`${e.replace(/\/$/,"")}/ripplo`}async function uy(e,t){if(t!=null){let r=e.find(n=>n.id===t);return r==null&&(process.stdout.write(`Unknown project id: ${t}
|
|
427
442
|
`),process.exit(1)),process.stdout.write(`Using project: ${r.name} (${r.id})
|
|
428
443
|
`),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})
|
|
429
|
-
`),r.id}return
|
|
430
|
-
`),process.exit(1)),t):
|
|
431
|
-
`),process.exit(1)}return e}return
|
|
444
|
+
`),r.id}return Rs({choices:e.map(r=>({name:r.name,value:r.id})),message:"Select a project"})}async function py(e,t){return t!=null?(t.trim().length===0&&(process.stdout.write(`--env-file must not be empty
|
|
445
|
+
`),process.exit(1)),t):fy(e)}async function my(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
|
|
446
|
+
`),process.exit(1)}return e}return gy()}async function fy(e){let t=We.join(e,".ripplo"),r=yn.find(o=>He.existsSync(We.resolve(t,o))),n=await Rs({choices:[...yn.map(o=>({name:r===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:r??yn[0],message:"Which env file should ripplo write RIPPLO_APP_URL, RIPPLO_ENGINE_URL, and RIPPLO_WEBHOOK_SECRET to?"});return n!=="__custom__"?n:ks({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function gy(){return ks({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 yy({appUrl:e,engineUrl:t,filePath:r}){He.mkdirSync(We.dirname(r),{recursive:!0});let n=He.existsSync(r)?He.readFileSync(r,"utf8"):"",o=[];if(/^RIPPLO_APP_URL=/m.test(n)||o.push(`RIPPLO_APP_URL=${e}`),/^RIPPLO_ENGINE_URL=/m.test(n)||o.push(`RIPPLO_ENGINE_URL=${t}`),/^RIPPLO_WEBHOOK_SECRET=/m.test(n)||o.push(`RIPPLO_WEBHOOK_SECRET=${Wr()}`),o.length===0)return;let i=n.length===0||n.endsWith(`
|
|
432
447
|
`)?"":`
|
|
433
|
-
`;
|
|
448
|
+
`;He.writeFileSync(r,`${n}${i}${o.join(`
|
|
434
449
|
`)}
|
|
435
|
-
`)}import
|
|
436
|
-
`),process.stderr.write(`${
|
|
437
|
-
`),process.exit(1)),await de({cwd:n,result:o.result});let i=
|
|
450
|
+
`)}import hn from"fs";import Ps from"path";import*as Cs from"remeda";async function Es(e){let{ids:t,requireImplemented:r}=e,n=process.cwd(),o=await j(n);o.ok||(process.stderr.write(`Compilation failed: ${o.error}
|
|
451
|
+
`),process.stderr.write(`${x("create","DSL authoring + lint rules")}
|
|
452
|
+
`),process.exit(1)),await de({cwd:n,result:o.result});let i=_e(o.result),s=t.length===0?i.diagnostics:i.diagnostics.filter(w=>t.includes(w.test)),a=Cs.groupBy(s,w=>w.test);Object.entries(a).forEach(([w,h])=>{process.stderr.write(`
|
|
438
453
|
${w}
|
|
439
|
-
`),h.forEach(
|
|
440
|
-
`),process.stderr.write(` ${
|
|
454
|
+
`),h.forEach(v=>{let E=v.step==null?"":` at "${v.step}"`;process.stderr.write(` [${v.rule}]${E}
|
|
455
|
+
`),process.stderr.write(` ${v.message}
|
|
441
456
|
`)})});let l=new Set(o.builder.getUnimplemented().tests),c=r.filter(w=>l.has(w));c.length>0&&(process.stderr.write(`
|
|
442
457
|
not-implemented
|
|
443
458
|
`),c.forEach(w=>{process.stderr.write(` ${w} is still marked .notImplemented()
|
|
444
|
-
`)}));let d=
|
|
459
|
+
`)}));let d=Sy(n);d.length>0&&(process.stderr.write(`
|
|
445
460
|
preconditions
|
|
446
461
|
`),d.forEach(w=>{process.stderr.write(` [hardcoded-identifier] ${w.file}
|
|
447
462
|
`),process.stderr.write(` ${w.message}
|
|
448
463
|
`)}));let u=s.length+c.length+d.length;u>0&&(process.stderr.write(`
|
|
449
464
|
${String(u)} error(s)
|
|
450
|
-
`),
|
|
451
|
-
`)}function
|
|
452
|
-
`))}var
|
|
465
|
+
`),hy({diagnostics:s,hardcodeWarnings:d,stillStubbed:c}),process.exit(1));let f=o.result.tests.length,b=t.length===0?"all tests":`${String(t.length)} test(s)`;process.stdout.write(`\u2713 ripplo lint: ${b} passed (${String(f)} compiled, lockfile written)
|
|
466
|
+
`)}function hy({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(`${x(o)}
|
|
467
|
+
`))}var wy=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,by=/['"`][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"`]/i;function Sy(e){let t=Ps.join(e,".ripplo","preconditions");return hn.existsSync(t)?hn.readdirSync(t).filter(n=>n.endsWith(".ts")).flatMap(n=>vy(Ps.join(t,n))):[]}function vy(e){let t=hn.readFileSync(e,"utf8"),r=t.includes("ctx.uniqueEmail")||t.includes("ctx.uniqueId"),n=[],o=wy.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=by.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 ky}from"gql.tada";var Ry=ky(`
|
|
453
468
|
query ProjectsList {
|
|
454
469
|
projects {
|
|
455
470
|
id
|
|
456
471
|
name
|
|
457
472
|
}
|
|
458
473
|
}
|
|
459
|
-
`);async function
|
|
460
|
-
`)}async function
|
|
474
|
+
`);async function Ts(){let e=re();e==null&&(process.stderr.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let t=fe(),n=((await S({config:De({serverUrl:t,token:e}),document:Ry,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:n},null,2)}
|
|
475
|
+
`)}async function As(e){let t=ye();await he(t);let{results:r,summary:n}=await qt({config:t,ids:e});process.stdout.write(`${n}
|
|
461
476
|
`);let o=r.some(i=>i.summary.includes("FAILED")||i.summary.includes("ERROR"));o&&(process.stderr.write(`Artifacts in .ripplo/debug/<runId>/ \u2014 read before re-running.
|
|
462
|
-
`),process.stderr.write(`${
|
|
463
|
-
`)),process.exit(o?1:0)}async function
|
|
477
|
+
`),process.stderr.write(`${x("debug")}
|
|
478
|
+
`)),process.exit(o?1:0)}async function $s(){let e=process.cwd(),t=W(e);try{let r=await Te(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}
|
|
464
479
|
`)}catch(r){let n=r instanceof Error?r.message:String(r);process.stderr.write(`ripplo sync failed: ${n}
|
|
465
|
-
`),process.stderr.write(`${
|
|
466
|
-
`),process.exit(1)}}import
|
|
480
|
+
`),process.stderr.write(`${x("setup","verify auth + server reachability")}
|
|
481
|
+
`),process.exit(1)}}import bn from"fs";import{createClient as $y}from"graphql-sse";import{graphql as zt}from"gql.tada";import{print as js}from"graphql";import{availableParallelism as xy}from"os";import Py from"p-limit";var Cy=Math.min(10,xy()/2),Ey=Py(Cy),wn=new Set;async function Is(e){if(!wn.has(e.runId)){wn.add(e.runId);try{await Ey(()=>Ty(e))}finally{wn.delete(e.runId)}}}async function Ty({agentProfileDescription:e,agentProfileId:t,config:r,cwd:n,runId:o,workflowId:i,workflowSlug:s}){let a=await Ce({headed:!1});try{await Ir({maxRuns:100});let l=n!=null&&s!=null?await Ay({cwd:n,workflowSlug:s}):void 0;await Yr({agentProfileDescription:e,agentProfileId:t,baseUrl:r.appUrl,browser:a,config:r,headed:!1,preconditionNames:l,runId:o,webhookSecret:r.webhookSecret,workflowId:i})}catch(l){g.error(l,"Runner error")}finally{await a.close()}}async function Ay({cwd:e,workflowSlug:t}){let r=await j(e);if(!r.ok)return;let n=r.result.tests.find(o=>o.slug===t);if(n!=null)return n.preconditions}var Iy=15e3,jy=zt(`
|
|
467
482
|
subscription RunRequestedWatch($devSessionId: String!) {
|
|
468
483
|
runRequested(devSessionId: $devSessionId) {
|
|
469
484
|
agentProfileDescription
|
|
@@ -473,30 +488,30 @@ ${String(u)} error(s)
|
|
|
473
488
|
workflowSlug
|
|
474
489
|
}
|
|
475
490
|
}
|
|
476
|
-
`),
|
|
491
|
+
`),Ny=zt(`
|
|
477
492
|
subscription HooksPausedWatch($projectId: String!) {
|
|
478
493
|
hooksPausedRequested(projectId: $projectId) {
|
|
479
494
|
paused
|
|
480
495
|
projectId
|
|
481
496
|
}
|
|
482
497
|
}
|
|
483
|
-
`),
|
|
498
|
+
`),Oy=zt(`
|
|
484
499
|
mutation HeartbeatDevSessionWatch($id: String!) {
|
|
485
500
|
heartbeatDevSession(id: $id) {
|
|
486
501
|
id
|
|
487
502
|
}
|
|
488
503
|
}
|
|
489
|
-
`),
|
|
504
|
+
`),Dy=zt(`
|
|
490
505
|
mutation EndDevSessionWatch($projectId: String!, $cwd: String!) {
|
|
491
506
|
endDevSession(projectId: $projectId, cwd: $cwd) {
|
|
492
507
|
id
|
|
493
508
|
}
|
|
494
509
|
}
|
|
495
|
-
`);async function
|
|
496
|
-
`),process.exit(1));let n=await
|
|
497
|
-
`);let d=async()=>{c(),a(),l(),await Promise.race([
|
|
498
|
-
`),
|
|
499
|
-
`),process.exit(1)}}var
|
|
510
|
+
`);async function Ns(){let e=Vy(process.cwd()),t=e.cwd,r=await j(t);r.ok||(process.stderr.write(`ripplo: DSL compilation failed: ${r.error}
|
|
511
|
+
`),process.exit(1));let n=await Hy(()=>lt({compiled:r.result,config:e,cwd:t})),o=Ht(t);o!=null&&g.info("watching branch %s in %s",o,t);let i=ns(t),s=$y({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`}),a=Ly({config:e,cwd:t,devSessionId:n.devSessionId,sseClient:s}),l=_y({cwd:t,projectId:e.projectId,sseClient:s}),c=Uy({config:e,devSessionId:n.devSessionId});process.stdout.write(`ripplo watch: ready as local executor for session ${n.devSessionId} (sync happens on each \`ripplo run\`; Ctrl-C to stop)
|
|
512
|
+
`);let d=async()=>{c(),a(),l(),await Promise.race([S({config:e,document:Dy,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise(f=>setTimeout(f,3e3))]),i()},u=()=>{d().finally(()=>process.exit(0))};process.on("SIGINT",u),process.on("SIGTERM",u),process.on("SIGHUP",u),process.on("SIGBREAK",u),await new Promise(()=>{})}function Ly({config:e,cwd:t,devSessionId:r,sseClient:n}){return n.subscribe({query:js(jy),variables:{devSessionId:r}},{complete:()=>{},error:o=>{g.error(o,"runRequested subscription error")},next:o=>{let i=o.data?.runRequested;i!=null&&(process.stdout.write(`ripplo: run ${i.runId} (${i.workflowSlug})
|
|
513
|
+
`),Is({agentProfileDescription:i.agentProfileDescription??void 0,agentProfileId:i.agentProfileId??void 0,config:e,cwd:t,runId:i.runId,workflowId:i.workflowId,workflowSlug:i.workflowSlug}))}})}function _y({cwd:e,projectId:t,sseClient:r}){return r.subscribe({query:js(Ny),variables:{projectId:t}},{complete:()=>{},error:n=>{g.error(n,"hooksPaused subscription error")},next:n=>{let o=n.data?.hooksPausedRequested?.paused;if(o===!0){bn.writeFileSync(pe(e),"");return}o===!1&&bn.existsSync(pe(e))&&bn.unlinkSync(pe(e))}})}function Uy({config:e,devSessionId:t}){let r=setInterval(()=>{S({config:e,document:Oy,variables:{id:t}}).catch(n=>{g.warn("heartbeat failed: %s",n instanceof Error?n.message:String(n))})},Iy);return()=>{clearInterval(r)}}function Vy(e){try{return W(e)}catch(t){let r=t instanceof Error?t.message:String(t);process.stderr.write(`${r}
|
|
514
|
+
`),process.exit(1)}}var Fy=1e3,My=6e4;async function Hy(e){let t=Date.now()+My,r;for(;Date.now()<t;){let n=await Wy(e);if(n.ok)return n.value;if(!qy(n.message))throw n.error;r=n.error,await By(Fy)}throw r instanceof Error?r:new Error("server never became ready")}async function Wy(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 qy(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function By(e){return new Promise(t=>setTimeout(t,e))}import{graphql as ut}from"gql.tada";var zy=ut(`
|
|
500
515
|
query ScopeStatus($projectId: String!, $cwd: String!) {
|
|
501
516
|
project(id: $projectId) {
|
|
502
517
|
id
|
|
@@ -516,7 +531,7 @@ ${String(u)} error(s)
|
|
|
516
531
|
}
|
|
517
532
|
}
|
|
518
533
|
}
|
|
519
|
-
`),
|
|
534
|
+
`),Gy=ut(`
|
|
520
535
|
query ScopeWorkflowBySlug($projectId: String!, $cwd: String!, $slug: String!) {
|
|
521
536
|
project(id: $projectId) {
|
|
522
537
|
id
|
|
@@ -529,7 +544,7 @@ ${String(u)} error(s)
|
|
|
529
544
|
}
|
|
530
545
|
}
|
|
531
546
|
}
|
|
532
|
-
`),
|
|
547
|
+
`),Ky=ut(`
|
|
533
548
|
mutation ScopeAddAgent($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
|
|
534
549
|
addAgentScopeItems(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
|
|
535
550
|
id
|
|
@@ -539,42 +554,42 @@ ${String(u)} error(s)
|
|
|
539
554
|
}
|
|
540
555
|
}
|
|
541
556
|
}
|
|
542
|
-
`),
|
|
557
|
+
`),Jy=ut(`
|
|
543
558
|
mutation ScopeLink($id: ID!, $workflowId: String!) {
|
|
544
559
|
linkScopeItem(id: $id, workflowId: $workflowId) {
|
|
545
560
|
id
|
|
546
561
|
}
|
|
547
562
|
}
|
|
548
|
-
`),
|
|
563
|
+
`),Yy=ut(`
|
|
549
564
|
mutation ScopeRemoveMany($ids: [ID!]!) {
|
|
550
565
|
removeScopeItems(ids: $ids)
|
|
551
566
|
}
|
|
552
|
-
`);async function
|
|
567
|
+
`);async function Os(e){let t=ye();await he(t);let n=(await S({config:t,document:zy,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
553
568
|
`);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??""}
|
|
554
569
|
`);return}let s=i.spec==null?"stub":"implemented";process.stdout.write(` [${s}] (${o.id}) ${i.slug} \u2014 ${i.name}
|
|
555
|
-
`)})}async function
|
|
570
|
+
`)})}async function Ds({testIds:e}){let t=ye();await he(t),await Te(t.cwd,t);let n=(await S({config:t,document:Ky,variables:{cwd:t.cwd,projectId:t.projectId,workflowSlugs:[...e]}})).addAgentScopeItems??[];if(n.length===0){process.stdout.write(`No scope items added.
|
|
556
571
|
`);return}let o=n.map(i=>i.workflow?.slug??"?").join(", ");process.stdout.write(`Added ${String(n.length)} scope item(s): ${o}
|
|
557
|
-
`)}async function
|
|
558
|
-
`)}async function
|
|
559
|
-
`)}async function
|
|
560
|
-
`),process.stderr.write(`${
|
|
561
|
-
`),process.exit(1)),n.id}async function
|
|
572
|
+
`)}async function Ls({id:e,testId:t}){let r=ye();await he(r),await Te(r.cwd,r);let n=await Xy({cfg:r,slug:t});await S({config:r,document:Jy,variables:{id:e,workflowId:n}}),process.stdout.write(`Linked scope item ${e} to ${t}
|
|
573
|
+
`)}async function _s({ids:e}){let t=ye();await he(t);let n=(await S({config:t,document:Yy,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${String(n)} scope item(s)
|
|
574
|
+
`)}async function Xy({cfg:e,slug:t}){let n=(await S({config:e,document:Gy,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.
|
|
575
|
+
`),process.stderr.write(`${x("create")}
|
|
576
|
+
`),process.exit(1)),n.id}async function Us(e){let t=process.cwd(),r=await j(t);r.ok||(process.stderr.write(`Compilation failed: ${r.error}
|
|
562
577
|
`),process.exit(1));let{tests:n}=r.builder.getUnimplemented();if(e.format==="summary"){n.length>0&&process.stdout.write(`tests: ${n.join(", ")}
|
|
563
578
|
`);return}let o={tests:n.map(i=>({id:i,implemented:!1}))};process.stdout.write(`${JSON.stringify(o,null,2)}
|
|
564
|
-
`)}import{z as
|
|
565
|
-
`).filter(t=>t.length>0)}function
|
|
566
|
-
`).filter(r=>r.length>0)}import{createHash as
|
|
567
|
-
`).filter(n=>n.length>0).filter(n=>
|
|
568
|
-
`),hookEventName:"UserPromptSubmit"}}});import
|
|
579
|
+
`)}import{z as Qy}from"zod";function N(e,t){let r=Qy.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 Vs from"picomatch";function Zy(e){return oe(["diff","--name-only","HEAD"],e).split(`
|
|
580
|
+
`).filter(t=>t.length>0)}function Fs({cwd:e,ignoreGlobs:t,watchGlobs:r}){let n=Vs([...r]),o=Vs([...t]);return Zy(e).filter(i=>n(i)&&!o(i))}function Gt(e,...t){return oe(["diff","--name-only","HEAD","--",...t],e).split(`
|
|
581
|
+
`).filter(r=>r.length>0)}import{createHash as eh}from"crypto";import{mkdirSync as th,readFileSync as Ms,writeFileSync as rh}from"fs";import Sn from"path";var nh=[".ts",".tsx",".js",".jsx"];function qe(e){let t=eh("sha256");return t.update(oe(["rev-parse","HEAD"],e)),t.update("\0"),t.update(oe(["diff","HEAD"],e)),t.update("\0"),oe(["ls-files","--others","--exclude-standard"],e).split(`
|
|
582
|
+
`).filter(n=>n.length>0).filter(n=>nh.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(oh(Sn.join(e,n))),t.update("\0")}),t.digest("hex")}function Be(e,t){try{return Ms(Hs(e,t),"utf8").trim()}catch{return null}}function ze(e,t,r){let n=Hs(e,t);th(Sn.dirname(n),{recursive:!0}),rh(n,r)}function Hs(e,t){return Sn.join(e,".ripplo",".local",`${t}.hash`)}function oh(e){try{return Ms(e)}catch{return Buffer.alloc(0)}}function Pe(){return{ignorePaths:xe,watchPaths:sn}}var Ws=N("UserPromptSubmit",e=>{let{cwd:t}=e;if(!$(t)||!V(t))return;let r=qe(t);if(Be(t,"coverage-nudge")===r)return;let{ignorePaths:n,watchPaths:o}=Pe(),i=Fs({cwd:t,ignoreGlobs:n,watchGlobs:o});if(ze(t,"coverage-nudge",r),!(i.length===0||Gt(t,".ripplo/tests",".ripplo/preconditions",".ripplo/observers").length>0))return{hookSpecificOutput:{additionalContext:`SCOPE DRIFT: ${String(i.length)} app file(s) changed without .ripplo/tests updates. ${x("scope")}`,hookEventName:"UserPromptSubmit"}}});import Kt from"fs";import ih from"os";import qs from"path";var Bs=N("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!V(e.cwd))return;let t=sh();if(t==null)return;let r=Kt.readFileSync(t,"utf8");if(!/\.ripplo\/tests|Tests to implement|No e2e coverage needed/.test(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Plan must cite ripplo test stubs. Add a "Tests to implement" section listing .ripplo/tests/<id>.ts per affected flow, OR add "No e2e coverage needed: <reason>" if this plan touches no user-facing behavior. ${x("explore")}`}}});function sh(){let e=qs.join(ih.homedir(),".claude","plans");return Kt.existsSync(e)?Kt.readdirSync(e).filter(r=>r.endsWith(".md")).map(r=>qs.join(e,r)).map(r=>({full:r,mtime:Kt.statSync(r).mtimeMs})).sort((r,n)=>n.mtime-r.mtime)[0]?.full??null:null}var zs=N("UserPromptSubmit",async e=>{if(e.permission_mode!=="plan"||!$(e.cwd)||!V(e.cwd))return;let t=await j(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(`
|
|
583
|
+
`),hookEventName:"UserPromptSubmit"}}});import ah from"path";import Gs from"picomatch";import{z as Ks}from"zod";var lh=Ks.looseObject({file_path:Ks.string()}),Js=N("PostToolUse",async e=>{let t=lh.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path,{cwd:n}=e;if(!$(n)||!V(n))return;let o=ah.relative(n,r);if(o.startsWith(".."))return;let{ignorePaths:i,watchPaths:s}=Pe(),a=Gs([...s]),l=Gs([...i]);if(!a(o)||l(o))return;let c=await j(n);if(!c.ok)return;let{tests:d}=c.builder.getUnimplemented();if(d.length!==0)return{hookSpecificOutput:{additionalContext:`Reminder: .notImplemented() stubs still present \u2014 tests: ${d.join(", ")}`,hookEventName:"PostToolUse"}}});import ch from"path";import{graphql as dh}from"gql.tada";import{z as Ys}from"zod";var uh=Ys.looseObject({file_path:Ys.string()}),ph=dh(`
|
|
569
584
|
mutation AutoScopeAdd($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
|
|
570
585
|
addAgentScopeItems(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
|
|
571
586
|
id
|
|
572
587
|
}
|
|
573
588
|
}
|
|
574
|
-
`),
|
|
575
|
-
${
|
|
589
|
+
`),Xs=N("PostToolUse",async e=>{let t=uh.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)||!V(n))return;let o=await j(n);if(!o.ok)return{decision:"block",reason:`Compilation failed: ${o.error}
|
|
590
|
+
${x("create","DSL authoring + lint rules")}`};await de({cwd:n,result:o.result}),Ve({cwd:n});let{diagnostics:i}=_e(o.result);return i.length===0?mh({compileResult:o,cwd:n,file:r}):{decision:"block",reason:`${i.map(a=>{let l=a.step==null?"":` at "${a.step}"`;return` [${a.rule}]${l} ${a.test}: ${a.message}`}).join(`
|
|
576
591
|
`)}
|
|
577
|
-
${
|
|
592
|
+
${x("create")}`}});async function mh({compileResult:e,cwd:t,file:r}){let n=fh(r);if(n==null)return;let o;try{o=W(t)}catch{return}if(await lt({compiled:e.result,config:o,cwd:t}).catch(l=>(g.warn("auto-sync failed: %s",l instanceof Error?l.message:String(l)),null))==null)return;let s=await S({config:o,document:ph,variables:{cwd:o.cwd,projectId:o.projectId,workflowSlugs:[n]}}).catch(l=>(g.warn("auto-scope failed: %s",l instanceof Error?l.message:String(l)),null));if(!(s==null||(s.addAgentScopeItems??[]).length===0))return{hookSpecificOutput:{additionalContext:`Auto-scoped ${n} (edited test).`,hookEventName:"PostToolUse"}}}function fh(e){if(!/\/\.ripplo\/tests\/[^/]+\.ts$/.test(e))return null;let t=ch.basename(e,".ts");return t==="index"?null:t}import{z as Qs}from"zod";var gh=Qs.looseObject({command:Qs.string()}),yh=/\bripplo\s+hooks\s+pause\b/,Zs=N("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=gh.safeParse(e.tool_input);if(!t.success||!yh.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{z as ra}from"zod";import{existsSync as hh,mkdirSync as wh,rmSync as o$,writeFileSync as bh}from"fs";import vn from"path";function ea(e,t,r){let n=ta(e,t,r);wh(vn.dirname(n),{recursive:!0}),bh(n,"")}function Jt(e,t,r){return hh(ta(e,t,r))}function Sh(e,t){return vn.join(e,".ripplo",".local","skills-loaded",t)}function ta(e,t,r){return vn.join(Sh(e,t),r)}var vh=ra.looseObject({command:ra.string()}),kh=/\bripplo run\b/,Rh="debug",na=N("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=vh.safeParse(e.tool_input);if(!t.success||!kh.test(t.data.command))return;let{cwd:r}=e;if(!(!$(r)||!V(r))&&!Jt(r,e.session_id,Rh))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"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."}}});import xh from"path";import{z as oa}from"zod";var Ph=new Set(["Edit","Write","NotebookEdit"]),Ch=oa.looseObject({file_path:oa.string()}),Eh="create",ia=N("PreToolUse",e=>{if(!Ph.has(e.tool_name))return;let t=Ch.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!$(r)||!V(r))return;let n=xh.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!Jt(r,e.session_id,Eh))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 Th from"path";import sa from"picomatch";import{graphql as Ah}from"gql.tada";import{z as aa}from"zod";var $h=new Set(["Edit","Write","NotebookEdit"]),Ih=aa.looseObject({file_path:aa.string()}),jh=Ah(`
|
|
578
593
|
query PreEditScopeGate($projectId: String!, $cwd: String!) {
|
|
579
594
|
project(id: $projectId) {
|
|
580
595
|
id
|
|
@@ -586,7 +601,7 @@ ${E("create")}`}});async function Zy({compileResult:e,cwd:t,file:r}){let n=eh(r)
|
|
|
586
601
|
}
|
|
587
602
|
}
|
|
588
603
|
}
|
|
589
|
-
`),
|
|
604
|
+
`),la=N("PreToolUse",async e=>{if(!$h.has(e.tool_name))return;let t=Ih.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!$(r)||!V(r))return;let n=Th.relative(r,t.data.file_path);if(!(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!Nh(n)||await Oh(r)))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Scope empty; edit touches app code (${n}). Stub a test or \`scope add\` an existing one before proceeding \u2014 or acknowledge "no user-facing behavior" if pure refactor. Hook re-fires until scope is populated (or hooks paused via the web UI). ${Gi(["scope","create"])}`}}});function Nh(e){let{ignorePaths:t,watchPaths:r}=Pe(),n=sa([...r]),o=sa([...t]);return n(e)&&!o(e)}async function Oh(e){let t;try{t=W(e)}catch{return!0}let r=await S({config:t,document:jh,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null);return r==null?!0:(r.project?.devSession?.scopeItems??[]).length>0}import Dh from"fs";import Lh from"path";import{z as ca}from"zod";var _h=new Set(["Edit","Write","NotebookEdit"]),Uh=ca.looseObject({file_path:ca.string()}),da=N("PreToolUse",e=>{if(!_h.has(e.tool_name))return;let t=Uh.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!$(r))return;let n=Lh.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!Dh.existsSync(pe(r))&&!Me(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`\`ripplo watch\` is not running, so this edit to \`${n}\` won't sync to the server and dev-mode guardrails won't fire. Run \`/ripplo:start\` (or spawn \`npx ripplo watch\` directly via Bash with run_in_background), then retry. The app's dev server also needs to be running \u2014 \`npx ripplo doctor\` reports both. If watch can't start (auth, server down, intentional offline work), the user can run \`npx ripplo hooks pause\` to bypass this gate; \`npx ripplo hooks resume\` re-enables it. ${x("start")}`}}});import{graphql as Vh}from"gql.tada";var Fh=Vh(`
|
|
590
605
|
query ScopeReminder($projectId: String!, $cwd: String!) {
|
|
591
606
|
project(id: $projectId) {
|
|
592
607
|
id
|
|
@@ -603,9 +618,9 @@ ${E("create")}`}});async function Zy({compileResult:e,cwd:t,file:r}){let n=eh(r)
|
|
|
603
618
|
}
|
|
604
619
|
}
|
|
605
620
|
}
|
|
606
|
-
`),
|
|
621
|
+
`),ua=N("UserPromptSubmit",async e=>{let{cwd:t}=e;if(!$(t)||!V(t))return;let r=qe(t);if(Be(t,"scope-reminder")===r)return;let n;try{n=W(t)}catch{return}let o=await S({config:n,document:Fh,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. ${x("scope")}`:`RIPPLO SCOPE (${String(i.length)}):
|
|
607
622
|
${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(`
|
|
608
|
-
`)}`,hookEventName:"UserPromptSubmit"}}});var
|
|
623
|
+
`)}`,hookEventName:"UserPromptSubmit"}}});var Mh="# 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=N("SessionStart",e=>{if($(e.cwd))return{hookSpecificOutput:{additionalContext:Mh,hookEventName:"SessionStart"}}});import{execFileSync as Hh}from"child_process";import Wh from"path";import ma from"process";import{graphql as qh}from"gql.tada";import{z as Yt}from"zod";var Bh=qh(`
|
|
609
624
|
query ScopeEnforce($projectId: String!, $cwd: String!) {
|
|
610
625
|
project(id: $projectId) {
|
|
611
626
|
id
|
|
@@ -624,14 +639,14 @@ ${i.map(a=>{let l=a.workflow;return l==null?` [intent] (${a.id}) ${a.label??""}
|
|
|
624
639
|
}
|
|
625
640
|
}
|
|
626
641
|
}
|
|
627
|
-
`),
|
|
642
|
+
`),ga=N("Stop",async e=>{let{cwd:t}=e;if(!$(t)||!V(t))return;let r=qe(t),n=Be(t,"stop-enforce")===r;if(n&&!e.stop_hook_active)return;let o=zh(t),i=await Gh(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:
|
|
628
643
|
${i.join(`
|
|
629
644
|
|
|
630
645
|
`)}`}:{decision:"block",reason:i.join(`
|
|
631
646
|
|
|
632
|
-
`)}});function
|
|
647
|
+
`)}});function zh(e){return Gt(e,".ripplo/tests").filter(t=>t.endsWith(".ts")).map(t=>Wh.basename(t,".ts")).filter(t=>t!=="index")}async function Gh(e,t){let r=await j(e);if(!r.ok)return[`--- Compilation failed ---
|
|
633
648
|
${r.error}
|
|
634
|
-
${
|
|
649
|
+
${x("create")}`];await de({cwd:e,result:r.result}),Ve({cwd:e});let n=await Jh(e),o=[...new Set([...t,...n.scopedSlugsToRun])],i=Yh(r,t),s=Xh(r),a=Kh(e,r),l=Qh(e,o);return[i,s,a,l,n.error].filter(c=>c!=null)}function Kh(e,t){let{ignorePaths:r}=Pe(),n=Ji({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(`
|
|
635
650
|
`);s.push(`Unacknowledged interactions (add to a test's .coverage(...)):
|
|
636
651
|
${a}`)}if(i.length>0){let a=i.map(l=>` ${l.id}`).join(`
|
|
637
652
|
`);s.push(`Stale .coverage(...) claims (id no longer exists in source):
|
|
@@ -639,23 +654,23 @@ ${a}`)}return`--- Exhaustiveness ---
|
|
|
639
654
|
${s.join(`
|
|
640
655
|
|
|
641
656
|
`)}
|
|
642
|
-
${
|
|
657
|
+
${x("create")}`}async function Jh(e){let t;try{t=W(e)}catch{return{error:null,scopedSlugsToRun:[]}}let n=(await S({config:t,document:Bh,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null))?.project?.devSession?.scopeItems??[],o=n.flatMap(a=>{let l=a.workflow;return l==null?[` [intent] ${a.label??"(no label)"} \u2014 stub a test for this flow`]:l.spec==null?[` [stub] ${l.slug} \u2014 implement \`${l.name}\``]:[]}),i=n.flatMap(a=>a.workflow?.spec==null?[]:[a.workflow.slug]);return{error:o.length===0?null:`--- Testing Scope ---
|
|
643
658
|
${o.join(`
|
|
644
659
|
`)}
|
|
645
|
-
${
|
|
660
|
+
${x("create")}`,scopedSlugsToRun:i}}function Yh(e,t){let{diagnostics:r}=_e(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 ---
|
|
646
661
|
${[...i,...s].join(`
|
|
647
662
|
`)}
|
|
648
|
-
${
|
|
663
|
+
${x("create")}`}function Xh(e){let{tests:t}=e.builder.getUnimplemented();return t.length===0?null:`--- Unimplemented stubs ---
|
|
649
664
|
${t.join(", ")}
|
|
650
665
|
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.
|
|
651
|
-
${
|
|
666
|
+
${x("create")}`}function Qh(e,t){if(t.length===0)return null;let r=ew(["run",...t],e);if(r.code===0)return null;let n=r.output.split(`
|
|
652
667
|
`).filter(o=>/FAILED/.test(o)).join(`
|
|
653
668
|
`);return n.length===0?null:`--- Ripplo Run Failures (${t.join(" ")}) ---
|
|
654
669
|
${n}
|
|
655
|
-
Artifacts: .ripplo/debug/<runId>/. ${
|
|
656
|
-
`),process.exit(1));let r=await
|
|
657
|
-
`),process.exit(1)});function
|
|
658
|
-
`))}export{
|
|
670
|
+
Artifacts: .ripplo/debug/<runId>/. ${x("debug")}`}var Zh=Yt.object({status:Yt.number().nullish(),stderr:Yt.unknown().optional(),stdout:Yt.unknown().optional()});function fa(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function ew(e,t){let r=ma.argv[1];if(r==null)return{code:1,output:""};try{return{code:0,output:Hh(ma.execPath,[r,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}}catch(n){let o=Zh.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 tw=ya.looseObject({skill:ya.string()}),ha=N("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let t=tw.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)&&ea(e.cwd,e.session_id,n)});uw();Cn(process.cwd());var wa={"coverage-nudge":Ws,"exit-plan-gate":Bs,"plan-reminder":zs,"post-edit-flag-stubs":Js,"post-edit-lint":Xs,"pre-bash-hooks-pause-gate":Zs,"pre-bash-run-gate":na,"pre-edit-ripplo-skill-gate":ia,"pre-edit-scope-gate":la,"pre-edit-watch-gate":da,"scope-reminder":ua,"session-preamble":pa,"stop-enforce":ga,"track-skill-load":ha};async function ow(){await rw(nw(process.argv)).scriptName("ripplo").command("watch","Watch for run requests and execute locally",()=>{},()=>Ns()).command("auth <subcommand>","Manage authentication",dw).command("projects <subcommand>","Inspect Ripplo projects",cw).command("hooks <subcommand>","Pause or resume Ripplo hooks",lw).command("init","Scaffold .ripplo/ in this project",e=>e.option("project",{type:"string"}).option("env-file",{type:"string"}).option("app-url",{type:"string"}).option("engine-url",{type:"string"}),e=>xs({appUrl:e["app-url"],engineUrl:e["engine-url"],envFile:e["env-file"],projectId:e.project})).command("run [ids..]","Run tests in parallel",e=>{let t=[];return e.positional("ids",{array:!0,default:t,describe:"Test ids to run (all if omitted)",type:"string"})},e=>As(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=>Es({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=>ys({id:e.id,runs:e.runs})).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>$s()).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=>Ki({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>Zi()).command("doctor","Check project health",()=>{},()=>ps()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>Us({format:e.format})).command("scope <subcommand>","Manage testing scope",aw).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(wa),demandOption:!0,type:"string"}),e=>iw(e.name)).option("env",{choices:["dev","local"],describe:"Server environment",type:"string"}).strict().help().parse()}async function iw(e){let t=wa[e];t==null&&(process.stderr.write(`Unknown hook: ${e}
|
|
671
|
+
`),process.exit(1));let r=await sw(),n=r.trim()===""?{}:JSON.parse(r),o=await t.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function sw(){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)})}ow().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
|
|
672
|
+
`),process.exit(1)});function aw(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=>Ds({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=>Ls({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=>_s({ids:t.ids})).demandCommand(1)}function lw(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>hs()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>ws()).demandCommand(1)}function cw(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>Ts()).demandCommand(1)}function dw(e){return e.command("login","Authenticate via device flow",()=>{},()=>ki()).command("status","Show authentication status",()=>{},()=>Ri()).command("logout","Remove the saved token",()=>{},()=>{xi()}).demandCommand(1)}function uw(){let e=process.cwd(),t=Xt(e);t!=null&&t!==e&&(process.chdir(t),process.stderr.write(`ripplo: resolved .ripplo/ at ${t}
|
|
673
|
+
`))}export{ow as main};
|
|
659
674
|
/*! Bundled license information:
|
|
660
675
|
|
|
661
676
|
mustache/mustache.mjs:
|