ripplo 0.8.2 → 0.8.3
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/dist/{chunk-WHSQBXWO.js → chunk-7Z7RVHEL.js} +1 -1
- package/dist/{chunk-CRELTIU2.js → chunk-GD63CZVP.js} +19 -19
- package/dist/daemon-EGU25OUV.js +139 -0
- package/dist/hook.js +1 -1
- package/dist/index.js +207 -208
- package/dist/{session-preamble-RJ4WNGJN.js → session-preamble-IHBGHKCW.js} +1 -1
- package/package.json +3 -3
- package/dist/daemon-BN42ZNCJ.js +0 -139
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __ripploCreateRequire } from "node:module";
|
|
3
3
|
const require = globalThis.require ?? __ripploCreateRequire(import.meta.url);
|
|
4
|
-
import{a as e}from"./chunk-7WZ3VIUU.js";import{c as t}from"./chunk-KOKEEAEF.js";import"./chunk-KMZ3L5YA.js";var s="# 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: entity/given modeling, parallel-isolation in engine impls, backend state assertions, 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, etc.).\n\nMatch the task to a skill from the triage table \u2014 if unsure between two, load both. If completely unsure, load `/ripplo:discover` or `/ripplo:create`. Loading is cheap. Acting under-informed is not.\n\n**This is a hard requirement, not a suggestion.** Do NOT run `npx ripplo` commands, edit `.ripplo/` files, or reason about how Ripplo behaves before loading the matching skill. Agents that skip this consistently misuse the CLI, invent flags that don't exist, and hold wrong expectations about compile, run, facts, scope, and the explorer \u2014 every one of those failure modes traces back to acting without the skill loaded. The skill is the source of truth for its area. When in doubt, load it first.\n\nThe skills share one mental model \u2014 how Ripplo thinks (workflows declare state, facts carry across workflows, what compile/run/explorer each enforce), and the rules below are consequences of it. It loads automatically the first time you load a Ripplo skill this session, so load a skill before acting.\n\n## Skill triage\n\n- Load `/ripplo:setup` skill for instructions on initializing Ripplo in a project; `npx ripplo doctor` reports the engine endpoint missing.\n- Load `/ripplo:discover` skill for instructions on planning/stubbing test coverage for a new project or new feature area.\n- Load `/ripplo:create` skill for instructions on authoring a single workflow for a user flow.\n- Load `/ripplo:run` skill for instructions on executing tests, managing the testing scope this session is responsible for, diagnosing a failed run (read artifacts in `.ripplo/debug/<runId>/` before re-running), and filing caught app bugs.\n- Load `/ripplo:tasks` skill for instructions on picking up tasks \u2014 open-ended requests users anchor to a replay frame and element (fix a bug, change behavior, extend or write a workflow, ask a question) and background-explorer findings, which arrive as tasks of their own. It routes the request, lets you ask the user back with `clarify`, and for app changes enforces proof with an exact run, frame, and element. Load it whenever a tasks reminder fires, the user points you at a task or finding, or before any `npx ripplo tasks` command.\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 daemon` (run `/ripplo:start` to spawn it, or invoke it directly via Bash with `run_in_background`), so the dev session is live. Without the daemon, dev-mode hooks don't arm (`ripplo run` will auto-start one if absent). Without the dev server, runs fail when they try to hit the app. `npx ripplo doctor` reports both. Manage the daemon with `npx ripplo daemon status` and `npx ripplo daemon stop` (stale holder, CLI update). Switch executor live with `npx ripplo executor <local|cloud>` \u2014 no restart. Don't use `daemon restart` as an agent \u2014 the start half never returns; stop, then respawn in the background.\n- **Two funnels.** Definitions \u2192 `createRipplo({ entities, singletons, workflows })` in `.ripplo/index.ts`. Implementations \u2192 `createEngine(ripplo, { entities: impls, singletons })` in your app server's `test/engine.ts` \u2014 one `seed`/`read` impl per entity. 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 workflows or stub new ones with `workflow(\"Intent\")` (no body). 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 unimplemented stubs, implement them \u2014 don't ask the user \"implement or defer?\", don't pause hooks to skip them. The fix isn't done until the test is. New scaffolding (entity, given, engine impl) is in-scope work, not follow-up.\n- **You control the hooks \u2014 use it for rapid iteration, never to dodge work.** `npx ripplo hooks pause` silences pre-edit gates and stop-enforce, `npx ripplo hooks resume` re-arms them. Pause when a user asks you to iterate fast on a feature and the checks are noise mid-loop. When you pause, say so, and before you call the work done, resume and run the full check clean. Pausing to escape a failing test or an unimplemented stub is the one thing it's not for.\n- **Keep the explorer running all session.** The background explorer walks composed paths no workflow author wrote \u2014 it fills coverage gaps and catches bugs that only surface when actions combine. It is the third gate, not an extra. A green `npx ripplo run` auto-enables it; check or toggle by hand with `npx ripplo explore [on|off]` (`--trail` sets path depth, `--workers` sets concurrency). Findings arrive as tasks \u2014 triage with `/ripplo:tasks`, and an open finding blocks the session end like any task. Leave it on \u2014 the only real off switch is `npx ripplo hooks pause`.\n- **A workflow is a user journey, not a single-mutation snippet.** One user intent, the real click path from a natural entry point, as many mutations as the intent takes \u2014 with `when` branches wherever seeded state changes an outcome along the path. Authoring method lives in `/ripplo:create`.\n- **Backend assertions are mandatory on mutations.** Every mutation step carries an `Entity.created/updated/deleted` in its `.expect(...)` \u2014 Ripplo checks your app's state against what the test expected. A UI-only check on a mutation ships the bug as green.\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 write `.ripplo/debug/<runId>/behavior.jsonl` \u2014 a causal stream of actions, assertions, rrweb DOM, console, network, and server spans \u2014 and the run output renders the findings. Read them. Never pipe `ripplo run` through `grep`/`tail`/`head`. Form a hypothesis citing an event, make one change, re-run once.\n- **`.ripplo/ripplo.lock` is committed, never hand-edited.** `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 daemon` talks to the wrong server, runs silently fail or hit the sibling worktree's app.\n- **DSL locators are semantic.** Use `role`/`button`/`textbox`/`heading`/`link`; `testId` only when no ARIA role exists.\n- **New backend state?** Add an `entity(...)` in `.ripplo/entities/` and a `seed`/`read` impl in your app's engine funnel (TS flags the missing impl).\n- **Tasks demand exact proof, never hand-waving.** Resolving a task (`npx ripplo tasks resolve`) requires a run that exercises the broken condition plus a frame and element that show the fix \u2014 a red\u2192green assertion or before/after snapshots you Read, anchored on the resolving comment. Never conclude \"fixed\" from the diff, a toast, or a log string. If a run can't yet reach the broken condition, extend or write the workflow that does \u2014 don't resolve without proof. Load `/ripplo:tasks` for the loop.\n- **Know the task lifecycle.** A task is **open** (needs you), **needs clarification** (waiting on the user after your `clarify` \u2014 not your move), **resolved**, or **dismissed**. The task watcher (armed by `/ripplo:start`) wakes you live on a new task, a reopen, or a user reply, even while idle. A **reopen** means your earlier fix didn't hold \u2014 revisit it, don't treat it as a fresh request. If the user resolves or dismisses a task you were working, it's no longer relevant \u2014 stop working it (you find out at your next stop, not via a wake). While hooks are on, you cannot end the session with a task open \u2014 clear each with resolve, clarify, or dismiss. Load `/ripplo:tasks` for the loop.\n\n## Key files\n\n- `.ripplo/index.ts` \u2014 `createRipplo` call.\n- `.ripplo/{entities,singletons,workflows}/index.ts` \u2014 registry aggregators. `.ripplo/givens.ts` + feature `givens.ts` \u2014 given builders.\n- `.ripplo/project.json` \u2014 project id + env-file pointers.\n- `<app>/src/test/engine.ts` \u2014 single impl funnel via `createEngine`.\n- `/ripplo:create` skill \u2014 DSL reference (entities, givens, workflows, backend assertions). Full primitive catalog at `node_modules/@ripplo/testing/DSL.md`.\n",i=t("SessionStart",o=>{if(e(o.cwd))return{hookSpecificOutput:{additionalContext:s,hookEventName:"SessionStart"}}});export{i as sessionPreambleHook};
|
|
4
|
+
import{a as e}from"./chunk-7WZ3VIUU.js";import{c as t}from"./chunk-KOKEEAEF.js";import"./chunk-KMZ3L5YA.js";var s="# 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: entity/given modeling, parallel-isolation in engine impls, backend state assertions, 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, etc.).\n\nMatch the task to a skill from the triage table \u2014 if unsure between two, load both. If completely unsure, load `/ripplo:discover` or `/ripplo:create`. Loading is cheap. Acting under-informed is not.\n\n**This is a hard requirement, not a suggestion.** Do NOT run `npx ripplo` commands, edit `.ripplo/` files, or reason about how Ripplo behaves before loading the matching skill. Agents that skip this consistently misuse the CLI, invent flags that don't exist, and hold wrong expectations about compile, run, facts, scope, and the explorer \u2014 every one of those failure modes traces back to acting without the skill loaded. The skill is the source of truth for its area. When in doubt, load it first.\n\nThe skills share one mental model \u2014 how Ripplo thinks (workflows declare state, facts carry across workflows, what compile/run/explorer each enforce), and the rules below are consequences of it. It loads automatically the first time you load a Ripplo skill this session, so load a skill before acting.\n\n## Skill triage\n\n- Load `/ripplo:setup` skill for instructions on initializing Ripplo in a project; `npx ripplo doctor` reports the engine endpoint missing.\n- Load `/ripplo:discover` skill for instructions on planning/stubbing test coverage for a new project or new feature area.\n- Load `/ripplo:create` skill for instructions on authoring a single workflow for a user flow.\n- Load `/ripplo:run` skill for instructions on executing tests, managing the testing scope this session is responsible for, diagnosing a failed run (read artifacts in `.ripplo/debug/<runId>/` before re-running), and filing caught app bugs.\n- Load `/ripplo:tasks` skill for instructions on picking up tasks \u2014 open-ended requests users anchor to a replay frame and element (fix a bug, change behavior, extend or write a workflow, ask a question) and background-explorer findings, which arrive as tasks of their own. It routes the request, lets you ask the user back with `clarify`, and for app changes enforces proof with an exact run, frame, and element. Load it whenever a tasks reminder fires, the user points you at a task or finding, or before any `npx ripplo tasks` command.\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 daemon` (run `/ripplo:start` to spawn it, or invoke it directly via Bash with `run_in_background`), so the dev session is live. Without the daemon, dev-mode hooks don't arm (`ripplo run` will auto-start one if absent). Without the dev server, runs fail when they try to hit the app. `npx ripplo doctor` reports both. Manage the daemon with `npx ripplo daemon status` and `npx ripplo daemon stop` (stale holder, CLI update). Switch executor live with `npx ripplo executor <local|cloud>` \u2014 no restart. Don't use `daemon restart` as an agent \u2014 the start half never returns; stop, then respawn in the background.\n- **Two funnels.** Definitions \u2192 `createRipplo({ entities, singletons, workflows })` in `.ripplo/index.ts`. Implementations \u2192 `createEngine(ripplo, { entities: impls, singletons })` in your app server's `test/engine.ts` \u2014 one `seed`/`read` impl per entity. 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 workflows or stub new ones with `workflow(\"Intent\")` (no body). 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 unimplemented stubs, implement them \u2014 don't ask the user \"implement or defer?\", don't pause hooks to skip them. The fix isn't done until the test is. New scaffolding (entity, given, engine impl) is in-scope work, not follow-up.\n- **You control the hooks \u2014 use it for rapid iteration, never to dodge work.** `npx ripplo hooks pause` silences pre-edit gates and stop-enforce, `npx ripplo hooks resume` re-arms them. Pause when a user asks you to iterate fast on a feature and the checks are noise mid-loop. When you pause, say so, and before you call the work done, resume and run the full check clean. Pausing to escape a failing test or an unimplemented stub is the one thing it's not for.\n- **Keep the explorer running all session.** The background explorer walks composed paths no workflow author wrote \u2014 it fills coverage gaps and catches bugs that only surface when actions combine. It is the third gate, not an extra. Check or toggle it with `npx ripplo explore [on|off]` (`--trail` sets path depth, `--workers` sets concurrency). Findings arrive as tasks \u2014 triage with `/ripplo:tasks`, and an open finding blocks the session end like any task. Leave it on.\n- **A workflow is a user journey, not a single-mutation snippet.** One user intent, the real click path from a natural entry point, as many mutations as the intent takes \u2014 with `when` branches wherever seeded state changes an outcome along the path. Authoring method lives in `/ripplo:create`.\n- **Backend assertions are mandatory on mutations.** Every mutation step carries an `Entity.created/updated/deleted` in its `.expect(...)` \u2014 Ripplo checks your app's state against what the test expected. A UI-only check on a mutation ships the bug as green.\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 write `.ripplo/debug/<runId>/behavior.jsonl` \u2014 a causal stream of actions, assertions, rrweb DOM, console, network, and server spans \u2014 and the run output renders the findings. Read them. Never pipe `ripplo run` through `grep`/`tail`/`head`. Form a hypothesis citing an event, make one change, re-run once.\n- **`.ripplo/ripplo.lock` is committed, never hand-edited.** `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 daemon` talks to the wrong server, runs silently fail or hit the sibling worktree's app.\n- **DSL locators are semantic.** Use `role`/`button`/`textbox`/`heading`/`link`; `testId` only when no ARIA role exists.\n- **New backend state?** Add an `entity(...)` in `.ripplo/entities/` and a `seed`/`read` impl in your app's engine funnel (TS flags the missing impl).\n- **Tasks demand exact proof, never hand-waving.** Resolving a task (`npx ripplo tasks resolve`) requires a run that exercises the broken condition plus a frame and element that show the fix \u2014 a red\u2192green assertion or before/after snapshots you Read, anchored on the resolving comment. Never conclude \"fixed\" from the diff, a toast, or a log string. If a run can't yet reach the broken condition, extend or write the workflow that does \u2014 don't resolve without proof. Load `/ripplo:tasks` for the loop.\n- **Know the task lifecycle.** A task is **open** (needs you), **needs clarification** (waiting on the user after your `clarify` \u2014 not your move), **resolved**, or **dismissed**. The task watcher (armed by `/ripplo:start`) wakes you live on a new task, a reopen, or a user reply, even while idle. A **reopen** means your earlier fix didn't hold \u2014 revisit it, don't treat it as a fresh request. If the user resolves or dismisses a task you were working, it's no longer relevant \u2014 stop working it (you find out at your next stop, not via a wake). While hooks are on, you cannot end the session with a task open \u2014 clear each with resolve, clarify, or dismiss. Load `/ripplo:tasks` for the loop.\n\n## Key files\n\n- `.ripplo/index.ts` \u2014 `createRipplo` call.\n- `.ripplo/{entities,singletons,workflows}/index.ts` \u2014 registry aggregators. `.ripplo/givens.ts` + feature `givens.ts` \u2014 given builders.\n- `.ripplo/project.json` \u2014 project id + env-file pointers.\n- `<app>/src/test/engine.ts` \u2014 single impl funnel via `createEngine`.\n- `/ripplo:create` skill \u2014 DSL reference (entities, givens, workflows, backend assertions). Full primitive catalog at `node_modules/@ripplo/testing/DSL.md`.\n",r=t("SessionStart",o=>{if(e(o.cwd))return{hookSpecificOutput:{additionalContext:s,hookEventName:"SessionStart"}}});export{r as sessionPreambleHook};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ripplo",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.3",
|
|
4
4
|
"description": "CLI for Ripplo — AI-powered end-to-end testing",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"homepage": "https://ripplo.ai",
|
|
@@ -68,10 +68,10 @@
|
|
|
68
68
|
"tsup": "^8.5.1",
|
|
69
69
|
"vitest": "^4.1.4",
|
|
70
70
|
"@ripplo/core": "^0.0.0",
|
|
71
|
-
"@ripplo/eslint-config": "0.0.0",
|
|
72
|
-
"@ripplo/rrweb-bundle": "0.0.0",
|
|
73
71
|
"@ripplo/graphql": "^0.0.0",
|
|
72
|
+
"@ripplo/eslint-config": "0.0.0",
|
|
74
73
|
"@ripplo/run-report": "0.0.0",
|
|
74
|
+
"@ripplo/rrweb-bundle": "0.0.0",
|
|
75
75
|
"@ripplo/runtime": "^0.0.0",
|
|
76
76
|
"@ripplo/solver": "^0.0.0",
|
|
77
77
|
"@ripplo/spec": "^0.0.0"
|
package/dist/daemon-BN42ZNCJ.js
DELETED
|
@@ -1,139 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { createRequire as __ripploCreateRequire } from "node:module";
|
|
3
|
-
const require = globalThis.require ?? __ripploCreateRequire(import.meta.url);
|
|
4
|
-
import{A as je,B as Be,C,E as Ke,F as Ge,G as ze,I as Je,J as Qe,K as $,e as Se,g as he,j as Ie,k as Ce,l as Te,m as Le,n as We,o as Ae,p as De,q as He,s as qe,t as E,u as b,v as Ue,w as _,x as Fe,y as Oe,z as Ne}from"./chunk-CRELTIU2.js";import{d as ve}from"./chunk-OY6HNCAZ.js";import{a as Me,c as _e,d as $e,e as I}from"./chunk-UVYCSHOJ.js";import{c as h}from"./chunk-LEFXRK53.js";import{e as we}from"./chunk-4W6WIT7T.js";import{a as oe}from"./chunk-R4ZTRVDQ.js";import{c as X}from"./chunk-FEHVIHVA.js";import{b as te}from"./chunk-2MT2MZJW.js";import{a as M}from"./chunk-AVBP7Q2M.js";import"./chunk-MHNGR6M7.js";import{g as fe,h as me}from"./chunk-EK6TENV6.js";import{f as R,g as ne,h as U}from"./chunk-AQ3DMGAY.js";import{e as ye,f as ge}from"./chunk-DBIXYJRB.js";import{c as V,d as y,f as s,g as q,h as Y}from"./chunk-PE5WVWI5.js";import"./chunk-CJUKILIO.js";import{b as ke,c as xe,d as Pe,e as Re,f as Ee,h as be}from"./chunk-M7VQD4VO.js";import{M as se,O as le,P as de,Q as ce,R as ue,S as pe,d as ie,h as ae}from"./chunk-ESOXRGIY.js";import{A as Z,H as ee,N as re}from"./chunk-5SM4TCSW.js";import"./chunk-NNH3YVVO.js";import"./chunk-KMZ3L5YA.js";import Rn from"path";import{createClient as En}from"graphql-sse";import bn,{AbortError as In}from"p-retry";import{graphql as Q}from"gql.tada";import{graphql as zr}from"gql.tada";import{print as Jr}from"graphql";async function Ve({config:e,cwd:r,headed:o,pool:n,runId:t,signal:i,testSlug:a,workClass:l,workflowSlug:d}){let u=await R(r);if(u.isErr())return await C(e,t,`lockfile:${u.error.kind}`),{kind:"dispatch-error",reason:{detail:`lockfile:${u.error.kind}`,type:"generic"}};let p=Gr(u.value,{testSlug:a,workflowSlug:d});if(p==null)return await C(e,t,`no-test:${d}/${a}`),{kind:"dispatch-error",reason:{detail:`no-test:${d}/${a}`,type:"generic"}};let c=await E({headed:o,workClass:l,task:()=>n.execute({headed:o,runId:t,testRef:p},i)});return!c.serverNotified&&c.outcome.kind==="error"&&await C(e,t,c.outcome.detail),c.outcome}function Gr(e,{testSlug:r,workflowSlug:o}){let t=e.workflows.find(i=>re(i.name)===o)?.tests.find(i=>i.slug===r);return t==null?void 0:ie(t)}var Qr=6e4,Vr=zr(`
|
|
5
|
-
subscription RunRequestedWatch($devSessionId: String!) {
|
|
6
|
-
runRequested(devSessionId: $devSessionId) {
|
|
7
|
-
runId
|
|
8
|
-
testSlug
|
|
9
|
-
workflowId
|
|
10
|
-
workflowSlug
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
`);async function Ye(e){let r=Math.min(1e3*2**e,Qr)+Zr();await new Promise(o=>setTimeout(o,r))}function Xe({claim:e,cwd:r,devSessionId:o,onSubscriptionDead:n,pool:t,sseClient:i,sseHealth:a}){let l=new Set;return i.subscribe({query:Jr(Vr),variables:{devSessionId:o}},{complete:()=>{},error:d=>{let u=d instanceof Error?d.message:String(d);s.warn("runRequested SSE failed: %s; re-registering session",u),n(u)},next:d=>{Yr({claim:e,cwd:r,event:d.data?.runRequested,inFlightRunIds:l,pool:t})}},{connected:()=>{a.onConnected()},connecting:d=>{a.onConnecting(d),d&&s.debug("runRequested SSE reconnecting")}})}function Yr({claim:e,cwd:r,event:o,inFlightRunIds:n,pool:t}){if(o==null)return;if(n.has(o.runId)){s.warn({runId:o.runId,workflowSlug:o.workflowSlug},"duplicate runRequested event; skipping dispatch");return}n.add(o.runId),process.stdout.write(`ripplo: run ${o.workflowSlug}
|
|
14
|
-
`),X(r);let i=h(r).match(l=>l,l=>{s.error({failure:l,runId:o.runId},"failed to load env for run dispatch; skipping")});if(i==null){n.delete(o.runId);return}let a=Xr(e(o.runId),o);a.started(),Ve({config:i,cwd:r,headed:a.headed,pool:t,runId:o.runId,signal:a.signal,testSlug:o.testSlug,workClass:a.workClass,workflowSlug:o.workflowSlug}).then(l=>{a.finished(l)}).catch(l=>{s.error({err:l,runId:o.runId,workflowSlug:o.workflowSlug},"run execution failed; daemon continuing"),a.finished({detail:l instanceof Error?l.message:String(l),kind:"error"})}).finally(()=>{n.delete(o.runId)})}function Xr(e,r){return e==null?(s.debug({runId:r.runId,workflowSlug:r.workflowSlug},"dispatching unclaimed run (externally triggered or replayed)"),{headed:!1,signal:new AbortController().signal,workClass:"p0-ui",finished:()=>{},started:()=>{}}):{headed:e.headed,signal:Oe(e.token),workClass:"p1-cli",finished:o=>{e.finished(r.runId,o)},started:()=>{e.started(r.runId)}}}function Zr(){return Math.floor(Math.random()*2700)+300}import{graphql as F}from"gql.tada";import{print as eo}from"graphql";var ro=F(`
|
|
15
|
-
subscription TeleportRequestedWatch($devSessionId: String!) {
|
|
16
|
-
teleportRequested(devSessionId: $devSessionId) {
|
|
17
|
-
runId
|
|
18
|
-
stepIndex
|
|
19
|
-
kind
|
|
20
|
-
testSlug
|
|
21
|
-
workflowSlug
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
`),oo=F(`
|
|
25
|
-
query TeleportRunRepro($id: String!) {
|
|
26
|
-
run(id: $id) {
|
|
27
|
-
id
|
|
28
|
-
reproJson
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
`),no=F(`
|
|
32
|
-
mutation ReportTeleportResult($devSessionId: String!, $runId: String!, $status: String!) {
|
|
33
|
-
reportTeleportResult(devSessionId: $devSessionId, runId: $runId, status: $status)
|
|
34
|
-
}
|
|
35
|
-
`);function Ze({cwd:e,devSessionId:r,onSubscriptionDead:o,sseClient:n}){let t=new Set,i=n.subscribe({query:eo(ro),variables:{devSessionId:r}},{complete:()=>{},error:a=>{let l=a instanceof Error?a.message:String(a);s.warn("teleportRequested SSE failed: %s; re-registering session",l),o(l)},next:a=>{to({cwd:e,devSessionId:r,event:a.data?.teleportRequested,running:t})}});return()=>{t.forEach(a=>{a.abort()}),t.clear(),i()}}function to({cwd:e,devSessionId:r,event:o,running:n}){if(o==null)return;let t=new AbortController;n.add(t),io({cwd:e,devSessionId:r,event:o,signal:t.signal}).catch(i=>{s.error({err:i},"teleport failed; daemon continuing")}).finally(()=>{n.delete(t)})}async function io({cwd:e,devSessionId:r,event:o,signal:n}){let t=d=>ao({cwd:e,devSessionId:r,runId:o.runId,status:d}),i=await so(e,o);if(i==null){s.warn({runId:o.runId},"teleport could not resolve target"),await t("unplannable");return}process.stdout.write(`ripplo: teleport ${co(o)} step ${String(o.stepIndex+1)}
|
|
36
|
-
`);let l=await Je({cwd:e,onReady:()=>{t("opened")},signal:n,step:o.stepIndex+1,target:i});l.kind==="done"&&l.result.kind==="handed-over"||(s.warn({kind:l.kind,runId:o.runId},"teleport could not open"),await t(l.kind==="unplannable"?"unplannable":"error"))}async function ao({cwd:e,devSessionId:r,runId:o,status:n}){let t=h(e).match(i=>i,()=>null);t!=null&&await y({config:t,document:no,variables:{devSessionId:r,runId:o,status:n}}).catch(()=>null)}async function so(e,r){if(r.kind==="explore"){let o=await lo(e,r.runId);return o==null?null:{kind:"explore",repro:o}}return r.testSlug==null||r.workflowSlug==null?null:{kind:"test",ref:`${r.workflowSlug}/${r.testSlug}`}}async function lo(e,r){let o=h(e).match(t=>t,()=>null);if(o==null)return null;let n=await y({config:o,document:oo,variables:{id:r}}).catch(()=>null);return n?.run?.reproJson==null?null:le.parse(JSON.parse(n.run.reproJson))}function co(e){return e.kind==="explore"?"explore finding":`${String(e.workflowSlug)}/${String(e.testSlug)}`}function er(){let e=!0,r,o=null,n=()=>{o!=null&&(clearTimeout(o),o=null)};return{markUnhealthy:t=>{e=!1,r=t,n()},onConnected:()=>{n(),o=setTimeout(()=>{e=!0,r=void 0,o=null},1e4)},onConnecting:()=>{n()},snapshot:()=>({detail:r,ok:e})}}import uo from"fs";import tr from"net";import{err as ir,ok as po}from"neverthrow";async function ar({cwd:e,onConnection:r}){Y(e);let o=ve(e),n=await rr({onConnection:r,socketPath:o});return n.isOk()||n.error.kind!=="stale-candidate"?n.map(or(o)).mapErr(nr(o)):await fo(o)?ir({kind:"already-running",socketPath:o}):(sr(o),(await rr({onConnection:r,socketPath:o})).map(or(o)).mapErr(nr(o)))}function fo(e){return new Promise(r=>{let o=tr.connect(e);o.once("connect",()=>{o.destroy(),r(!0)}),o.once("error",()=>{r(!1)})})}async function rr(e){let r=await mo(e);return r.kind==="listening"?po(r.server):ir(r.error)}function mo({onConnection:e,socketPath:r}){return new Promise(o=>{let n=tr.createServer(e);n.once("error",t=>{o({error:t.code==="EADDRINUSE"?{kind:"stale-candidate"}:{kind:"listen-failed",message:t.message},kind:"failed"})}),n.listen(r,()=>{o({kind:"listening",server:n})})})}function or(e){return r=>({socketPath:e,close:()=>{r.close(),sr(e)}})}function sr(e){uo.rmSync(e,{force:!0})}function nr(e){return r=>r.kind==="stale-candidate"?{kind:"already-running",socketPath:e}:{kind:"bind-failed",message:r.message}}import{randomInt as yo,randomUUID as go}from"crypto";function dr(e){let r={attempts:0,consecutiveErrors:0,driverBackoffUntil:0,findings:0,lastUnhealthyReportMs:0,lockfile:null,prepared:null,preparing:!1,refreshing:!1,windowAttempts:0,windowFindings:0,windowStartMs:Date.now()},o=O(e,r);return{priority:"p3",next:()=>Po(e,r),onResult:()=>{},ready:()=>o,status:()=>({attempts:r.attempts,findings:r.findings}),stop:()=>Promise.resolve()}}var So=10;async function O(e,r){if(!r.preparing){r.preparing=!0;try{let o=await e.loadLockfile(),n=o==null?null:await wo(o);if(n==null||o==null)return;r.lockfile=o.lockfile,r.prepared=n,N(r),e.notifyWork()}finally{r.preparing=!1}}}async function wo({lockfile:e,rawHash:r}){let o=await ce(e);return o==null?null:{exploration:o,lockfileHashValue:r,strategy:se("even")}}var vo=6,ho=3e4,ko=2e4;function N(e){e.consecutiveErrors=0,e.driverBackoffUntil=0,e.lastUnhealthyReportMs=0}async function xo(e,r){if(!(r.refreshing||r.preparing||r.prepared==null)){r.refreshing=!0;try{let o=await e.loadLockfile();if(o==null||o.rawHash===r.prepared.lockfileHashValue)return;s.info("workflow definitions changed, re-preparing exploration"),r.prepared=null,await O(e,r)}finally{r.refreshing=!1}}}function Po(e,r){xo(e,r);let o=r.prepared;if(o==null||Date.now()<r.driverBackoffUntil)return null;let n=ue({lockfileHash:o.lockfileHashValue,prepared:o.exploration,random:Ro,strategy:{...o.strategy,maxAttemptLength:e.maxTrailLength()}});if(n==null)return null;let t=n.baseStateTest.name;return{id:`explore:${go()}`,label:t,run:i=>Eo({assign:n,params:e,signal:i,state:r})}}var lr=2**31;function Ro(){return yo(lr)/lr}async function Eo({assign:e,params:r,signal:o,state:n}){if(!await r.probeApp()){cr({params:r,reason:"app-unreachable",state:n});return}let t=await r.executeTrail(e,o);if(t.kind==="aborted")return;if(t.kind==="error"){Io({params:r,reason:t.reason,state:n});return}N(n),n.attempts+=1,n.windowAttempts+=1;let i=t.kind==="finding";i&&(n.findings+=1,n.windowFindings+=1,s.info("exploration finding recorded")),r.reportProgress({attempts:1,findings:i?1:0,result:t}),n.windowAttempts>=So&&bo(n)}function bo(e){let r=Date.now()-e.windowStartMs;s.info({attempts:e.windowAttempts,avgTrailMs:Math.round(r/e.windowAttempts),findings:e.windowFindings,windowMs:r,yield:Number((e.windowFindings/e.windowAttempts).toFixed(3))},"explore window"),e.windowAttempts=0,e.windowFindings=0,e.windowStartMs=Date.now()}function Io({params:e,reason:r,state:o}){if(r?.startsWith("lockfile:daemon-load-failed")===!0){Co(e,o);return}cr({params:e,reason:r,state:o})}function Co(e,r){r.preparing||(r.prepared=null,O(e,r))}function cr({params:e,reason:r,state:o}){let n=Lo(r);if(n==="trail"){N(o);return}o.consecutiveErrors+=1,s.debug("exploration infra error: %s",r),!(o.consecutiveErrors<vo)&&(n==="driver"&&(o.driverBackoffUntil=Date.now()+ho),To({params:e,reason:r,state:o}))}function To({params:e,reason:r,state:o}){let n=Date.now();n-o.lastUnhealthyReportMs<ko||(o.lastUnhealthyReportMs=n,s.warn("exploration unhealthy after %d consecutive infra errors (last: %s)",o.consecutiveErrors,r),e.reportUnhealthy())}function Lo(e){return e==="app-unreachable"?"driver":e==null||e==="error"||e.startsWith("transport:")?"infra":e.startsWith("runtime:")?Wo(e.slice(8)):"trail"}function Wo(e){return e==="driver-launch"?"driver":ae(e)?"infra":"trail"}function j(e){return{priority:e,next:()=>null,onResult:()=>{}}}function ur({config:e,executorIsLocal:r,pool:o}){return Ho({appUrl:e.appUrl,cwd:e.cwd,executorIsLocal:r,executeTrail:async(n,t)=>(await o).exploreTrail(n,t)})}function Ho({appUrl:e,cwd:r,executeTrail:o,executorIsLocal:n}){let t={concurrency:2,enabled:!1,maxTrailLength:12},i={notify:()=>{}},a={report:p=>{}},l={report:()=>{}},d=qo({appUrl:e,cwd:r,executeTrail:o,maxTrailLength:()=>t.maxTrailLength,notifyWork:()=>{i.notify()},reportProgress:p=>{a.report(p)},reportUnhealthy:()=>{l.report()}}),u=he({now:Date.now,probe:Mo,setTimer:_o,sources:[j("p0"),j("p1"),d],execute:({job:p,priority:c,signal:f})=>E({headed:!1,workClass:$o(c),task:()=>p.run(f)}),exploreConcurrency:()=>t.concurrency,exploreEnabled:()=>t.enabled&&n()});return _(()=>{u.notifyQueueChange()}),i.notify=()=>{u.notifyQueueChange()},{notifyExecutorChanged:()=>{u.notifyQueueChange()},progress:()=>d.status(),setConcurrency:p=>{n()&&p!==t.concurrency&&s.info({workers:p},"explore local worker count changed"),t.concurrency=p,u.notifyQueueChange()},setEnabled:p=>{t.enabled=p,u.notifyQueueChange()},setMaxTrailLength:p=>{t.maxTrailLength=p},setReportProgress:p=>{a.report=p},setReportUnhealthy:p=>{l.report=p},status:()=>({explorer:Uo(t.enabled,u.stalled()),exploring:u.explorationActive(),progress:d.status()}),stop:()=>{u.stop(),_(null),d.stop()}}}function qo({appUrl:e,cwd:r,executeTrail:o,maxTrailLength:n,notifyWork:t,reportProgress:i,reportUnhealthy:a}){return dr({cwd:r,executeTrail:o,maxTrailLength:n,notifyWork:t,reportProgress:i,reportUnhealthy:a,loadLockfile:async()=>{let{fingerprint:l,result:d}=await ne(r),u=await I(r);return u==null?null:d.match(async p=>{let c=await me(r,p);return c==null?null:{fingerprint:l,lockfile:c,rawHash:u}},()=>Promise.resolve(null))},probeApp:async()=>await Se(e)==null})}function Uo(e,r){return e?r>0?"stalled":"on":"off"}function Mo(){let e=Ue();return{headedActive:e.headedActive,interactiveActive:e.active,interactiveQueued:e.queued,poolSize:e.poolSize}}function _o(e,r){let o=setTimeout(e,r);return()=>{clearTimeout(o)}}function $o(e){switch(e){case"p0":return"p0-ui";case"p1":return"p1-cli";case"p2":return"p2-cover";case"p3":return"p3-explore"}}import{graphql as rn}from"gql.tada";import{connect as Oo}from"net";import No from"ssh2";import{WebSocket as fr,createWebSocketStream as jo}from"ws";var Fo="ripplo-";function B(e){return Object.entries(e).map(([r,o])=>`${Fo}${r}.${o}`)}var{Server:Bo,utils:pr}=No;function mr(){let e=pr.generateKeyPairSync("ed25519"),r=pr.parseKey(e.private);if(r instanceof Error)throw r;return{fingerprint:r.getPublicSSH().toString("base64"),privateKey:e.private}}function yr(e){return new Promise((r,o)=>{let n={closers:new Set,stopped:!1},t=new fr(e.relayUrl,B({grant:e.grant,role:"daemon-control"}));t.on("open",()=>{s.info("cloud-executor relay control up"),r({stop:Ko(t,n)})}),t.on("message",i=>{Go(e,n,i)}),t.on("close",(i,a)=>{n.stopped||s.warn({code:i,reason:a.toString()},"relay control closed"),en(e,n)}),t.on("error",i=>{o(i instanceof Error?i:new Error(String(i)))})})}function Ko(e,r){return()=>(r.stopped=!0,r.closers.forEach(o=>{o()}),e.close(),Promise.resolve())}function Go(e,r,o){let n=zo(o);n!=null&&Qo(e,r,n.pipeId)}function zo(e){try{let r=JSON.parse(Jo(e));return typeof r=="object"&&r!=null&&"signal"in r&&r.signal==="open-data"&&"pipeId"in r&&typeof r.pipeId=="string"?{pipeId:r.pipeId}:null}catch{return null}}function Jo(e){return Buffer.isBuffer(e)?e.toString("utf8"):Array.isArray(e)?Buffer.concat(e).toString("utf8"):Buffer.from(e).toString("utf8")}function Qo(e,r,o){if(r.stopped)return;let n=new fr(e.relayUrl,B({pipeId:o,role:"daemon-data"}));n.on("open",()=>{Vo(e,r,n)}),n.on("error",t=>{s.warn({err:t},"cloud-executor relay data pipe error")})}function Vo(e,r,o){let n=jo(o);n.on("error",()=>{});let t=new Bo({hostKeys:[e.hostKey.privateKey]},a=>{a.on("error",l=>{s.warn({err:l},"cloud-executor ssh connection error")}),a.on("authentication",l=>{Xo(l,e.secret)}),a.on("ready",()=>{a.on("tcpip",(l,d,u)=>{Zo({accept:l,allowedPorts:e.allowedPorts,deny:d,destPort:u.destPort})})})}),i=()=>{o.close()};r.closers.add(i),o.on("close",()=>r.closers.delete(i)),Yo(t,n)}function Yo(e,r){e.injectSocket(r)}function Xo(e,r){if(e.method==="password"&&e.password===r){e.accept();return}if(e.method==="none"){e.reject(["password"]);return}e.reject()}function Zo({accept:e,allowedPorts:r,deny:o,destPort:n}){if(!r.includes(n)){o();return}let t=!1,i=Oo({autoSelectFamily:!0,host:"localhost",port:n},()=>{t=!0;let a=e();a.on("error",()=>{}),i.pipe(a).pipe(i)});i.on("error",()=>{t||o()})}function en(e,r){r.stopped||(r.stopped=!0,r.closers.forEach(o=>{o()}),e.onFatal())}var on=rn(`
|
|
37
|
-
mutation EnterCloudMode(
|
|
38
|
-
$devSessionId: String!
|
|
39
|
-
$localUrl: String!
|
|
40
|
-
$engineUrl: String!
|
|
41
|
-
$hostKeyFingerprint: String!
|
|
42
|
-
) {
|
|
43
|
-
enterCloudMode(
|
|
44
|
-
devSessionId: $devSessionId
|
|
45
|
-
localUrl: $localUrl
|
|
46
|
-
engineUrl: $engineUrl
|
|
47
|
-
hostKeyFingerprint: $hostKeyFingerprint
|
|
48
|
-
) {
|
|
49
|
-
__typename
|
|
50
|
-
... on RelaySession {
|
|
51
|
-
generation
|
|
52
|
-
grant
|
|
53
|
-
relayUrl
|
|
54
|
-
secret
|
|
55
|
-
session
|
|
56
|
-
}
|
|
57
|
-
... on DevSessionEndedError {
|
|
58
|
-
message
|
|
59
|
-
}
|
|
60
|
-
... on TunnelNotConfiguredError {
|
|
61
|
-
message
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
`),T=class extends Error{failure;constructor(r){super(r.kind),this.failure=r}};async function K({config:e,devSessionId:r,onFatal:o}){let n=mr(),i=(await y({config:e,document:on,variables:{devSessionId:r,engineUrl:e.engineUrl,hostKeyFingerprint:n.fingerprint,localUrl:e.appUrl}})).enterCloudMode;if(i==null)throw new T({kind:"empty-response"});if(i.__typename!=="RelaySession")throw new T({kind:"server-error",typename:i.__typename});let a=await yr({allowedPorts:[...new Set([gr(e.appUrl),gr(e.engineUrl)])],grant:i.grant,hostKey:n,onFatal:o,relayUrl:i.relayUrl,secret:i.secret});return s.info({session:i.session},"cloud-executor relay up"),{stop:a.stop}}function gr(e){let r=new URL(e);return r.port.length>0?Number(r.port):r.protocol==="https:"?443:80}var nn=[1e3,3e3,8e3,15e3];function Sr({config:e,onChanged:r}){let o={devSessionId:null,mode:"local",queue:Promise.resolve(),tunnel:void 0},n=()=>{o.tunnel=void 0,i(0)},t=()=>o.mode==="cloud",i=async c=>{let f=o.devSessionId;if(!t()||f==null)return;let m=nn[c];if(m==null){s.warn("tunnel connector gave up; reverting executor to local"),p("local"),$(e,"local");return}if(s.warn({attempt:c+1},"relay tunnel dropped; reconnecting"),await new Promise(w=>setTimeout(w,m)),!(!t()||o.tunnel!=null))try{let w=await K({config:e,devSessionId:f,onFatal:n});if(!t()){await w.stop();return}o.tunnel=w,s.info("relay tunnel reconnected")}catch{i(c+1)}},a=async c=>{let f=await K({config:e,devSessionId:c,onFatal:n});o.tunnel=f,o.mode="cloud",s.info("executor switched to cloud"),r()},l=async()=>{let c=o.tunnel;o.tunnel=void 0,o.mode="local",c!=null&&await c.stop(),s.info("executor switched to local"),r()},d=async c=>{let f=o.devSessionId;if(!(f==null||c===o.mode)){if(c==="cloud"){await a(f);return}await l()}},u=async c=>{s.warn({err:c},"executor switch failed; staying local"),await $(e,"local").catch(()=>{})},p=c=>{o.queue=o.queue.then(()=>d(c).catch(u))};return{request:p,connect:c=>{o.devSessionId=c},current:()=>o.mode,stop:async()=>{await o.queue.catch(()=>{}),await d("local")}}}import{readdir as tn}from"fs/promises";import{existsSync as wr}from"fs";import G from"path";async function vr({config:e,cwd:r}){let o=G.join(r,".ripplo","debug");await(await tn(o,{withFileTypes:!0}).catch(()=>[])).filter(i=>i.isDirectory()).map(i=>i.name).filter(i=>!i.startsWith("replay-")&&!i.startsWith("explore-")&&!wr(G.join(o,i,je))&&wr(G.join(o,i,"behavior.jsonl"))).reduce((i,a)=>i.then(()=>Be({config:e,debugDir:o,runId:a}).catch(()=>{})),Promise.resolve(void 0))}import{fork as an}from"child_process";import hr from"os";import{CancellationTokenSource as kr,ResponseError as xr}from"vscode-jsonrpc/node";function Pr(e,r){return()=>{let o=an(e,["run-worker"],{cwd:r,detached:!0,stdio:["ignore","inherit","inherit","ipc"]});return{connection:He(o),kill:()=>{sn(o)},onExit:n=>{o.once("exit",n)}}}}function Rr(e){let r={closed:!1,devSessionId:e.devSessionId,lockfileProvider:e.lockfileProvider,nextId:0,size:e.initialSize,spawn:e.spawn,waiters:[],workers:[]};return Cr(r),{close:async()=>{r.closed=!0,await Promise.all([...r.workers].map(o=>z(o,r)))},execute:(o,n)=>cn(o,n,r),exploreTrail:(o,n)=>pn(o,n,r),routeSpan:(o,n)=>{let t=r.workers.find(i=>i.runId===o);t?.worker.connection.sendNotification(Ae,{runId:o,span:n})},setSize:o=>{mn(o,r)}}}function sn(e){let r=e.pid;if(r!=null)try{process.kill(-r,"SIGKILL")}catch{e.kill("SIGKILL")}}var ln=1e4,dn=1e4,Er=-32800;async function cn(e,r,o){let n=await br(o);if(n.runId=e.runId,!n.alive)return L(n,o),{outcome:{detail:"worker-exit",kind:"error"},serverNotified:!1};let t=new kr,i=()=>{t.cancel()};r.aborted&&t.cancel(),r.addEventListener("abort",i,{once:!0});try{let a=await n.worker.connection.sendRequest(Te,e,t.token),l=Ie.safeParse(a);return l.success?l.data:{outcome:{detail:"bad-outcome-frame",kind:"error"},serverNotified:!1}}catch(a){return un(a,n)}finally{r.removeEventListener("abort",i),t.dispose(),L(n,o)}}async function br(e){let r=e.workers.find(o=>o.alive&&o.runId===void 0);if(r!=null)return r.runId="pending",await r.ready,r;if(e.workers.length<e.size){let o=Ir(e);return o.runId="pending",await o.ready,o}return new Promise(o=>{e.waiters.push(n=>{n.runId="pending",o(n)})})}function Ir(e){let r=e.spawn(),o={resolve:()=>{}},n={alive:!0,id:e.nextId,ready:new Promise(t=>{o.resolve=t,r.connection.onNotification(Ce,t)}),runId:void 0,worker:r};return e.nextId+=1,r.connection.onRequest(Le,()=>e.lockfileProvider()),r.onExit(()=>{n.alive=!1,e.workers=e.workers.filter(t=>t!==n),r.connection.dispose(),o.resolve()}),e.workers.push(n),n}function L(e,r){if(e.runId=void 0,!e.alive||r.closed)return;if(r.workers.length>r.size){z(e,r);return}let o=r.waiters.shift();o?.(e)}async function z(e,r){if(r.workers=r.workers.filter(t=>t!==e),!e.alive)return;let o=new Promise(t=>{e.worker.onExit(t)});await e.ready,await e.worker.connection.sendNotification(De).catch(()=>{});let n=setTimeout(()=>{e.worker.kill()},ln);await o,clearTimeout(n)}function un(e,r){return e instanceof xr&&e.code===Er?{outcome:{detail:"aborted",kind:"error"},serverNotified:!1}:r.alive?{outcome:{detail:e instanceof Error?e.message:String(e),kind:"error"},serverNotified:!1}:{outcome:{detail:"worker-exit",kind:"error"},serverNotified:!1}}async function pn(e,r,o){let n=await br(o);if(n.runId="explore",!n.alive)return L(n,o),{kind:"error"};let t=new kr,i={cancel:()=>{}},a=()=>{t.cancel();let l=setTimeout(()=>{n.worker.kill()},dn);i.cancel=()=>{clearTimeout(l)}};r.aborted&&a(),r.addEventListener("abort",a,{once:!0});try{let l=await n.worker.connection.sendRequest(We,{assign:e,devSessionId:o.devSessionId},t.token),d=de.safeParse(l);return d.success?d.data:{kind:"error"}}catch(l){return fn(l)}finally{i.cancel(),r.removeEventListener("abort",a),t.dispose(),L(n,o)}}function fn(e){return e instanceof xr&&e.code===Er?{kind:"aborted"}:{kind:"error",reason:`transport:${e instanceof Error?e.message.slice(0,120):"unknown"}`}}function mn(e,r){r.size=e,e>hr.availableParallelism()&&s.warn({cores:hr.availableParallelism(),size:e},"worker pool size exceeds available cores");let o=r.workers.filter(t=>t.alive&&t.runId===void 0),n=r.workers.length-e;o.slice(0,Math.max(0,n)).forEach(t=>{z(t,r)}),Cr(r)}function Cr(e){e.closed||Array.from({length:Math.max(0,e.size-e.workers.length)}).forEach(()=>{Ir(e)})}import W from"fs";import yn from"p-retry";import{graphql as x}from"gql.tada";import{print as A}from"graphql";var gn=x(`
|
|
66
|
-
query DaemonExploration($devSessionId: String!) {
|
|
67
|
-
exploration(devSessionId: $devSessionId) {
|
|
68
|
-
active
|
|
69
|
-
localWorkers
|
|
70
|
-
maxTrailLength
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
`),Sn=x(`
|
|
74
|
-
subscription WatchExplorationChanged($devSessionId: String!) {
|
|
75
|
-
explorationChanged(devSessionId: $devSessionId) {
|
|
76
|
-
exploration {
|
|
77
|
-
active
|
|
78
|
-
localWorkers
|
|
79
|
-
maxTrailLength
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
`);function Tr({config:e,devSessionId:r,machinery:o,sseClient:n}){return yn(()=>wn({config:e,devSessionId:r,machinery:o}),{factor:2,minTimeout:500,retries:6}).catch(t=>{s.warn({err:t},"initial exploration state read failed \u2014 explorer stays off")}),n.subscribe({query:A(Sn),variables:{devSessionId:r}},{complete:()=>{},error:t=>{s.error(t,"exploration subscription error")},next:t=>{Lr(o,t.data?.explorationChanged.exploration)}})}async function wn({config:e,devSessionId:r,machinery:o}){let n=await y({config:e,document:gn,variables:{devSessionId:r}});Lr(o,n.exploration)}function Lr(e,r){r!=null&&(e.setMaxTrailLength(r.maxTrailLength),e.setConcurrency(r.localWorkers),e.setEnabled(r.active))}function Wr({config:e,devSessionId:r,machinery:o}){o.setReportProgress(n=>{Ge({attempts:n.attempts,config:e,devSessionId:r,findings:n.findings,trail:Ke(n.result)}).catch(t=>{s.warn({error:t},"exploration progress report failed")})}),o.setReportUnhealthy(()=>{ze(e,r).catch(n=>{s.warn({error:n},"exploration unhealthy report failed")})})}var vn=x(`
|
|
84
|
-
subscription HooksPausedWatch($projectId: String!) {
|
|
85
|
-
hooksPausedRequested(projectId: $projectId) {
|
|
86
|
-
paused
|
|
87
|
-
projectId
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
`),hn=x(`
|
|
91
|
-
subscription WatchLocalConcurrencyChanged {
|
|
92
|
-
myMaxLocalConcurrentRunsChanged
|
|
93
|
-
}
|
|
94
|
-
`);function Ar({pool:e,sseClient:r}){return r.subscribe({query:A(hn)},{complete:()=>{},error:o=>{s.error(o,"localConcurrency subscription error")},next:o=>{let n=o.data?.myMaxLocalConcurrentRunsChanged;n!=null&&(b(n),e.setSize(n))}})}var kn=x(`
|
|
95
|
-
subscription WatchExecutorChangeRequested($devSessionId: String!) {
|
|
96
|
-
executorChangeRequested(devSessionId: $devSessionId) {
|
|
97
|
-
executor
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
`);function Dr({config:e,devSessionId:r,sseClient:o,switcher:n}){return n.connect(r),xn({config:e,switcher:n}),Pn({devSessionId:r,sseClient:o,switcher:n})}async function xn({config:e,switcher:r}){let o=await Qe(e);if(o.isErr()){s.warn({error:o.error},"initial executor fetch failed, staying local");return}r.request(o.value)}function Pn({devSessionId:e,sseClient:r,switcher:o}){return r.subscribe({query:A(kn),variables:{devSessionId:e}},{complete:()=>{},error:n=>{s.error(n,"executor subscription error")},next:n=>{let t=n.data?.executorChangeRequested?.executor;t!=null&&o.request(t)}})}function Hr({cwd:e,projectId:r,sseClient:o}){return o.subscribe({query:A(vn),variables:{projectId:r}},{complete:()=>{},error:n=>{s.error(n,"hooksPaused subscription error")},next:n=>{let t=n.data?.hooksPausedRequested?.paused;t!=null&&J({cwd:e,paused:t})}})}function J({cwd:e,paused:r}){let o=we(e);if(r&&!W.existsSync(o)){W.writeFileSync(o,"");return}!r&&W.existsSync(o)&&W.unlinkSync(o)}var Cn=6e4,qr=500,Tn=15e3,Ur=6e4,Ln=3,Wn=Q(`
|
|
101
|
-
mutation HeartbeatDevSessionWatch($id: String!) {
|
|
102
|
-
heartbeatDevSession(id: $id) {
|
|
103
|
-
__typename
|
|
104
|
-
... on DevSession {
|
|
105
|
-
id
|
|
106
|
-
}
|
|
107
|
-
... on DevSessionEndedError {
|
|
108
|
-
message
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
`),An=Q(`
|
|
113
|
-
query WatchLocalConcurrency {
|
|
114
|
-
currentUser {
|
|
115
|
-
id
|
|
116
|
-
maxLocalConcurrentRuns
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
`),Dn=Q(`
|
|
120
|
-
mutation EndDevSessionWatch($projectId: String!, $cwd: String!, $devSessionId: String) {
|
|
121
|
-
endDevSession(projectId: $projectId, cwd: $cwd, devSessionId: $devSessionId) {
|
|
122
|
-
__typename
|
|
123
|
-
... on DevSession {
|
|
124
|
-
id
|
|
125
|
-
}
|
|
126
|
-
... on NoActiveDevSessionError {
|
|
127
|
-
message
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
`);async function ra(){Vn();let e=Gn(process.cwd()),r=e.cwd,o=On(r),{executorSwitch:n,exploration:t,poolGate:i}=Hn(e),a={handler:()=>{}},l=jn(),d=er(),u=Ne({config:e,cwd:r,executor:n.current,explorationStatus:t.status,ready:l.promise,onShutdownRequest:()=>{a.handler()},sseHealth:()=>d.snapshot()}),p=await Bn({cwd:r,ipc:u,releasePid:o}),c=await U(r);c.isErr()&&(process.stderr.write(`ripplo: ${M(c.error)}
|
|
132
|
-
`),process.exit(1));let f=c.value,m=await Mr(()=>$e({config:e,cwd:r,lockfile:f}),{config:e,label:"initial sync"}),w=await I(r);w!=null&&Fe(w),qe({config:e,cwd:r,lockfile:f});let P=await Xn(e);J({cwd:r,paused:m.hooksPaused});let g=Me(r);g!=null&&s.info("watching branch %s in %s",g,r);let S=En({headers:{Authorization:`Bearer ${e.token}`},retry:Ye,retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`});vr({config:e,cwd:r}).catch(()=>{});let v=Fn({cwd:r,devSessionId:m.devSessionId,initialConcurrency:P});i.provide(v);let D=await qn({cwd:r,pool:v}),H=_n({claim:u.claim,config:e,cwd:r,initialId:m.devSessionId,pool:v,sseClient:S,sseHealth:d}),_r=Dr({config:e,devSessionId:m.devSessionId,sseClient:S,switcher:n}),$r=Hr({cwd:r,projectId:e.projectId,sseClient:S}),Fr=Ar({pool:v,sseClient:S}),Or=Tr({config:e,devSessionId:m.devSessionId,machinery:t,sseClient:S});Wr({config:e,devSessionId:m.devSessionId,machinery:t});let Nr=Mn({config:e,session:H}),jr=Qn();l.resolve(),Un(m.devSessionId);let Br=async()=>{Nr(),jr(),t.stop(),p.close(),H.stop(),_r(),$r(),Fr(),Or(),await v.close(),await n.stop(),await D.stop().catch(()=>{}),await Promise.race([y({config:e,document:Dn,variables:{cwd:e.cwd,devSessionId:H.getId(),projectId:e.projectId}}).catch(()=>{}),new Promise(Kr=>setTimeout(Kr,3e3))]),o()},k=()=>{Br().finally(()=>process.exit(0))};a.handler=k,process.on("SIGINT",k),process.on("SIGTERM",k),process.on("SIGHUP",k),process.on("SIGBREAK",k),await new Promise(()=>{})}function Hn(e){let r={handler:()=>{}},o=Sr({config:e,onChanged:()=>{r.handler()}}),n=Kn(),t=ur({config:e,pool:n.pool,executorIsLocal:()=>o.current()==="local"});return r.handler=t.notifyExecutorChanged,{executorSwitch:o,exploration:t,poolGate:n}}function qn({cwd:e,pool:r}){return pe({localDir:Rn.join(e,".ripplo",".local"),writePortFile:!0,onRrwebBatch:()=>{},onSpan:o=>{let n=o.attributes["ripplo.run"];n!=null&&r.routeSpan(n,o)}})}function Un(e){process.stdout.write(`${Re({devSessionId:e,version:oe()})}
|
|
133
|
-
`)}function Mn({config:e,session:r}){let o=async()=>{try{let t=await y({config:e,document:Wn,variables:{id:r.getId()}});t.heartbeatDevSession?.__typename==="DevSessionEndedError"&&(s.warn("dev session ended server-side (%s); re-registering",t.heartbeatDevSession.message),await r.reregister())}catch(t){s.warn("heartbeat failed: %s",t instanceof Error?t.message:String(t))}},n=setInterval(()=>{o()},Tn);return()=>{clearInterval(n)}}function _n({claim:e,config:r,cwd:o,initialId:n,pool:t,sseClient:i,sseHealth:a}){let l=n,d=null,u=0,p=0,c=g=>{P(g)},f=()=>{let g=Xe({claim:e,cwd:o,devSessionId:l,onSubscriptionDead:c,pool:t,sseClient:i,sseHealth:a}),S=Ze({cwd:o,devSessionId:l,onSubscriptionDead:c,sseClient:i});return()=>{g(),S()}},m=f(),w=async g=>{let S=Date.now();u=S-p>Ur*2?1:u+1,p=S,u>=Ln&&a.markUnhealthy(g),await $n(Math.min(1e3*2**(u-1),Ur));let v=await U(o);if(v.isErr()){s.error("re-register: compile failed: %s",M(v.error));return}let D=await Mr(()=>_e({config:r,cwd:o,lockfile:v.value}),{config:r,label:"re-register sync"});m(),l=D.devSessionId,m=f(),s.info("re-registered dev session as %s",l)},P=g=>(d!=null||(d=w(g).finally(()=>{d=null})),d);return{getId:()=>l,reregister:()=>P("dev session ended server-side"),stop:()=>{m()}}}function $n(e){return new Promise(r=>setTimeout(r,e))}function Fn({cwd:e,devSessionId:r,initialConcurrency:o}){return Rr({devSessionId:r,initialSize:o,spawn:Pr(Zn(),e),lockfileProvider:async()=>{let n=await R(e);if(n.isErr())return{unavailable:`daemon-load-failed:${n.error.kind}`};let t=await fe(e,n.value);return{lockfileJson:Z(ee,t)}}})}function On(e){try{return ge({cwd:e,onCompromised:Nn})}catch(r){throw r instanceof ye&&(process.stderr.write(`${Ee({cwd:r.cwd,pid:r.pid})}
|
|
134
|
-
`),process.exit(1)),r}}function Nn(){s.error("daemon lock compromised; shutting down"),process.stderr.write(`${be()}
|
|
135
|
-
`),process.exit(1)}function jn(){let e={handler:()=>{}};return{promise:new Promise(o=>{e.handler=o}),resolve:()=>{e.handler()}}}async function Bn({cwd:e,ipc:r,releasePid:o}){return(await ar({cwd:e,onConnection:r.handleConnection})).match(t=>t,t=>{process.stderr.write(`${ke(t)}
|
|
136
|
-
`),o(),process.exit(1)})}function Kn(){let e={provide:()=>{}};return{pool:new Promise(o=>{e.provide=o}),provide:o=>{e.provide(o)}}}function Gn(e){return h(e).match(r=>r,r=>{process.stderr.write(`${te(r)}
|
|
137
|
-
`),process.exit(1)})}function Mr(e,{config:r,label:o}){let n=r.ripploServerUrl.includes("localhost")||r.ripploServerUrl.includes("127.0.0.1");return bn(async()=>{try{return await e()}catch(t){zn({config:r,error:t});let i=t instanceof Error?t.message:String(t);throw Jn(i)?t:(s.error("%s failed: %s",o,i),new In(i))}},{factor:2,maxTimeout:n?2e3:1e4,minTimeout:n?100:1e3,retries:1/0,onFailedAttempt:({attemptNumber:t,error:i})=>{s.warn("%s attempt %d failed \u2014 retrying: %s",o,t,i.message)}})}function zn({config:e,error:r}){let o=V(r);o==="UNAUTHENTICATED"&&(process.stderr.write(`ripplo: ${Pe()}
|
|
138
|
-
`),process.exit(1)),o==="FORBIDDEN"&&(process.stderr.write(`ripplo: ${xe({projectId:e.projectId,serverUrl:e.ripploServerUrl})}
|
|
139
|
-
`),process.exit(1))}function Jn(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function Qn(){q({maxRuns:qr});let e=setInterval(()=>{q({maxRuns:qr})},Cn);return()=>{clearInterval(e)}}function Vn(){process.on("unhandledRejection",e=>{s.error({err:e},"unhandledRejection in watch; continuing")}),process.on("uncaughtException",e=>{s.error({err:e},"uncaughtException in watch; continuing")})}var Yn=4;async function Xn(e){try{let o=(await y({config:e,document:An,variables:void 0})).currentUser?.maxLocalConcurrentRuns;if(o!=null)return b(o),o}catch(r){s.warn({err:r},"failed to fetch local concurrency setting; using default")}return Yn}function Zn(){let e=process.argv[1];if(e==null)throw new Error("cli entry unavailable");return e}export{ra as runDaemon};
|