waygraph 0.15.20 → 0.15.22

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 CHANGED
@@ -1,1389 +1,115 @@
1
1
  # Waygraph
2
2
 
3
- A typed graph of reusable Blocks for driving a browser through E2E flows, in place of a
4
- flat pile of ad hoc helper functions.
5
-
6
- Not yet `1.0.0` - breaking changes between minor versions are expected. See
7
- [ROADMAP.md](./ROADMAP.md) for what's shipped, spec'd, and planned, and
8
- `openspec/specs/` for the current merged spec behind each capability
9
- (`openspec/changes/archive/` holds the historical planning artifacts once a change ships).
10
-
11
- This repo is the `waygraph` npm package itself. The full live **Sauce Demo** example
12
- (Page inventory hub, Effect Add/Remove, MemNav Open details, `waygraph auto`) ships
13
- in-tree at [`examples/saucedemo`](./examples/saucedemo). `waygraph try demo` copies
14
- [`templates/quickstart`](./templates/quickstart) (same Sauce Demo Blocks) into an OS
15
- temp dir.
16
-
17
- ## Docs (GitHub Pages)
18
-
19
- Browser docs (quick start, **demo / run**, **auto explore**, engine handout, consumer
20
- layout, deploy):
21
-
22
- - **Published:** https://deviate-dv8.github.io/waygraph/ (workflow auto-enables Pages via
23
- `enablement: true`; manual Settings only if org policy blocks it)
24
- - **Source:** [`docs/`](./docs/) - static HTML, no build step
25
- - **Local preview:** `npm run docs:preview` -> http://127.0.0.1:4173/
26
- - **Deploy:** push to `main` touching `docs/**` runs
27
- [`.github/workflows/pages.yml`](./.github/workflows/pages.yml) (`workflow_dispatch` also
28
- works)
29
- - **Demo / run contract:** [`docs/demo.html`](./docs/demo.html) - `list` / `.flow.ts` path
30
- / export / flags
31
- - **Auto explore:** [`docs/auto.html`](./docs/auto.html) - prefer `auto --cli` /
32
- `npm run auto:cli` (same menus as headed)
33
- - **In-repo example:** [`examples/saucedemo`](./examples/saucedemo) - full Sauce Demo
34
- project
35
- - **Convention showcase (Pages):** [`docs/saucedemo/`](./docs/saucedemo/) -
36
- https://deviate-dv8.github.io/waygraph/saucedemo/
37
- - **Helpers (consumer copy):** [`examples/saucedemo/docs/HELPERS.md`](./examples/saucedemo/docs/HELPERS.md)
38
-
39
- This README stays the in-repo API narrative; Pages is the same material for eyeballing and
40
- cross-mesh handoff.
41
-
42
- ## Install
43
-
44
- ```bash
45
- npm install waygraph @playwright/test
46
- ```
47
-
48
- `@playwright/test` is a peer dependency, not bundled - you bring your own version
49
- (`^1.40.0` or later) since it's also what drives the rest of your test suite. Requires
50
- Node 22+ (uses `URL`/`URLPattern` from `@types/node` for `Trait.url`'s type checking).
51
-
52
- ## Core concepts
53
-
54
- - **`Checkpoint<Tag>`** - a state identified solely by its string tag. Carries no data.
55
- - **`MemPage`** / **`MemKey<T>`** - typed shared memory across a run, keyed by object
56
- identity (`key<T>("debug-name")`), not by name string.
57
- - **`Block<In, Out>`** - one step: `act(page, input, mem)` does the work,
58
- `resolve()` decides the resulting Checkpoint (never touches the page or mem),
59
- `verify` (optional) confirms the page actually matches what `resolve()` claimed.
60
- - **`Trait`** - a named, independently-reportable check (`{ name, check(page, mem) }`).
61
- Built-in factories: `Trait.url` / `Trait.text` / `Trait.visible` (also importable as
62
- free functions `urlMatches` / `textEquals` / `visible`).
63
- - **`Flow`** - several Blocks chained with `Engine().defineFlow([start, ...blocks, end])`,
64
- run with `flow.run(mem)` (Engine launches its own browser) or `flow.run(context, mem)`
65
- (reuse an existing `@playwright/test` `context` fixture).
66
-
67
- ## Quick start
3
+ Write browser tests as a **graph of small, reusable steps** instead of one long script.
4
+ Built on Playwright. Every step says where it starts, where it ends, and how to confirm it
5
+ worked - so a whole app becomes something you (or an AI agent) can walk, check, and demo.
68
6
 
69
7
  ```typescript
70
- import { Engine, start, end, MemPage, key, checkpoint, Trait } from "waygraph";
71
- import type { Block, Checkpoint, Start } from "waygraph";
72
-
73
- type LoggedIn = Checkpoint<"LoggedIn">;
74
-
75
- const Username = key<string>("username");
76
-
77
- const Login: Block<Start, LoggedIn> = {
78
- name: "login",
8
+ // One Block = one action. It says: start on LoginPage, end on LoggedIn, and prove it.
9
+ export const SubmitLoginBlock = defineMethodBlock<LoginPage, LoggedIn>({
10
+ name: "submit-login",
79
11
  instruction: {
80
- async act(page, _input, mem) {
81
- await page.goto("https://example.com/login");
82
- await page.getByLabel("Username").fill(mem.get(Username));
83
- await page.getByRole("button", { name: "Sign in" }).click();
84
- },
12
+ async act(page) { await page.locator(LoginSel.button).click(); },
85
13
  resolve: () => checkpoint("LoggedIn"),
86
- verify: [Trait.url({ pathname: "/dashboard" })],
14
+ verify: [Trait.url({ pathname: "/inventory.html" })],
87
15
  },
88
- };
89
-
90
- const mem = new MemPage();
91
- mem.set(Username, "alice");
92
-
93
- const flow = new Engine().defineFlow([start, Login, end]);
94
- const result = await flow.run(mem); // Engine launches its own browser
95
- // result === { __state: "LoggedIn" }
96
- ```
97
-
98
- Inside an existing `@playwright/test` file, reuse its `context` fixture instead of having
99
- the Engine launch its own browser: `await flow.run(context, mem)`.
100
-
101
- See `tests/define-flow.spec.ts` here, and
102
- `examples/saucedemo/tests/checkout-flow.spec.ts` (a real multi-Block flow against live
103
- saucedemo.com), for this running for real. The lower-level `connect()`/`runGraph()` still
104
- exist and are what `defineFlow` builds on - reach for them directly only if you need a
105
- shape `defineFlow`'s array can't express yet.
106
-
107
- ## Engine features
108
-
109
- A Block's output type is the only contract the next Block can rely on. `resolve` is
110
- structurally incapable of touching the browser or shared memory. `verify` runs only after
111
- `resolve` has already decided (confirms or fails loud, never redirects).
112
-
113
- ### Routing and composition
114
-
115
- - **`branch()`** attaches routing to a Block - including back to itself (self-loops) -
116
- without ever touching that Block's own phases. A `maxSteps` safety cap keeps a routing
117
- bug from hanging a run forever.
118
- - **`withVerify(block, verify)`** decorates any existing Block with different
119
- confirmation, same `act`/`resolve`, same routing - without that Block needing to have
120
- been authored as a parameterized factory (`withVerify(LoginBlock, [])` is the "I only
121
- care that I navigated this far, no DOM check" case).
122
- - **`flow.withBlockVerify` / `flow.modBlockVerify`** patch one Block's verify from
123
- outside a finished `Flow` - addressed by the Block reference (preferred), its name, or
124
- its numeric position - without editing the flow's own file.
125
- - **`composeBlock(name, steps)`** chains several Blocks into one named unit, the same way
126
- `connect()` already does - useful for a multi-step form that's naturally "one feature"
127
- but still wants each step's own real `verify` independently overridable, not one giant
128
- Block with no per-step confirmation. `composedBlock.withStepVerify` / `modStepVerify`
129
- patch one step from outside, addressed the same three ways as `withBlockVerify`. A
130
- `composeBlock` result is a plain Block, so it drops straight into
131
- `defineFlow([start, ..., composed, ..., end])` like any other.
132
- - **`fastForwardComposeBlock(name, steps)`** is the same shape marked for wall-clock
133
- **fast-forward**: one opaque demo step that blitzes (no per-inner gate, no smooth cursor
134
- theater, Playwright `slowMo` off for that flow unless `WAYGRAPH_SLOWMO` is set) unless
135
- expanded. Put several FF units in one Flow to race past auth, then a heavy dashboard
136
- settle, then watch the interesting middle. `waygraph demo --ff-disabled` (alias
137
- `--no-ff`) expands every FFCompose into its inner Blocks so a broken step is visible as
138
- its own panel row; former FF inners keep blitz pacing so wall-clock stays comparable.
139
- `--ff-expand` is the older expand-only flag (same flatten).
140
-
141
- ### Cross-cutting Layouts (`defineLayout`)
142
-
143
- Real, direct request this responds to: persistent chrome (a sidebar, say) that's supposed
144
- to stay on screen across most of an app shouldn't need its own `Trait` copy-pasted into
145
- every single Checkpoint's `verify` - one missed copy and a regression silently ships. A
146
- **Layout** is a `verify` that's enforced automatically, by Checkpoint tag, wherever it
147
- applies - not once per Block:
148
-
149
- ```ts
150
- import { defineLayout, Engine } from "waygraph";
151
-
152
- const AppShellLayout = defineLayout({
153
- name: "AppShell",
154
- // string[] of exact Checkpoint tags, or a (tag) => boolean predicate for a
155
- // broader match (e.g. "every Checkpoint except the signed-out ones")
156
- appliesTo: ["AppHome", "Chats", "Notifications", "Settings"],
157
- verify: [Trait.visible(AppShellSel.sidebar)],
158
16
  });
159
17
 
160
- const engine = new Engine({ layouts: [AppShellLayout] });
161
- ```
162
-
163
- Every `Flow` this `Engine` defines - **and every intermediate Checkpoint inside it**, not
164
- just the final one - runs `AppShellLayout.verify` automatically whenever it resolves to a
165
- tag `appliesTo` matches, alongside that Block's own `verify`. `runGraph`/`Flow.run` also
166
- take `{ layouts }` directly (`RunGraphOptions.layouts`), for driving a Layout outside an
167
- `Engine`-owned Flow (e.g. `waygraph auto`'s own runtime pathfinding).
168
-
169
- Deliberately matched by Checkpoint tag, never by folder path - a Layout works identically
170
- whether a project uses the [Waygraph Map](#waygraph-map) convention or the older freeform
171
- folder style, since some real consumers of this package still use the latter.
172
-
173
- ### `map()` - a kind-checked, no-teleporting flow builder
174
-
175
- `Engine.defineFlow([start, ...blocks, end])` already typechecks that each Block's `Out`
176
- matches the next one's `In`. It does **not** stop an agent (or a careless human) from
177
- handing it a hand-rolled plain object that merely *looks* like a Block - TypeScript's
178
- structural typing can't tell a real `defineNavBlock(...)` output from a copy-pasted
179
- object literal with the right shape. That gap is exactly what broke down in real
180
- consumer projects: agents editing/hand-composing Blocks into ad hoc shapes, a "locks"
181
- convention tried and still bypassed. `map()` closes it with an actual runtime check, not
182
- just a convention:
183
-
184
- ```ts
185
- import { Engine } from "waygraph";
186
-
187
- const engine = new Engine();
188
- const flow = engine
189
- .map({ homeOrigin: "https://app.example.com" })
190
- .start()
191
- .gotoPage(NavHomeBlock) // must be defineNavBlock / defineMemNavBlock / definePageBlock
192
- .assert(AssertHelloBlock) // must be defineAssertBlock
193
- .gotoExternal(NavMailpitBlock) // same kind requirement, plus the INVERSE origin check
194
- .method(ClearCartBlock) // must be defineMethodBlock / defineActionBlock / defineEffectBlock
195
- .end(); // -> a real Flow<Out> - withBlockVerify/withTitle/withHighlightFixtures/etc. all still apply
18
+ // A Flow = Blocks in order.
19
+ export const loginFlow = engine.defineFlow([start, NavLoginBlock, FillUsernameBlock, FillPasswordBlock, SubmitLoginBlock, end]);
196
20
  ```
197
21
 
198
- Each step method is scoped to exactly the Block kind its name promises, checked against
199
- the same `__waygraphKind`/`__waygraphSalt` runtime markers `waygraph check`/`graph`/`map`
200
- already trust - a Block that didn't come from a real `define*Block` factory throws
201
- immediately, naming the step and the factory it should have used, instead of silently
202
- entering the chain. Give `homeOrigin` and `.gotoPage()`/`.gotoExternal()` also cross-check
203
- each Nav/Page Block's own static `url` against it (skipped, honestly, for click-based or
204
- mem-dependent nav - not statically checkable). The Checkpoint chain itself is still
205
- typechecked exactly like `defineFlow`'s own tuple overloads - there is no method on this
206
- builder that can skip from one Checkpoint to an unrelated one without a real, kind-correct
207
- Block in between, which is what "no teleporting" means here.
208
-
209
- `map()` is sugar over `defineFlow`, not a new execution engine - the result is a real
210
- `Flow`, so every existing Flow-level feature (Layouts, `withBlockVerify`, demo narration,
211
- `chainFlow`) works on it unchanged. `import { map } from "waygraph"` is also available
212
- standalone (`map(options)` ~= `new Engine(options).map(options)`) for a call site that
213
- doesn't otherwise need its own `Engine` instance. **Recommended for new projects** over
214
- hand-assembled `defineFlow([start, ...])` arrays - the freeform array form still works
215
- and isn't going away (real consumers on the older folder convention depend on it), but
216
- `map()` is the one that actually stops a broken/hacked Block from entering a flow
217
- unnoticed.
218
-
219
- ### Traits beyond the page
220
-
221
- A hand-written `Trait`'s `check(page, mem)` receives `mem` too, for the same-Checkpoint
222
- case: an action that doesn't navigate at all (clicking "+" to bump a cart item's quantity,
223
- say) has `In === Out`, which `defineBlock`/`defineFlow` already accept with no
224
- special-casing - `act()` updates `mem` alongside the real click, and a bespoke `verify`
225
- Trait confirms the page's own displayed value actually matches what `mem` now expects, not
226
- just that *some* number is showing. `resolve()` itself stays exactly as pure as ever - it
227
- never sees `mem`, only `verify` does.
228
-
229
- `Trait.url` takes a structured `URLPatternInit` (`{ pathname, hostname, search, hash, ... }`,
230
- the same shape the standard `URLPattern` Web API takes), not a hand-written regex -
231
- whichever components you leave out default to "match anything," so
232
- `Trait.url({ pathname: "/inventory.html" })` already ignores whatever query params a
233
- hybrid SPA tacks on, with no separate flag needed for that.
234
-
235
- ### `precondition` - confirming the page is *still* there
236
-
237
- `verify` only ever confirms what a Block itself just did - nothing previously checked
238
- whether the page was still there by the time the next Block's `act()` starts. A
239
- `precondition` (same `Trait[]` / `(input) => Trait[]` shape as `verify`, checked
240
- automatically by `connect()`/`runGraph` right before `act()` runs, never called directly)
241
- closes that gap: a session timeout, a redirect, an interstitial popup - anything that
242
- changes the page in the moment between one Block finishing and the next one starting -
243
- fails loud with a clear "trait X failed before Y," instead of a confusing error deep
244
- inside `act()` trying to click something that's no longer there.
245
-
246
- ### `requires` and `preflight()`
247
-
248
- A Block's `requires: MemKey[]` gets checked by `preflight()` (built into `runGraph`)
249
- before a tab even opens - a missing credential fails in milliseconds, not after several
250
- real browser actions already ran.
251
-
252
- ### memStub - fake values for `requires`, opt-in per Flow
253
-
254
- Hand-supplying `--data '{...}'` every run gets old fast for a `requires` key that's
255
- genuinely arbitrary (a username, an email, a name) rather than something the run actually
256
- depends on. `registerMemStub(key, fake)` registers a generator for one `MemKey` (bring your
257
- own - Faker.js or anything else; waygraph takes no dependency on it); `withMemStub(flow)`
258
- opts that Flow into filling any `requires` key with no `--data` coverage from that registry
259
- instead of failing preflight. A key with no registration still fails exactly as before -
260
- this narrows the case that needs real input, it doesn't remove the guard:
261
-
262
- ```typescript
263
- import { registerMemStub, withMemStub } from "waygraph";
264
- import { faker } from "@faker-js/faker";
265
-
266
- registerMemStub(LoginCreds.key, () => ({
267
- username: faker.internet.userName(),
268
- password: faker.internet.password(),
269
- }));
22
+ ## Try it in 60 seconds
270
23
 
271
- export const demoLoginFlow = withMemStub(loginFlow);
272
- ```
273
24
  ```bash
274
- waygraph run demoLoginFlow # zero --data - fills from the registry
275
- waygraph run loginFlow --mem-stub # same effect without a Flow-level wrapper -
276
- # --mem-stub / WAYGRAPH_MEM_STUB=1 force it
277
- # for one CLI call, opt-in or not
25
+ npx waygraph try demo # watch a full Sauce Demo checkout, step by step (nothing written to your folder)
278
26
  ```
279
- `--data` always wins for a key it actually covers - memStub only fills what's left over.
280
- Registered by `MemKey` *identity*, not by name (matching `MemPage`'s own store): two keys
281
- sharing a debug name never cross-contaminate. For a bare library `flow.run(mem)` call
282
- outside the CLI, call `seedMemStub(mem, flow)` yourself before `run()` when
283
- `flow.memStub` is true - `run()` never reads Flow flags itself, same as
284
- `resetSession`/`title`/every other `with*` wrapper.
285
-
286
- ### Engine config and pluggable browsers
287
-
288
- `new Engine({ headless, browserName, slowMo })` configures a browser the Engine launches
289
- and owns itself: `flow.run(mem)` (no context) uses it, and
290
- `flow.run(mem, { ...overrides })` overrides it per call - so one module-level `Flow`,
291
- imported by many specs, doesn't force every caller into the same settings.
292
- `flow.run(context, mem)` still works exactly as before and ignores all of this, since that
293
- context is already launched.
294
-
295
- `new Engine({ browsers: { chromium, firefox, webkit } })` overrides which `BrowserType`
296
- actually launches for a `mem`-only run, per browser name - waygraph is deliberately "just
297
- an opinionated Playwright," so a stealth-patched or otherwise customized launcher (e.g.
298
- `playwright-extra` plus a stealth plugin) drops in unmodified, since those already expose
299
- the same `.launch()` shape as Playwright's own `chromium`/`firefox`/`webkit`.
300
-
301
- ### Driving an existing page / tabs
302
-
303
- `spawnTab(entry, page, mem)` drives a genuinely separate second tab through its own
304
- Block/Flow, in the same browser context an existing `page` already belongs to - the
305
- pattern `observe()` could already reach for (it's the only phase allowed to touch
306
- `page.context()`), now a named, discoverable, tested primitive.
307
-
308
- `flow.run(context, mem, options)` also accepts a trailing optional options object -
309
- additively, so `flow.run(context, mem)` still behaves byte-for-byte as before:
310
- `options.page` drives that already-open page instead of opening a fresh tab (the run
311
- won't close a page you handed it unless you say so), and `options.closeOnFinish: false`
312
- leaves the run's page open and returns `{ result, page }` so the caller can keep driving
313
- it. See [Recipes](#recipes) for the surviving-tab and popup-capture patterns.
314
-
315
- ### NavBlock / ActionPage / waygraph check
316
-
317
- `defineNavBlock({ name, checkpoint, url })` or
318
- `defineNavClickBlock({ name, checkpoint, click })` builds a Block whose only possible
319
- action is navigating. Prefer `defineNavClickBlock` for click-nav in app code;
320
- `defineNavBlock` for `url` / `goto` deep links. Both accept a plain string or
321
- `(mem) => string` / `(mem) => selector`. Generated `act()` is always exactly
322
- `page.goto(url)` or `page.locator(click).click()`. For screen hubs that also register
323
- methods, prefer `definePageBlock` (see [Block helpers](#block-helpers-page-method-sel)
324
- below).
325
-
326
- A regular `defineBlock` / `defineMethodBlock`'s `act()` receives `page` typed as
327
- `ActionPage` - `goto`/`reload`/`goBack`/`goForward` are `@deprecated` there (editor
328
- strike-through pointing at Nav/Page helpers). This is a soft, TypeScript-only signal:
329
- nothing is blocked, nothing fails to build. `waygraph check [project]` is the
330
- complementary whole-project sweep for contexts with no editor watching (CI, generated
331
- code, an autonomous agent authoring Blocks) - it warns, never fails the process.
332
-
333
- **`waygraph typecheck [project]`** runs `tsc --noEmit` then the same **bad-practice** scan
334
- (wildcard `Checkpoint<string>`, assert blocks missing type args, multi-`.fill()` Methods,
335
- fill+click in one Method, empty `verify` on a transition Block or `defineAssertBlock`).
336
- Practices warn only unless `tsc` fails; use `--no-practices` to skip the scan. Opt out per
337
- file: `// waygraph-ignore-practices` or `// waygraph-ignore: multi-input, combined-action,
338
- empty-verify`. Print full agent guidance: `waygraph --skill-convention`.
339
-
340
- **Empty verify is the one that matters most for codegen'd Blocks.** A framework can enforce
341
- that a check *exists* and stays structurally honest (typed, wired, right file) - it cannot
342
- author the semantic content of that check, since only someone who knows what "success" means
343
- for this specific app can write it. That's a correct place to draw the line, but it shifts
344
- all the risk onto whether anything catches a Block left with a placeholder `verify: []` by
345
- the time it ships - which would otherwise pass every static check, the orphan scan, and
346
- `tsc`, and run green in CI forever, because an empty array isn't a wrong check, it's the
347
- *absence* of one. `waygraph check`/`typecheck` now flag exactly that: a `defineMethodBlock`/
348
- `defineEffectBlock` whose `In`/`Out` Checkpoints actually differ (a real transition, not a
349
- self-loop like `fill-username`) with no `verify` key or a literal `verify: []`, and the same
350
- for `defineAssertBlock` (whose entire job is checking). Silence it deliberately, the same as
351
- any other practice warning, with `// waygraph-ignore: empty-verify` - e.g. when a downstream
352
- `defineAssertBlock` right after it in the `.flow.ts` is what actually confirms the transition
353
- (see `templates/scaffold`'s own `open-message.method.block.ts`, confirmed by
354
- `AssertEmailContentBlock` right after it, not by its own `verify`).
355
-
356
- ### Demo narration
357
-
358
- Automation rings are gray; authored stubs/slides can use
359
- `tone: "info" | "warning" | "danger" | "success"` (iconified captions), plus
360
- `size: "sm" | "md" | "lg"` and `weight: "normal" | "bold"`. Flow episode defaults:
361
- `withHighlightStyle(flow, { size, weight, tone? })` (slot/fixture wins). Episode pacing:
362
- `withDemoPace(flow, "fast" | "slow" | "normal" | "blitz" | number)` or
363
- `withBlockPace(block, ...)` (`number <= 20` = scale vs normal, e.g. `0.5` / `2`; `> 20` =
364
- absolute ms, e.g. `4500`). FFCompose stays blitz. Living objectives:
365
- `docs/proposals/OBJECTIVES.md`.
366
-
367
- ### Graph traversal
368
-
369
- `waygraph traverse` walks the Block graph. `--parallel N` (default `--session clone`)
370
- bootstraps one context, forks N workers with `storageState` + mem snapshot, partitions
371
- edges by hash, and claims via in-process edge leases (audit trail under
372
- `.waygraph-traverse/`). `--session inherit` is refused when `parallel > 1`. It writes
373
- `.waygraph-traverse/coverage.json` and prints `[Coverage edges=H/T ratio=R%...]`;
374
- `--min-edge-coverage 80%` fails the suite with exit 2 when the ratio is below the gate
375
- (even if every worker leaf-PASSed). `--coverage-out PATH` / `--no-coverage-report` adjust
376
- the JSON. See `docs/proposals/traverse-ffcompose-rfc.md`.
377
27
 
378
- ### Not yet implemented
379
-
380
- Tracked on the project board / roadmap, not in this package today:
381
-
382
- - Interstitials/Watchers - background overlay handling (cookie banners, popups).
383
- - Split `requires` (externally-supplied vs producedBy) recovery hints.
384
- - Federated multi-package pool of waygraphs.
385
-
386
- ## Block helpers (Page, Method, Sel)
387
-
388
- Runtime is still one type: `Block`. Helpers are TypeScript salt.
389
-
390
- | Helper | Role | Typical file |
391
- |--------|------|----------------|
392
- | `definePageBlock` | Screen hub (checkpoint + `verify` + registered methods) | `*.page.block.ts` |
393
- | `defineMethodBlock` | One-shot non-nav step, exactly one action (submit, upload, logout) | `methods/*.method.block.ts` |
394
- | `defineAssertBlock` | Self-loop-only assertion (no state change) - `verify` only | `methods/*.method.block.ts` |
395
- | `defineEffectBlock` | Instance mutate + `instanceOptions` auto menu | `methods/*.effect.block.ts` |
396
- | `defineNavBlock` / `defineNavClickBlock` | `goto` / click-nav | `nav-*.block.ts` |
397
- | `defineMemNavBlock` | Nav + per-row `instanceOptions` | `nav-*.block.ts` |
398
- | `defineActionBlock` | Deprecated alias of `defineMethodBlock` | - |
399
-
400
- **Page hub:** one Checkpoint = this screen. Methods hang off the page for readability /
401
- auto grouping. Arrival-only hubs omit `url`/`click` (previous Block already landed here).
402
- Deep-link hubs pass `url` or `click` like a Nav.
403
-
404
- **One distinct action per Block - hard rule.** A Method that fills form fields *and*
405
- submits, or that drives several steps inside one `act()`, is wrong even if it "works" -
406
- split it into atomic Blocks (a login form is `fill-username` + `fill-password` +
407
- `submit-login`, never one Block doing all three; see `examples/saucedemo`'s own
408
- `saucedemo-web/methods/` for the real split). A Block that only asserts something on the
409
- current page, with no state change, is `defineAssertBlock({ name, checkpoint, verify,
410
- waitForHeading?, requires? })` - self-loop and `resolve` are generated for you, so there's no
411
- hand-written `act`/`resolve` to accidentally make do two things. It also accepts
412
- `stubBefore`/`stubAfter`/`stubOnError`/`slides`, the same narration fields every other
413
- Block helper takes, so converting a hand-written assertion Method loses no demo/highlight
414
- fixture data. `requires` (declare it whenever a mem-aware Trait reads a mem key the caller
415
- must supply externally - see the mail example below) lets preflight catch a missing input
416
- before the flow ever runs, the same as every other Block helper:
417
-
418
- ```typescript
419
- export const AssertInventoryHeaderBlock = defineAssertBlock({
420
- name: "assert-inventory-header",
421
- checkpoint: "LoggedIn",
422
- waitForHeading: "Products",
423
- verify: [Trait.visible(InventorySel.list)],
424
- });
425
- ```
426
-
427
- `waygraph check` warns when a `verify` array inlines a literal selector string
428
- (`Trait.visible("#some-id")`) instead of referencing a `*Sel` object - the exact pattern
429
- `defineAssertBlock` exists to make easy to avoid.
430
-
431
- **Give `defineAssertBlock` an explicit type argument when it sits mid-chain.** Without one,
432
- `Out` defaults to wildcard `Checkpoint<string>` on both sides - harmless when the assert is
433
- the last real Block before `end` (nothing downstream needs it narrower), but a `defineFlow`
434
- array's tuple typing breaks once a wildcard Block is sandwiched between two
435
- specifically-typed ones. Write `defineAssertBlock<LoggedIn>({ ..., checkpoint: "LoggedIn",
436
- ... })` any time the assert has a real Block after it, not just before.
437
-
438
- **An assert Block can check the *result* of an action, not just static page state.** Since
439
- `Trait.check(page, mem)` receives mem as well as the page, an assert placed right after a
440
- Method/Effect can confirm what that specific action actually did - not a duplicate of that
441
- Block's own inline `verify`, a genuinely separate, nameable QA checkpoint:
442
-
443
- ```typescript
444
- const removeButtonVisibleForSelectedItem: Trait = {
445
- name: "remove-button-visible-for-selected-item",
446
- async check(page, mem) {
447
- const { id } = mem.get(SelectedItem.key); // what add-item just acted on
448
- return page.locator(RemoveBtnSel(id)).isVisible();
449
- },
450
- };
451
-
452
- export const AssertItemAddedBlock = defineAssertBlock<ItemInCart>({
453
- name: "assert-item-added",
454
- checkpoint: "ItemInCart",
455
- verify: [removeButtonVisibleForSelectedItem, Trait.text(CartCountSel, "1")],
456
- });
457
-
458
- // wired right after the action it checks:
459
- engine.defineFlow([start, NavHomeBlock, AddItemBlock, AssertItemAddedBlock, ClearCartBlock, end])
460
- ```
461
-
462
- Live reference: `templates/scaffold/src/map/(app_base)/home/_methods/assert-item-added.method.block.ts`,
463
- wired into `shop.flow.ts`.
464
-
465
- **An assert Block also names a feature *state*, not just a result or static content.** A
466
- submit button greyed out until required fields are filled, a "Save" button re-enabling
467
- after a successful edit, a field-level validation error appearing under one specific input
468
- - these are conditions the UI is *in*, worth a nameable Checkpoint of their own the same way
469
- `AssertItemAddedBlock` names "did add-item work." There's no built-in `Trait.disabled` -
470
- write the state check as a custom Trait against the real DOM condition (`isDisabled()`, a
471
- class, an `aria-disabled` attribute - whatever the app actually uses), the same pattern as
472
- `removeButtonVisibleForSelectedItem` above:
473
-
474
- ```typescript
475
- const submitGatedUntilFieldsComplete: Trait = {
476
- name: "submit-gated-until-fields-complete",
477
- async check(page) {
478
- return page.locator(CheckoutSel.submitButton).isDisabled();
479
- },
480
- };
481
-
482
- export const AssertSubmitGatedBlock = defineAssertBlock<CheckoutInfoPage>({
483
- name: "assert-submit-gated",
484
- checkpoint: "CheckoutInfoPage",
485
- verify: [submitGatedUntilFieldsComplete],
486
- });
487
-
488
- // wired right after the fields that gate it, before the ones that clear the gate:
489
- engine.defineFlow([start, NavCheckoutInfoBlock, AssertSubmitGatedBlock, FillFirstNameBlock, ...])
490
- ```
491
-
492
- Same rule as any other assert Block: give it an explicit type argument when it sits
493
- mid-chain (see above), and keep the selector in a `*Sel` object, never inlined in the Trait.
494
-
495
- **`methods/` folder:** on-page work lives next to the route, not free-floating.
496
-
497
- **`*Sel`:** DOM selectors only (static strings + `(id) => ...` for item-no-1 style). Mem
498
- keys store values (which item / upload queue), not selectors. `instanceOptions` scrapes the
499
- live DOM into menu rows and `mem.set`s on pick; predefined methods seed mem from the flow
500
- instead.
501
-
502
- ```typescript
503
- import { definePageBlock, Trait } from "waygraph";
504
-
505
- export const InventorySel = {
506
- list: ".inventory_list",
507
- addBtn: (id: string) => `[data-test="add-to-cart-${id}"]`,
508
- };
509
-
510
- export const InventoryPage = definePageBlock({
511
- name: "page-inventory",
512
- checkpoint: "LoggedIn",
513
- verify: [
514
- Trait.url({ pathname: "/inventory.html" }),
515
- Trait.visible(InventorySel.list),
516
- ],
517
- methods: {
518
- addToCart: () => AddToCartBlock,
519
- removeFromCart: () => RemoveFromCartBlock,
520
- addAllToCart: () => AddAllToCartBlock,
521
- removeAllFromCart: () => RemoveAllFromCartBlock,
522
- },
523
- });
524
- ```
525
-
526
- Live reference: `examples/saucedemo/src/blocks/saucedemo-web/inventory/`
527
- (`inventory.page.block.ts` + `methods/` + `InventorySel`). Bulk `add-all-to-cart` /
528
- `remove-all-from-cart` are one menu row each (`from: "*"` - works after leave/return).
529
-
530
- ## Mail adapters (cross-origin, browser-driven)
531
-
532
- For flows driven by an email (signup confirmation, password reset, a magic link), the
533
- convention is **not** a REST/HTTP client to the mail catcher - it's more Blocks, pointed at
534
- the catcher's own web UI (MailHog, MailDev, Mailpit all ship one) as a real, separate,
535
- cross-origin page. This needs zero new engine surface: a `NavBlock` navigates there like any
536
- other page, `MethodBlock`s read the DOM with ordinary `page.locator`/`page.frameLocator`
537
- calls, and a final `NavBlock` carries the extracted link back into the app under test.
538
- Convergent, real-world evidence for this exact shape: independently, more than one real
539
- consumer project settled on it rather than a REST client.
540
-
541
- **Keep it in its own `*-external/<tool>/` folder, never mixed into your app's own Blocks** -
542
- it's a different origin, driving a different site:
543
-
544
- ```typescript
545
- // demo-external/mailpit/nav-mailpit-inbox.block.ts
546
- export const NavMailpitInboxBlock = defineNavBlock<MailpitInbox>({
547
- name: "nav-mailpit-inbox",
548
- checkpoint: "MailpitInbox",
549
- url: () => process.env.WAYGRAPH_MAIL_URL ?? "http://127.0.0.1:8025",
550
- verify: [Trait.url({ pathname: "/" })],
551
- });
552
-
553
- // demo-external/mailpit/methods/open-message.method.block.ts
554
- export const OpenMessageBlock = defineMethodBlock<MailpitInbox, MailpitMessageOpen>({
555
- name: "open-message",
556
- requires: [ExpectedRecipient.key], // externally supplied - avoids picking the wrong inbox row
557
- instruction: {
558
- async act(page, _in, mem) {
559
- const { email } = mem.get(ExpectedRecipient.key);
560
- await page.locator(MailpitSel.messageRow, { hasText: email }).first().click();
561
- await page.waitForURL(/\/view\//);
562
- },
563
- resolve: () => checkpoint("MailpitMessageOpen"),
564
- },
565
- });
566
-
567
- // demo-external/mailpit/methods/extract-email-link.method.block.ts
568
- // Named for what it does, not for one scenario - see "reusable across
569
- // scenarios" below for why.
570
- export const ExtractEmailLinkBlock = defineMethodBlock<MailpitMessageOpen, MailpitMessageOpen>({
571
- name: "extract-email-link",
572
- requires: [ExpectedLinkPattern], // which link in the body to follow - externally supplied
573
- instruction: {
574
- async act(page, _in, mem) {
575
- const pattern = mem.get(ExpectedLinkPattern);
576
- const link = page.frameLocator(MailpitSel.previewIframe).locator(`a[href*="${pattern}"]`).first();
577
- const href = await link.getAttribute("href");
578
- if (!href) throw new Error(`no link matching "${pattern}" found`);
579
- mem.set(EmailLink({ url: href }));
580
- },
581
- resolve: () => checkpoint("MailpitMessageOpen"),
582
- },
583
- });
584
-
585
- // demo-web/nav-verification-link.block.ts - back into the app, no `requires` (see below)
586
- export const NavVerificationLinkBlock = defineNavBlock<HomeVerified>({
587
- name: "nav-verification-link",
588
- checkpoint: "HomeVerified",
589
- url: (mem) => mem.get(EmailLink.key).url,
590
- verify: [Trait.visible(DemoSel.verifiedBanner)],
591
- });
592
- ```
593
-
594
- Four atomic Blocks, each doing exactly one thing - `open-message` and `extract-email-link`
595
- stay separate Methods for the same reason `fill-username`/`submit-login` do in the Sauce
596
- Demo example: reading the link and navigating to it are two distinct actions, so they are
597
- two distinct Blocks (`nav-verification-link` does the actual navigation).
598
-
599
- Note `nav-verification-link` deliberately does **not** declare `requires: [EmailLink.key]` -
600
- `requires` means "the caller must seed this externally before the flow starts" (preflight
601
- checks a whole chain's requires up front), and this key is instead produced by
602
- `extract-email-link` earlier in the very same chain. Declaring it as a requirement would make
603
- preflight reject the run before it ever gets a chance to produce it - `requires` is only for
604
- keys a caller truly must supply from outside the chain (like `ExpectedRecipient` above).
605
-
606
- Live reference, proven end to end against a real, throwaway Mailpit container:
607
- `templates/scaffold/src/map/(external)/mailpit/` + `src/flows/mail-verify.flow.ts` +
608
- `tests/mail-verify.spec.ts`.
609
-
610
- ### Reusable across scenarios: mem-driven, not one Block per email
611
-
612
- The natural instinct once you have a signup-verification flow is to want a matching set of
613
- Blocks for password reset, then another for a magic link, and so on - N scenarios, N Block
614
- sets. That's the wrong axis to scale on. `open-message`, `extract-email-link`, and the two
615
- assert Blocks below are already scenario-agnostic: **only mem varies per run, never the
616
- Blocks**:
617
-
618
- | Mem key | Answers |
619
- |---|---|
620
- | `ExpectedRecipient` | Which inbox row to open |
621
- | `ExpectedLinkPattern` | Which link in the body to follow (a real email often has more than one - "report abuse" and the real link both present) |
622
- | `ExpectedEmailContent` | What the body is supposed to say |
623
-
624
- The same four Blocks (`assert-email-received`, `open-message`, `assert-email-content`,
625
- `extract-email-link`) run a signup-verification check and a password-reset check identically
626
- - just with different mem, in `templates/scaffold/tests/mail-verify.spec.ts`:
627
-
628
- ```typescript
629
- mem.set(ExpectedRecipient({ email: "demo-user@example.com" }));
630
- mem.set(ExpectedLinkPattern, "verified=1");
631
- mem.set(ExpectedEmailContent, "Please confirm your email address...");
632
- await mailVerifyFlow.run(context, mem); // signup verification
633
-
634
- mem.set(ExpectedRecipient({ email: "password-reset-user@example.com" }));
635
- mem.set(ExpectedLinkPattern, "verified=1"); // picks the real link, not the "report abuse" decoy also in the body
636
- mem.set(ExpectedEmailContent, "We received a request to reset your password.");
637
- await mailVerifyFlow.run(context, mem); // same flow, same Blocks, different email entirely
638
- ```
639
-
640
- Naming matters here: a Block named `extract-verification-link` would wrongly imply it only
641
- ever handles verification emails - once a Block's behavior is mem-driven, its name should
642
- describe the mechanism (`extract-email-link`), not one scenario that happens to use it.
643
-
644
- A **mail-provider page hub** ties it together, the same `definePageBlock` pattern used
645
- everywhere else - one page, several reusable methods, each pulling its specifics from mem:
646
-
647
- ```typescript
648
- export const MailpitInboxPageBlock = definePageBlock<MailpitInbox>({
649
- name: "page-mailpit-inbox",
650
- checkpoint: "MailpitInbox",
651
- verify: [Trait.url({ pathname: "/" })],
652
- methods: {
653
- assertEmailReceived: () => AssertEmailReceivedBlock,
654
- openMessage: () => OpenMessageBlock,
655
- assertEmailContent: () => AssertEmailContentBlock,
656
- extractEmailLink: () => ExtractEmailLinkBlock,
657
- },
658
- });
659
- ```
660
-
661
- ### QA-rich: does the email exist, and does it say the right thing
662
-
663
- Two more assert Blocks slot into the same chain, both mem-driven, both proven to fail loud
664
- (not silently pass) on a real negative case - no email arrived, and an email arrived with
665
- the wrong copy:
666
-
667
- ```typescript
668
- // "Did the email even arrive" - doesn't open/consume it, safe to check before deciding to.
669
- // A mem-aware Trait: the selector depends on the expected recipient, so it
670
- // can't be a static Trait.visible(...) string - check(page, mem) already gets mem.
671
- const emailReceived: Trait = {
672
- name: "email-received",
673
- async check(page, mem) {
674
- const { email } = mem.get(ExpectedRecipient.key);
675
- try {
676
- await page.locator(MailpitSel.messageRow, { hasText: email }).first().waitFor({
677
- state: "visible",
678
- timeout: 10_000,
679
- });
680
- return true;
681
- } catch {
682
- return false;
683
- }
684
- },
685
- };
686
- export const AssertEmailReceivedBlock = defineAssertBlock<MailpitInbox>({
687
- name: "assert-email-received",
688
- checkpoint: "MailpitInbox",
689
- requires: [ExpectedRecipient.key],
690
- verify: [emailReceived],
691
- });
692
-
693
- // "Does the email say what it's supposed to" - reads the body content, not
694
- // just whether a link exists. The expected text comes from mem too (same
695
- // reuse reasoning as above) via another bespoke mem-aware Trait, since
696
- // Trait.frameContains's own factory bakes its expected string in at
697
- // Block-definition time, not runtime.
698
- const bodyContainsExpectedText: Trait = {
699
- name: "body-contains-expected-text",
700
- async check(page, mem) {
701
- const expected = mem.get(ExpectedEmailContent);
702
- const text = await page.frameLocator(MailpitSel.previewIframe).locator("body").textContent();
703
- return (text ?? "").includes(expected);
704
- },
705
- };
706
- export const AssertEmailContentBlock = defineAssertBlock<MailpitMessageOpen>({
707
- name: "assert-email-content",
708
- checkpoint: "MailpitMessageOpen",
709
- requires: [ExpectedEmailContent],
710
- verify: [bodyContainsExpectedText],
711
- });
712
- ```
713
-
714
- `Trait.frameVisible(frameSelector, innerSelector)` / `Trait.frameText(frameSelector,
715
- innerSelector, expected)` (exact match) / `Trait.frameContains(frameSelector, innerSelector,
716
- expected)` (substring match, for a *fixed* known expected string) mirror
717
- `Trait.visible`/`Trait.text` exactly, scoped to a frame - reusable for any iframe content,
718
- not just mail; reach for a bespoke mem-aware Trait instead when the expected value itself
719
- needs to vary per run, as both examples above do. Wired into the chain right where they
720
- belong:
721
-
722
- ```typescript
723
- engine.defineFlow([
724
- start, NavMailpitInboxBlock, AssertEmailReceivedBlock, OpenMessageBlock,
725
- AssertEmailContentBlock, ExtractEmailLinkBlock, NavVerificationLinkBlock, end,
726
- ])
727
- ```
728
-
729
- ### Where this shows up in `waygraph auto`
730
-
731
- A `NavBlock` always has wildcard `In` (`from: "*"` in the static graph), so it's reasonable to
732
- wonder whether `nav-mailpit-inbox` clutters the live picker on every single screen. It
733
- doesn't - `waygraph auto`'s menu builder already special-cases exactly this
734
- (`src/auto-explore.ts`, `buildExploreMenu`): a URL-based Nav is excluded from the interactive
735
- menu once you're on a known screen, offered only as a "Start here" bootstrap option. The
736
- static graph still keeps the `from: "*"` edge for `waygraph graph`/`findBlockPath`/`traverse`,
737
- so `waygraph auto --blocks "<AppCheckpoint> MailpitInbox"` can still route there deliberately -
738
- it's just never suggested unprompted. The tested, recommended way to actually use this is an
739
- authored flow/chain (`someAppFlow then mailVerifyFlow`), exactly like `mailVerifyFlow` itself.
740
-
741
- ## Waygraph Pilot
742
-
743
- Bootstraps a real, persistent, inspectable browser session for an **agent** to discover and
744
- drive toward a natural-language goal it plans itself - not a tool that resolves one ask to one
745
- Block internally. A real request is a multi-step task ("log in and buy the backpack for me",
746
- "make a signature draft request") that needs an agent reasoning over a sequence of Blocks, not
747
- a single best-matching edge. Comparable in shape to a browser-use-style agent, but the action
748
- space is constrained to this project's own pre-verified Blocks (each with a real resolve/verify
749
- already checked) instead of freeform DOM/pixel guessing - narrower, but far more accurate and
750
- deterministic.
751
-
752
- ### auto vs browser vs pilot
753
-
754
- | Layer | Command | What it is |
755
- |-------|---------|------------|
756
- | **auto** | `waygraph auto` | Interactive explore (picker / `--cli` menu). **Not** a persistent agent browser. |
757
- | **browser** | `waygraph browser start` | New persistent Playwright session — **headful by default**, **about:blank by default**. |
758
- | **pilot** | `waygraph pilot start` | Bootstrap only: `browser start` + whole-project `graph` + starting `snapshot` in one JSON payload. Does not plan or act. |
759
-
760
- Session control (`send`, `status`, `highlight`, `dom`, …) works on **`auto`**, **`browser`**, and
761
- **`pilot`** — same socket, same session id. Prefer the `browser`/`pilot` prefix when driving a
762
- detached session; `auto` remains for the interactive picker and legacy `--cli --detach`.
763
-
764
- **Session lifecycle is explicit** — list what's live before opening another:
765
-
766
- ```bash
767
- waygraph browser # show browser subcommands
768
- waygraph browser sessions [--json] # list live sessions; --json for agents
769
- waygraph browser start # always opens a new session
770
- waygraph browser stop <sessionId> # shut one down
771
- waygraph browser stop --all # shut every session for this project
772
- waygraph browser attach <sessionId> # terminal picker on an existing session
773
- waygraph pilot attach <sessionId> # graph + snapshot, no new browser
774
- ```
775
-
776
- ```bash
777
- waygraph pilot start
778
- # {"sessionId":"bb65d74c","socketPath":"...","headless":false,"graph":{...},"snapshot":{...}}
779
- ```
780
-
781
- `pilot start` is one round trip for agents that need the whole graph immediately. For browser-only
782
- work (no graph payload), use `browser start`. `auto --cli --detach` still works but is the older
783
- explore entry point — prefer `browser start` for agent-driven sessions.
784
-
785
- From a live session, drive one pick at a time:
28
+ ## Start a project
786
29
 
787
30
  ```bash
788
- waygraph browser status <sessionId> # read the current menu (no side effects)
789
- waygraph browser send <sessionId> "<pick>" # run one pick, get the resulting menu back
790
- waygraph browser dom <sessionId> # inspect the live DOM/ARIA tree
791
- waygraph browser trace <sessionId> # read the Checkpoint/Block history so far
792
- waygraph browser reach <sessionId> <Checkpoint> # run a whole multi-step route in one call
793
- waygraph browser resync <sessionId> # force here to re-detect from the real page
794
- ```
795
-
796
- (`auto …` and `pilot …` accept the same subcommands with the same `<sessionId>`.)
797
-
798
- Worked example (run for real against `examples/saucedemo`, no new execution code involved): an
799
- agent gets a plain request - "log me in and buy the backpack" - reads the graph and the starting
800
- `status`, reasons out login -> add-to-cart -> cart -> checkout info -> submit -> finish as the
801
- route to `OrderComplete`, then drives it by repeatedly reading each `status`/`send` response and
802
- picking the next index itself. The browser stays open the whole time; the user can watch it, or
803
- check the final tab afterward.
804
-
805
- **`auto reach <sessionId> <Checkpoint>`** runs a whole route in one call instead of one
806
- `send` per step - real, reported pain for any non-trivial task on a rich graph ("the entire
807
- prompts of the day" for one manual walkthrough). It path-finds via the same BFS `auto --blocks
808
- <From> <To>` already uses, then runs each step directly against the session's own live
809
- page/mem, verifying every step actually lands where its own graph edge promised (not just that
810
- it ran without throwing - a Block can legitimately resolve elsewhere, e.g. a login submission
811
- staying put after bad auth). **Real, stated limitation, not silently papered over:** for a
812
- target only reachable by crossing a wildcard (`from: "*"`) edge whose real DOM precondition
813
- depends on same-Checkpoint setup (e.g. filling form fields before a submit), neither `reach`
814
- nor the already-shipped `auto --blocks` can safely route there automatically - both fail loud
815
- within a bounded time (a real Playwright click/wait timeout) rather than silently guessing
816
- wrong or hanging. Full design history - three rejected approaches, a real correctness bug this
817
- change's own tests caught, and this limitation confirmed by direct reproduction - is in
818
- `openspec/changes/waygraph-pilot/tasks.md`'s own M5 section.
819
-
820
- **`auto resync <sessionId>`** - `here` is only ever updated by an action the session itself
821
- ran (`send`/`reach` set it from a Block's own resolved Checkpoint; the raw `click`/`type`/
822
- `goto` primitives null it because *they* just changed the page). Anything that changes the
823
- page *outside* the session - a human clicking around in a visible `--non-headless` session
824
- someone is co-driving, for instance - leaves `here` silently stale, since `send`/`reach` only
825
- ever re-detect when the position is already unknown, never to double-check a known one.
826
- `resync` forces that re-detection unconditionally, right now, against whatever the real page
827
- actually shows. Doesn't crash or corrupt anything if you never need it - it's a real, found
828
- gap (confirmed by reading the exact code path, `src/auto-session.ts`'s `currentMenu()`), fixed
829
- outright rather than left as a caveat.
830
-
831
- **Coverage gaps `waygraph check`/`graph` can't see, because there's no Block to scan yet.**
832
- Static tools only find gaps in Blocks that already exist - a real link or button on the live
833
- page with *no Block written for it at all* has nothing in source to catch it. Every live
834
- `auto`/`browser`/`pilot` session watches the real page instead and warns (once per element,
835
- via `console.warn`) on a same-origin `<a href>` no `defineNavBlock` covers, or a visible
836
- `button`/`[role=button]`/submit input no Method/NavClick Block selector matches:
837
-
838
- ```text
839
- [waygraph] unmapped nav link on this page: /settings - no NavBlock covers this URL; add defineNavBlock
840
- [waygraph] unmapped button on this page: #save-draft - no Method/NavClick Block selector matches; consider defineMethodBlock or defineNavClickBlock
31
+ npx waygraph init my-app
32
+ cd my-app
33
+ npm install && npx playwright install chromium
34
+ npm test # green immediately, fully offline
35
+ npm run test:ui # same tests in Playwright's interactive UI
36
+ npm run auto # explore the app by picking Blocks in a browser
841
37
  ```
842
38
 
843
- Read them back with `auto console <sessionId>` - the same channel real console/network errors
844
- already come through, not a separate command (`src/coverage-gap.ts`, wired into every session
845
- in `src/auto-session.ts`).
846
-
847
- **On-page indicator.** A headful (`--non-headless`) session looks like an ordinary browser
848
- tab otherwise - no sign anything is driving it, which matters once a human might be watching
849
- or co-driving the same visible session. Every session injects a small badge (bottom-right
850
- corner: `Waygraph Pilot - session <id> - <Checkpoint>`) that click-expands into a panel
851
- listing the current live menu's real edges (block name, kind, target Checkpoint,
852
- description) - the same data `auto status` returns, rendered in the page itself. The overlay
853
- shell is installed via `context.addInitScript`, so it **persists on `about:blank`** and
854
- survives `goto` navigations (browser start defaults to blank; pilot navigates when a base URL
855
- exists). Headful sessions paint the badge immediately on start — no need to call `status`
856
- first. Bottom-left activity toasts label raw primitives as **`Running (no Block): …`**
857
- (click/type/goto/upload outside the Block library); Block runs stay **`Running (Block): …`**.
858
- Both refresh automatically after every `send`/`reach`/`reload`/`resync`/raw action.
859
- Self-contained (`src/pilot-overlay.ts`), not built on `waygraph demo`'s own panel/banner
860
- system.
861
-
862
- **Pilot itself does no planning, resolving, narrating, or acting** - `pilotStart`'s only job is
863
- starting the session and handing back its graph in one round trip; see `src/pilot.ts`. An
864
- earlier shape (`pilot ask "<text>"`, a deterministic ask-to-one-edge text matcher) was built,
865
- shipped, and then explicitly rejected as not matching this goal - preserved for reference at git
866
- tag `waygraph-pilot-v1-logs-prettified`, not on any active branch.
39
+ Already have a repo? `npm install waygraph @playwright/test`.
867
40
 
868
- **Honest scope, not silently redefined:** this capability's own proof runs against an in-repo
869
- example (`examples/saucedemo`), not a real external consumer application - it demonstrates the
870
- mechanism works, not the "demoable on one real consumer" bar `ROADMAP.md` sets for `1.0.0`,
871
- which remains separate, later, unmet work. Live reference: `tests/pilot/pilot.spec.ts` (the
872
- library function) and `tests/cli/pilot.spec.ts` (the real CLI), both proven against live
873
- saucedemo.com.
41
+ ## Run the Sauce Demo example
874
42
 
875
- ## Blind Pilot (cold start, zero Blocks)
876
-
877
- Waygraph Pilot above assumes a Block library already exists. Blind Pilot is the opposite
878
- case: a session on a site nobody has described to this package yet. `AutoSession`/`auto --cli
879
- --detach` already tolerate a project directory with **zero** `.block.ts` files (no crash,
880
- `here` just stays `null`), so an agent can open a real session and start exploring cold with
881
- no new code at all - `auto dom <sessionId>` already gives real DOM/ARIA visibility
882
- independent of any Block library.
883
-
884
- What's actually new here is two primitives an agent needs to go from "exploring" to "building
885
- a Block library incrementally":
43
+ The full example (`examples/saucedemo`) is a real project against saucedemo.com.
886
44
 
887
45
  ```bash
888
- waygraph auto click <sessionId> "<selector>" # act before any Block covers this
889
- waygraph auto type <sessionId> "<selector>" "<text>" # same, for a real input
890
- waygraph auto goto <sessionId> "<url>" # navigate the real live page
891
- waygraph auto reload <sessionId> # pick up a Block just written to disk,
892
- # without restarting the session
46
+ git clone https://github.com/deviate-dv8/waygraph.git
47
+ cd waygraph
48
+ npm install && npm run build # the example uses this checkout of waygraph
49
+ npx playwright install chromium
50
+ cd examples/saucedemo && npm install
51
+ npm test # 15 tests against the live site
52
+ npm run demo # watch the checkout flow with the step overlay
53
+ npm run auto # explore it by hand
893
54
  ```
894
55
 
895
- `click`/`type`/`goto` each re-detect the session's Checkpoint afterward (the same detection
896
- `send`/`status` already use) and return a fresh snapshot - a selector matching nothing is a
897
- reported failure naming it, not a silent no-op. `reload` re-discovers the project's Block
898
- library/graph from disk in place, leaving the live page, mem, and current Checkpoint
899
- untouched - so a Block an agent just wrote to disk becomes immediately runnable via the
900
- session's existing `send`, without relaunching the browser.
901
-
902
- **This package writes no Block content.** The driving agent recognizes a pattern ("this is a
903
- login form") and writes the `.block.ts`/`*Sel`/mem-keys files itself, using the conventions
904
- documented above - the same way it would write any other source file. Worked example (proven
905
- end to end in `tests/cli/auto-session-blind-pilot.spec.ts` against an in-repo synthetic
906
- fixture, `tests/fixtures/blind-pilot-site/`): start a session with zero Blocks, explore via
907
- `dom`/`click`/`goto`, write one real `defineNavBlock` to disk, `reload`, then `send` it -
908
- reaching the real Checkpoint it declares, proving it's genuinely driveable, not just visible.
56
+ ## The four ideas
909
57
 
910
- **Two real gotchas found while proving this, worth knowing before debugging a silent
911
- failure:** a `.block.ts` file that throws on import (e.g. a malformed Trait call) vanishes
912
- from the graph with no error printed anywhere - `discoverGraph`'s per-file import errors are
913
- mostly swallowed silently, so "reload did nothing" can mean a real mistake in the file just
914
- written, not a package bug. And a Block not wired into any `.flow.ts` (`waygraph graph`'s own
915
- "orphan" warning) is still fully visible and runnable in a live session's menu - orphan status
916
- only affects `auto --blocks <From> <To>` path-finding, not `auto`'s own menu.
58
+ | Word | Meaning |
59
+ |---|---|
60
+ | **Checkpoint** | A named place the app can be: `LoginPage`, `LoggedIn`, `OrderComplete`. |
61
+ | **Block** | One action from one Checkpoint to another, with a `verify` that confirms it. |
62
+ | **Flow** | Blocks in order. Run it, demo it, or let `auto` pick the route. |
63
+ | **Mem** | Typed shared data for a run (`LoginCreds`, `SelectedItem`). |
917
64
 
918
- **Honest scope:** Blind Pilot does not currently author into the Waygraph Map convention
919
- below by default - it still writes plain files wherever it's pointed. Proof stays against an
920
- in-repo synthetic fixture, not a real external site.
65
+ Block kinds: **Nav** (go to a page), **Method** (one action), **Effect** (act on one row of a
66
+ list), **Assert** (confirm a state, e.g. a button is disabled), **Page** (a page's hub).
921
67
 
922
- ## Waygraph Map
68
+ ## Where files go: the Map
923
69
 
924
- An opinionated, Next.js/Nuxt-style folder convention where a project's own directory
925
- structure mechanically *is* its map - not a separate schema file to generate, maintain, or
926
- let drift out of sync. Needs zero new engine code: `discoverGraph`/`loadBlockLibrary` already
927
- recurse through any folder structure, matching only the `.block.ts` filename pattern - folder
928
- naming and depth are already 100% cosmetic to every existing command.
70
+ Use the **Waygraph Map**. Folders under `src/map/` mirror your app's URLs, one folder per page:
929
71
 
930
72
  ```text
931
- src/map/
932
- (app_base)/ # the landing/base group - purely organizational, never part of
933
- dashboard/ # any Checkpoint tag. One folder per Checkpoint - "Dashboard"
934
- _page.block.ts # arrival hub (definePageBlock) - fixed name, every folder
935
- _nav.block.ts # navigation (defineNavBlock) - fixed name, every folder
936
- _sel.ts # selectors for this Checkpoint - fixed name, every folder
937
- _methods/ # this Checkpoint's own action Blocks - fixed name, every
938
- click-widget.block.ts # folder. Contents keep their own descriptive names -
939
- (external)/ # only the folder itself is fixed.
940
- docs/ # a genuinely cross-origin group, same shape - "Docs"
941
- _page.block.ts
942
- _nav.block.ts
943
- _sel.ts
944
- ```
945
-
946
- **Not just a naming preference - a forced convention.** Folder nesting under `map/(group)/`
947
- must **verbatim-match** the real site's own URL path segments, `(group)` parens excluded
948
- (purely organizational, same as a Next.js route group): `/app/chats` lives at
949
- `map/(app_base)/app/chats/`, never `map/(auth)/chats/` for a fabricated grouping that was
950
- never a real `/auth/*` URL. `waygraph map [project]` (see [CLI reference](#cli-reference))
951
- enforces this mechanically and exits 1 on a mismatch - don't rely on review alone. Same Block
952
- helpers as today's freeform "manual mode" (`definePageBlock`/`defineNavBlock`/
953
- `defineMethodBlock`/etc.) either way - Map only changes *where files live and what they're
954
- named*, never what kind of Block authors them or how they execute. A project adopts it
955
- incrementally, folder by folder. Prefer [`map()`](#map---a-kind-checked-no-teleporting-flow-builder)
956
- over a hand-assembled `defineFlow([start, ...])` array when wiring these Blocks into a Flow -
957
- it's the one that can't silently accept a Block that didn't come from a real factory.
958
-
959
- **Leading underscore = this Checkpoint's own fixed machinery, never a route segment.**
960
- `_nav.block.ts`/`_page.block.ts`/`_sel.ts`/`_methods/` (same private-folder idea as Next.js's
961
- own `_folder` convention) mark "this belongs to the endpoint whose folder it's directly in,"
962
- so a bare (non-underscore, non-`(group)`) folder name always means a real child
963
- Checkpoint/URL segment - `_methods/` can never be mistaken for a sibling endpoint folder the
964
- way a bare `methods/` structurally could be, since only ONE of those two readings is
965
- mechanically distinguishable at a glance. `waygraph map`'s own folder-vs-URL comparison
966
- excludes underscore segments the same way it excludes `(group)` ones - `_methods/foo.block.ts`
967
- compares against the URL as if `_methods/` weren't there at all. Individual files inside
968
- `_methods/` keep their own descriptive names (`join-pool.method.block.ts`, not
969
- `_join-pool...`) - they're hand-authored per-project content, not fixed convention names; the
970
- `_methods/` folder boundary alone already marks the whole subtree as non-route.
971
-
972
- **"waypack" - loading another project's Blocks needs no separate manifest either.** A second
973
- project depending on a Map-convention project as a plain `file:` dependency (the same
974
- mechanism `examples/saucedemo`'s own `"waygraph": "file:../.."` already uses) is immediately
975
- understandable: `waygraph graph node_modules/<loaded-package>` correctly discovers its full
976
- Checkpoint/edge structure, with nothing generated or maintained separately. Proven end to end
977
- in `examples/routed-demo-consumer/` against `examples/routed-demo/`.
978
-
979
- **A real bug this proof surfaced, fixed, not left as a caveat:** a *live* `--detach` session
980
- against a package loaded through a consumer project's own deeply nested `node_modules/<pkg>`
981
- path used to fail with `listen EINVAL` - the session's Unix socket lived under the project
982
- directory, and that absolute path could exceed the OS's AF_UNIX limit (~108 bytes on Linux).
983
- Fixed: session sockets now live in a short, fixed location (`os.tmpdir()/waygraph-auto/`),
984
- independent of how deeply the project itself is nested - confirmed against the exact
985
- previously-failing path (`auto --cli --detach`, `auto reach`, and quit all working normally).
986
- Session metadata (`.waygraph-auto/<id>.json`, discoverable per-project) is unaffected - only
987
- the socket moved.
988
-
989
- Full design history (why "Router" isn't a separate thing to build, two prior wrong readings
990
- of this before landing here, and everything above stated as requirements) in
991
- `openspec/changes/waygraph-map/`.
992
-
993
- ## Migrating from freeform ("router") to Waygraph Map
994
-
995
- "Router" isn't a separate mode to turn off - it's this project's own name for today's
996
- freeform, folder-organized style (`src/blocks/<slug>/`, any nesting, any file names).
997
- Migrating means moving those files under `src/map/(group)/<page-slug>/` with verbatim
998
- URL-matching names, nothing more - no engine change, no new Block helpers, no flag to flip.
999
- Do it incrementally: the two styles coexist in the same project (and even the same Flow) with
1000
- no special-casing, since `discoverGraph`/`loadBlockLibrary` only ever match the `.block.ts`
1001
- filename pattern, never folder depth or naming.
1002
-
1003
- 1. **List every real URL your NavBlocks/PageBlocks already navigate to.** For each one with a
1004
- static string `url`, note its real path. For each one that's `click`-based (no `url` field
1005
- at all) or a dynamic `(mem) => string` function, note that too - neither is statically
1006
- checkable by `waygraph map`, so they can go wherever makes sense; only a literal string
1007
- `url` is verified.
1008
- 2. **Pick your group(s).** `(app_base)/` for the landing/base app (organizational only, never
1009
- part of a Checkpoint tag); `(external)/` for genuinely cross-origin Blocks (mail tools,
1010
- third-party embeds) - verify with the real URL, not the folder's own current name, since a
1011
- folder can already be mis-grouped (a real bug this session found: a project's own
1012
- `(external)/docs/` was actually same-origin the whole time).
1013
- 3. **Create `src/map/(group)/<verbatim-url-segments>/` per Checkpoint**, `git mv` each
1014
- Block/Sel file in, and rename the fixed ones: `nav.block.ts` -> `_nav.block.ts`,
1015
- `page.block.ts` -> `_page.block.ts`, your selector file -> `_sel.ts` (drops its slug - now a
1016
- fully fixed name), `methods/` -> `_methods/` (contents keep their own names unchanged).
1017
- **Two Checkpoints sharing one real URL** (a DOM-state distinction, not a URL one - e.g. a
1018
- "joined" vs "not joined" variant of the same page) can't both use the bare fixed names in
1019
- one folder; give each pair a slug prefix instead (`app-home._nav.block.ts` /
1020
- `in-pool._nav.block.ts`, or similar) rather than nesting either under its own subfolder
1021
- (that would add a folder segment the real URL doesn't have, and fail step 5).
1022
- 4. **A dynamic per-instance URL** (a real chat/order/ticket id, not a fixed route) - if it's
1023
- currently a plain string constant, wrap it as `url: () => thatConstant` instead. A bare
1024
- string is always treated as a real, checkable static route; a function is correctly treated
1025
- as dynamic/non-canonical and skipped, matching how you'd actually navigate a real instance of
1026
- it in practice anyway.
1027
- 5. **Fix every import** the moves break (states/mem-key paths change depth; sibling
1028
- nav/page/methods imports need their new `_`-prefixed names) - let the compiler do this for
1029
- you: `tsc --noEmit` if the project has one, otherwise `waygraph check [project]` and
1030
- `waygraph graph [project]` (both do real dynamic imports of every Block file and report
1031
- import failures by name) are just as effective a proof.
1032
- 6. **Run `waygraph map [project]`.** Exit 0 / "0 violations" is the actual finish line - not a
1033
- subjective review. A remaining violation names the exact file, its real folder path, and the
1034
- real URL it doesn't match; fix the folder, not the check.
1035
- 7. **Diff `waygraph graph`'s node/edge/skipped/orphan counts against before the move.** A pure
1036
- migration changes zero Block behavior - if a count changed, something broke in transit
1037
- (a bad import silently dropped a Block from discovery is the usual cause), not something to
1038
- wave off as "close enough."
1039
-
1040
- Once the folder structure is settled, prefer building/rebuilding Flows over these Blocks with
1041
- [`map()`](#map---a-kind-checked-no-teleporting-flow-builder) instead of a hand-assembled
1042
- `defineFlow([start, ...])` array - it's the one that can't silently accept a Block that isn't
1043
- really a Nav/Page/Assert/Method from this package's own factories.
1044
-
1045
- ## Getting started (pick one)
1046
-
1047
- | Goal | Command |
1048
- |------|---------|
1049
- | Watch Sauce Demo step-through (temp dir only) | `npx waygraph try demo` |
1050
- | Interactive explore (Add/Remove/Open details from live page) | `cd examples/saucedemo && npm i && npx waygraph auto` |
1051
- | Scaffold a new **offline** project (green `npm test` on local fixture `:4177`) | `npx waygraph init my-app` |
1052
- | Install coding-agent defs for diving an app into Blocks | `npx waygraph agent-dive --loop claude` (also `opencode` / `cursor` / `vscode`) |
1053
- | Print a packaged agent skill to stdout | `npx waygraph --skill` (list) / `--skill-pilot` / `--skill-pilot-blind` / `--skill-convention` |
1054
- | Add waygraph to an existing repo | `npm install waygraph @playwright/test` |
1055
-
1056
- ```bash
1057
- npx waygraph init my-app
1058
- cd my-app && npm install && npx playwright install chromium && npm test
73
+ src/map/(app)/checkout/
74
+ _nav.block.ts how to get here
75
+ _page.block.ts "you've arrived"
76
+ _sel.ts every selector for this page
77
+ _methods/ one action per file
1059
78
  ```
1060
79
 
1061
- `try demo` is different: live saucedemo.com, step-through **Sign In -> Shop & Checkout ->
1062
- blocked Viewer login**, then headless tests. Permanent full example:
1063
- [`examples/saucedemo`](./examples/saucedemo). Offline empty scaffold: `init`.
1064
-
1065
- **`create-waygraph` (npm) is deprecated** - it was the identical `init` template shipped as
1066
- a second package for no real benefit. Use `npx waygraph init my-app` instead.
1067
-
1068
- ```bash
1069
- # From this checkout, after npm run build:
1070
- cd examples/saucedemo && npm install && npx playwright install chromium
1071
- npm test # live Playwright suite
1072
- npm run auto # headed interactive explore
1073
- npm run demo:step # stepper (manual Next)
1074
- npm run demo:autoplay # stepper with Auto-advance
1075
- ```
1076
-
1077
- Both scaffold commands emit the same offline tree (route-shaped `demo-web/` + `methods/`,
1078
- stubs, fixtures, one YAP slide). Layout: [`docs/scaffold.html`](./docs/scaffold.html) ·
1079
- `templates/scaffold/STRUCTURE.md`.
1080
-
1081
- **Consumer layout (Next.js App Router):** block folders mirror `app/` page routes (`/` at
1082
- the namespace root; no invented `landing/`/`root/`; sidebar = chrome + edges). See
1083
- [`docs/consumer.html`](./docs/consumer.html). A separate mesh handout
1084
- (`WAYGRAPH-CONSUMER-CONVENTION.md`) covers the same convention outside this repo - not
1085
- part of this package's own tree.
1086
-
1087
- ## CLI reference
1088
-
1089
- `waygraph auto [project]` is the **interactive explore** loop: `locate()` reads where you
1090
- are, lists runnable Blocks from the graph, you pick one (headful panel or `--cli` terminal
1091
- menu), repeat. Static graph export (old JSON / Mermaid) is `waygraph graph [project]`
1092
- (`--mermaid`). Unattended JSON execution is `run` + `WAYGRAPH_JSON=1`.
1093
-
1094
- **`--cli` session control:** `waygraph auto --cli` on its own is a blocking terminal loop -
1095
- fine for a person, awkward for an agent that needs to inspect state between picks or send
1096
- one command at a time without guessing a whole input sequence upfront. `--detach` runs that
1097
- same session as a background socket server instead (session identity under
1098
- `.waygraph-auto/` in the target project, mirroring `.waygraph-traverse/`'s convention);
1099
- `auto send <sessionId> "<pick>"` and `auto status <sessionId>` are non-interactive
1100
- request/response calls against it (no TTY needed), and `auto attach <sessionId>` reopens an
1101
- interactive terminal against an already-running session. `send q`/`send quit` ends the
1102
- session and cleans up its socket/metadata. `--detach` defaults to headless;
1103
- `--non-headless` (the same flag `run`/`demo` already use) launches a real visible browser
1104
- window while the session stays driven entirely through `send`/`status`/`attach`/`dom` - not
1105
- a new picker UI, and the existing page-embedded headful panel (bare `waygraph auto`, no
1106
- `--cli`) is untouched either way.
80
+ `waygraph map` fails if a folder stops matching its real URL, so the graph can't quietly go
81
+ stale. `waygraph init` scaffolds this layout. A plainer, freeform layout (any folders, any
82
+ names) still works and is fine for small projects, but the Map is where the tooling is going.
1107
83
 
1108
- **Session history:** `auto trace <sessionId>` returns a Checkpoint/Block-level record of
1109
- what the session actually did - Block name, Checkpoint before/after, and (when the Block
1110
- authors them) its resolved `stubBefore`/`stubAfter`/`stubOnError` demo-narration fixtures
1111
- (the same highlight/todo/device data `waygraph demo`'s own lifecycle logging computes via
1112
- `runStubPhase`, reused here since it's pure data with no browser side effects). Deliberately
1113
- not a raw action recorder - no clicks/fills, only the same Block-level resolution the rest of
1114
- the engine already reasons about, capped at the last 500 steps.
1115
-
1116
- **Reading the live page:** `auto dom <sessionId>` gives an agent driving a session read-only
1117
- visibility into the actual page, without reading the target project's frontend source.
1118
- Default `--mode aria` returns Playwright's AI-oriented accessibility snapshot
1119
- (`ariaSnapshotJSON({ mode: "ai" })`) - small and usually enough to find "the Username
1120
- textbox" or "the Login button." `--mode full` returns a bounded raw DOM subtree
1121
- (tag/attributes/text/children - useful when you need actual CSS classes or data-attributes
1122
- `aria` can't see), hard-capped on depth/node count/text length and marked `truncated: true`
1123
- whenever a cap is hit, since this is read by an LLM, not a human. `--selector <sel>` scopes
1124
- either mode to one element's subtree instead of the whole page - a modifier on the mode, not
1125
- a third mode.
1126
-
1127
- **Agent bootstrap:** `waygraph pilot start` starts a `--detach` session and reads back the
1128
- whole project graph in one call, so an agent can begin planning a multi-step request
1129
- immediately - see "Waygraph Pilot" above for the full picture.
1130
-
1131
- **Cold start (zero Blocks):** `auto click/type/goto <sessionId>` act on the live page even
1132
- when no Block covers that action yet, and `auto reload <sessionId>` picks up a Block just
1133
- written to disk without restarting the session - see "Blind Pilot" above.
1134
-
1135
- **`waygraph test [...args]`** is a thin wrapper around the project's own `@playwright/test`
1136
- suite - it forwards to the local `node_modules/.bin/playwright` (falling back to
1137
- `npx playwright` if the project hasn't installed it locally yet), so `waygraph test` behaves
1138
- exactly like `playwright test`, and anything after it (`--grep`, a spec path, `--headed`, …)
1139
- passes straight through. `waygraph test ui` (or `waygraph test --ui`) launches Playwright's
1140
- interactive UI Mode the same way. Scaffolded projects (`waygraph init`) wire this up as
1141
- `npm test` / `npm run test:ui`, and ship `trace: "retain-on-failure"` plus
1142
- the `html` reporter in `playwright.config.ts`, so a failing `waygraph test` already has a
1143
- trace waiting - `waygraph test report` opens the HTML report, and
1144
- `waygraph test show-trace <trace.zip>` opens one trace directly (both forward to Playwright's
1145
- own `show-report`/`show-trace`, which live outside `playwright test`, so they're handled
1146
- before the `test` forward rather than passed through it).
1147
-
1148
- Flows are files (0.10.5+):
1149
-
1150
- | Want | Command |
1151
- |------|---------|
1152
- | List flows | `waygraph list` -> `src/flows/shop.flow.ts shopFlow` |
1153
- | Run by file | `waygraph run src/flows/shop.flow.ts --data '{...}'` |
1154
- | Same via `auto` | `waygraph auto src/flows/shop.flow.ts --data '{...}'` |
1155
- | Run by export | `waygraph run --blocks shopFlow` |
1156
- | Manual watch | `waygraph demo src/flows/shop.flow.ts` |
1157
- | Auto-advance | `waygraph demo --blocks shopFlow --auto-next` (nav auto-hides strip) |
1158
- | Fast / full strip | `waygraph demo ... --fast` (shorter gates; keeps cursor) · `--full` (classic chips; default = carousel) |
1159
- | Todo dock UX | `waygraph demo ... --todo-smart` (default) · `--todo-full` (no compact/collision/behind) |
1160
- | QA watch + record | `waygraph demo --blocks shopFlow --auto-play-video` |
1161
- | Ad-hoc Blocks | `waygraph run --blocks "login then nav-cart" --data '{...}'` |
1162
- | Headed execute | `waygraph run --blocks shopFlow --non-headless --video` |
1163
- | Explore | `waygraph auto` / `waygraph auto --cli` |
1164
- | Browser command reference | `waygraph browser` |
1165
- | List live browser sessions | `waygraph browser sessions [--json]` |
1166
- | Open a new persistent browser | `waygraph browser start` (headful, about:blank by default) |
1167
- | Stop a browser session | `waygraph browser stop <sessionId>` / `stop --all` |
1168
- | Pilot bootstrap (browser + graph + snapshot) | `waygraph pilot start` |
1169
- | Attach to existing session (graph only) | `waygraph pilot attach <sessionId>` |
1170
- | Path-find | `waygraph auto --blocks LoginPage OrderComplete` |
1171
- | Run `--cli` as a background session (legacy) | `waygraph auto --cli --detach` -> `{sessionId, socketPath}` |
1172
- | Drive a detached session (no TTY) | `waygraph browser send <sessionId> "<pick>"` -> JSON state (`<pick>` is a menu index or a Block name) |
1173
- | Paint highlight rings (shorthand) | `waygraph browser highlight <sessionId> "#x\|Label\|tone; .y\|Label2"` |
1174
- | Paint highlight rings (full JSON) | `waygraph browser highlight <sessionId> '{"rings":[{"selector":"#x","label":"X"}]}'` |
1175
- | Read a detached session's state | `waygraph browser status <sessionId>` (no side effects) |
1176
- | Reattach a terminal to a detached session | `waygraph browser attach <sessionId>` |
1177
- | Read the live page (aria, small/default) | `waygraph auto dom <sessionId>` |
1178
- | Read the live page (raw DOM, bounded) | `waygraph auto dom <sessionId> --mode full` |
1179
- | Scope either to one element | `waygraph auto dom <sessionId> --selector ".inventory_list"` |
1180
- | Detached session with a real visible browser | `waygraph auto --cli --detach --non-headless` |
1181
- | Read the session's Checkpoint/Block history | `waygraph auto trace <sessionId>` |
1182
- | Read real console/network errors + coverage-gap warnings | `waygraph auto console <sessionId>` |
1183
- | Read localStorage/sessionStorage + service workers | `waygraph auto storage <sessionId>` |
1184
- | Whole-project nav-escape + inline-selector + orphan sweep | `waygraph check [project]` |
1185
- | `tsc --noEmit` + bad-practice warnings | `waygraph typecheck [project]` (`--no-practices` to skip scan) |
1186
- | Waygraph Map enforcement (verbatim url-vs-folder, exits 1 on a violation) | `waygraph map [project]` |
1187
- | Graph crawl | `waygraph traverse [project] --parallel N --min-edge-coverage 80%` |
1188
- | Coding-agent defs | `waygraph agent-dive --loop claude` |
1189
- | Print packaged skills | `waygraph --skill` / `--skill-pilot` / `--skill-pilot-blind` / `--skill-convention` |
1190
- | One-shot temp-dir demo | `waygraph try demo` / `waygraph try auto` / `waygraph try auto:cli` |
1191
- | Run the project's `@playwright/test` suite | `waygraph test` |
1192
- | Same suite, Playwright's interactive UI Mode | `waygraph test ui` (or `--ui`) |
1193
- | Open the last HTML report | `waygraph test report` |
1194
- | Open one trace in the trace viewer | `waygraph test show-trace <trace.zip>` |
1195
-
1196
- `--blocks` / positional accepts a Flow export, a `.flow.ts` path, or `"a then b"`.
1197
- `auto <file.flow.ts>` **runs** that flow (same as `run`); bare `auto` still explores.
1198
- `--auto-next` (alias `--autoplay`) = panel Auto-advance. `--auto-play-video` is **demo
1199
- only**. `chain` remains a compat alias for `run --blocks` / `auto --blocks`.
1200
-
1201
- ### Todo dock UI (demo, 0.15.8+)
1202
-
1203
- Long FR/AC checklists used to bury highlight rings. **Smart defaults are on:**
1204
-
1205
- | Behavior | Default | Opt out |
1206
- |----------|---------|---------|
1207
- | Compact fold (~5 rows around current; hover expands; `+N more`) | on | `ctx.todoDockFull()` / `ctx.todoDockUi({ compact: false })` / `--todo-full` / `WAYGRAPH_TODO_UI=full` |
1208
- | Collision flip (dock L/R when a ring overlaps) | on | `ctx.todoDockUi({ collision: false })` / `WAYGRAPH_TODO_COLLISION=0` |
1209
- | Behind ring (dim + lower z-index while a ring is up) | on | `ctx.todoDockUi({ behindRing: false })` / `WAYGRAPH_TODO_BEHIND=0` |
1210
-
1211
- Per-knob env also: `WAYGRAPH_TODO_COMPACT`, `WAYGRAPH_TODO_CAP` (default 5),
1212
- `WAYGRAPH_TODO_EXPAND_CAP` (default 14). Author API: `ctx.todoDockUi({ ... })`.
1213
- `browser highlight` (same as `auto`/`pilot highlight` - identical command, see "auto vs
1214
- browser vs pilot" above) accepts the same knobs as `todoUi` on the JSON body.
1215
-
1216
- Run `waygraph --help` (or any subcommand with no args) for the full flag reference kept
1217
- in `src/cli.ts`'s own `usage()` - that's the source of truth for flags, this table is the
1218
- scannable summary.
1219
-
1220
- ## Example
1221
-
1222
- Two Tier-0 Blocks (only `act` + `resolve`, no branching), each confirmed with `verify`
1223
- after the fact rather than asserting mid-`observe`, defined as a flow and run against a
1224
- real page:
1225
-
1226
- ```typescript
1227
- import { Engine, start, end, MemPage, key, checkpoint } from "waygraph";
1228
- import type { Block, Checkpoint, Start } from "waygraph";
84
+ ## Commands you'll use
1229
85
 
1230
- type FormLoaded = Checkpoint<"FormLoaded">;
1231
- type Submitted = Checkpoint<"Submitted">;
1232
-
1233
- const EmailKey = key<string>("form.email");
1234
- const PasswordKey = key<string>("form.password");
1235
-
1236
- const GotoForm: Block<Start, FormLoaded> = {
1237
- name: "goto-form",
1238
- instruction: {
1239
- async act(page) {
1240
- await page.goto("https://example.com/login");
1241
- },
1242
- resolve: () => checkpoint("FormLoaded"),
1243
- },
1244
- };
1245
-
1246
- const FillAndSubmit: Block<FormLoaded, Submitted> = {
1247
- name: "fill-and-submit",
1248
- instruction: {
1249
- async act(page, _input, mem) {
1250
- await page.getByPlaceholder("Email").fill(mem.get(EmailKey));
1251
- await page.getByPlaceholder("Password").fill(mem.get(PasswordKey));
1252
- await page.getByRole("button", { name: "Submit" }).click();
1253
- },
1254
- resolve: () => checkpoint("Submitted"),
1255
- verify: [
1256
- {
1257
- name: "submitted-heading-shown",
1258
- check: async (page) => {
1259
- await page.getByRole("heading", { name: "Submitted" }).waitFor();
1260
- return true;
1261
- },
1262
- },
1263
- ],
1264
- },
1265
- };
1266
-
1267
- const mem = new MemPage();
1268
- mem.set(EmailKey, "alice@test.com");
1269
- mem.set(PasswordKey, "hunter2");
1270
-
1271
- const engine = new Engine();
1272
- const flow = engine.defineFlow([start, GotoForm, FillAndSubmit, end]);
1273
- const result = await flow.run(context, mem);
1274
- // result === { __state: "Submitted" }
1275
- ```
1276
-
1277
- ## Recipes
1278
-
1279
- ### Detect / drive the surviving tab after a run
1280
-
1281
- The default run closes the page it opened, and a page you hand in via `options.page`
1282
- survives. For a flow that must BE the surviving tab after it returns (an interactive
1283
- demo, a hand-back to a caller), ask for the page back explicitly:
1284
-
1285
- ```typescript
1286
- const { result, page } = await registerFlow.run(context, mem, { closeOnFinish: false });
1287
- // `result.__state` reached the terminal Checkpoint; `page` is still open where the
1288
- // flow left it - the caller keeps driving it, and closes it whenever IT is done.
1289
- ```
1290
-
1291
- ### Capture a popup (`target=_blank` click)
1292
-
1293
- Frameworks and email UIs routinely rewrite links to `target="_blank"`, so a click that
1294
- "should navigate" actually opens a second, engine-invisible tab. Until a second real use
1295
- case promotes this to an engine API, capture it in userland with a context-level page
1296
- event armed before the click that is expected to open exactly one popup:
1297
-
1298
- ```typescript
1299
- let popup: Page | undefined;
1300
- context.once("page", (p) => { popup = p; });
1301
- await linkHandle.click(); // the block that causes the popup (e.g. the
1302
- // MailHog email's real verify link)
1303
- if (popup) {
1304
- await popup.waitForLoadState(); // fully loaded before calling into the engine
1305
- await verifyLinkFlow.run(context, mem, { page: popup, closeOnFinish: false });
1306
- // popup is now the caller's page - close it when done, or leave it as the
1307
- // surviving tab of a demo.
1308
- }
1309
- ```
1310
-
1311
- `context.once` (not `.on`) guarantees a second stray popup won't re-fire the handler and
1312
- clobber your handle; if a page truly can open more than one popup, this recipe needs to
1313
- collect them instead. The popup is a normal Playwright `Page` from the same context, so
1314
- anything `Flow.run(context, mem, { page })` can drive is available to keep driving here,
1315
- and `closeOnFinish: false` hands it back into your ownership instead of the run closing
1316
- it out from under you.
86
+ | Do this | Command |
87
+ |---|---|
88
+ | Run tests / UI mode / open last report | `waygraph test` / `waygraph test ui` / `waygraph test report` |
89
+ | Run a flow | `waygraph run shopFlow --data '{...}'` (or `--mem-stub`) |
90
+ | Watch a flow with narration | `waygraph demo shopFlow` |
91
+ | Explore by picking Blocks | `waygraph auto` |
92
+ | See the whole graph | `waygraph graph` |
93
+ | Lint your Blocks and folders | `waygraph check` / `waygraph typecheck` / `waygraph map` |
94
+ | Open a persistent browser for an agent | `waygraph browser start` |
95
+ | Highlight things on the live page | `waygraph browser highlight <id> "#login\|Login button\|warning"` |
96
+ | Set up coding-agent skills | `waygraph agent-dive --loop claude` |
1317
97
 
1318
- ## Developing this package
98
+ `waygraph --help` lists everything.
1319
99
 
1320
- ```bash
1321
- git clone git@github.com:deviate-dv8/waygraph.git
1322
- cd waygraph
1323
- npm install
1324
- npm run typecheck # waygraph typecheck . (tsc --noEmit + practice warnings)
1325
- npm run test # node --test tests/unit + playwright test
1326
- npm run test:ui # playwright test --ui
1327
- npm run build # tsc -p tsconfig.build.json, emits dist/
1328
- ```
100
+ ## Learn more
1329
101
 
1330
- ### Blind-agent overlay gate (anti-blank)
102
+ - **[Docs site](https://deviate-dv8.github.io/waygraph/)** - guides and walkthroughs
103
+ - **[Full reference](./docs/REFERENCE.md)** - every feature in detail (long)
104
+ - **[Sauce Demo walkthrough](https://deviate-dv8.github.io/waygraph/saucedemo/)** - a worked example
105
+ - Agent skills: `waygraph --skill` prints them (pilot, blind-pilot, convention)
1331
106
 
1332
- Every live modal (`#wg-panel`, `#wg-banner`, `#wg-auto-panel`, `#wg-todo-dock`) stamps
1333
- `data-wg-ui` / `data-wg-modal` / `data-wg-ready="1"`. Do **not** claim the stepper works
1334
- unless one of these passes:
107
+ ## Develop this package
1335
108
 
1336
109
  ```bash
1337
- # Playwright helper (exported from waygraph)
1338
- import { assertWgOverlayReady } from "waygraph";
1339
- await assertWgOverlayReady(page); // throws on blank / opacity-0 / missing stamp
1340
-
1341
- # Live demo prove (exit 0 = painted, exit 2 = blank)
1342
- WAYGRAPH_PROVE_EXIT=1 WAYGRAPH_PROVE_SHOT=/tmp/wg.png \
1343
- waygraph demo --blocks loginFlow --data '...'
1344
- # stderr: WAYGRAPH_PROVE {"ok":true,"beacons":[...],"readyAttr":"1"}
1345
- ```
1346
-
1347
- Tests: `tests/cli/overlay-beacon.spec.ts`. Helpers: `src/overlay-beacon.ts`. Rules for
1348
- touching the stepper/overlay chrome itself: `src/CLI-STOMP-GUARD.md`.
1349
-
1350
- ## Layout
1351
-
1352
- ```
1353
- package.json the "waygraph" npm package itself
1354
- src/
1355
- types.ts Checkpoint, Instruction, Block, connect()
1356
- mem-page.ts MemKey, key(), MemPage
1357
- trait.ts Trait (type + discoverable Trait.url/.text/.visible), runVerify()
1358
- engine.ts runGraph(), definePageBlock, defineMethodBlock, Engine, ...
1359
- graph.ts discoverGraph, orphans, paths
1360
- auto-explore.ts waygraph auto menu building
1361
- auto-explore-run.ts waygraph auto interactive loop (headful + --cli)
1362
- highlights.ts stub/fixture/slide/todo-dock/device narration types + helpers
1363
- step-overlay.ts demo step overlay chrome (panel, ring, cursor)
1364
- overlay-beacon.ts blind-agent overlay readiness beacons
1365
- traverse-run.ts waygraph traverse crawl (serial/parallel)
1366
- traverse-coverage.ts traverse coverage report + CI gate
1367
- traverse-lease.ts traverse edge lease coordinator
1368
- blocks-select.ts shared --blocks glob/regex/bare grammar
1369
- agent-dive.ts waygraph agent-dive coding-agent scaffolding
1370
- cli.ts waygraph CLI entrypoint (all subcommands)
1371
- index.ts public barrel
1372
- examples/saucedemo/ live Sauce Demo (Page + methods/ + Sel)
1373
- templates/quickstart/ try demo / init template (mirrors sauce)
1374
- templates/scaffold/ offline waygraph init scaffold template
1375
- templates/agents/ waygraph agent-dive coding-agent definitions
1376
- docs/ GitHub Pages static HTML + docs/proposals/ RFCs
1377
- openspec/ spec-driven planning: specs/ (current), changes/ (in-flight),
1378
- changes/archive/ (shipped)
1379
- tests/ runtime unit + integration tests (@playwright/test)
1380
- tsconfig.json base config
1381
- tsconfig.build.json emits to dist/
110
+ git clone https://github.com/deviate-dv8/waygraph.git && cd waygraph
111
+ npm install && npm run build
112
+ npm run typecheck && npm test # unit + Playwright suites
1382
113
  ```
1383
114
 
1384
- In-package Sauce Demo: [`examples/saucedemo`](./examples/saucedemo). Other consumer
1385
- experiments may still live in a sibling workspace folder and depend on this package via
1386
- `"waygraph": "file:../waygraph"` during local dev (see that
1387
- project's own `.npmrc` - `install-links=true` is required there, or npm will symlink
1388
- instead of copy and pull this package's own `node_modules` in through the symlink, causing
1389
- a duplicate-Playwright-installation error).
115
+ MIT