chore: Add verify-outline skill for driving an isolated instance (#14076)

* chore: Add verify-outline skill for driving an isolated instance

Adds a project skill that launches a production build of the current
checkout with its own Postgres and Redis containers, drives it in headless
Chromium through journey scripts, and captures screenshots, traces, logs and
database checks as evidence. Includes a feature map for workspace setup,
collections, documents, search and public sharing.

* fix: Quote SQL values in verify-outline journeys and write state before containers start

- Add literal() to drive.mjs and use it for every value in journey SQL
- Check the document body with strpos on the JSON-escaped text, not LIKE
- Read the body back from the editor, as input rules change typed quotes
- Scope the public share check to main, not the screen-reader-only copy
- Write state.env before docker run so down can always clean up
This commit is contained in:
Tom Moor authored and GitHub committed 2026-10-13 08:37:50 -04:00
1 parent 95216810f8
commit b4bef2c014
14 files changed
+1214

No files matched your search

+247
View File
@@ -0,0 +1,247 @@
---
name: verify-outline
description: Launch an isolated Outline instance (web UI + API, production build, own Postgres/Redis containers) from the current checkout and drive it in a headless browser to prove a user-facing change works, with screenshots, Playwright traces and database checks as evidence. Use when asked to verify, demo, reproduce or screenshot Outline behavior in the real app, rather than only in unit tests.
---
# Verify Outline
Outline is a team knowledge base. The primary surface is the **web app**: a
React SPA served by the Koa server. The other surfaces are the RPC API
(`POST /api/<resource>.<verb>`), the collaboration websocket (Y.js) that saves
editor content, and the MCP server. All of them run in the same server process
that this skill starts.
This skill **never** uses the developer's dev server
(`https://*.outline.dev:3000`, Vite on 3001) or the docker-compose
Postgres/Redis on 5432/6379. They hold the developer's real session and data.
Every run gets its own copy of the source, its own containers, a free port and
an empty database. Many runs can exist side by side.
All commands below run from the repo root. `$V` is this skill's directory:
```bash
V=.claude/skills/verify-outline
```
## Launch
```bash
$V/scripts/verify-outline.sh up my-run # run-id: [a-z0-9-]+, omit for a timestamped id
```
What it does (about 30s on an M-series Mac):
1. rsyncs the checkout (with uncommitted changes) to
`~/.cache/outline-verify/runs/<id>/src`. It does not copy `node_modules`,
`build`, `.git`, `.env*` or the local TLS certs. `node_modules` is symlinked
from the checkout. The record of what was snapshotted is in `source.txt`.
Then it checks that every `package.json` dependency is in
`node_modules`. If not, it stops with `node_modules in … does not match`.
This happens when Conductor has moved the checkout to another commit:
run `yarn install` there, or use a checkout that matches.
2. Starts `outline-verify-<id>-pg` (postgres:latest) and
`outline-verify-<id>-redis` (redis:latest) on random 127.0.0.1 ports.
It waits for a TCP query to succeed *inside* the container: the image's
init phase runs a socket-only server, so `pg_isready` passes too early.
3. `node build.js` (SWC server build) and `vite build` (frontend) into the
snapshot's `build/`.
4. `sequelize db:migrate` on the empty database, including the data
migrations in `server/scripts/`.
5. Starts `node build/server/index.js --services=web,websockets,collaboration,worker,cron`
with `NODE_ENV=production`, `URL=http://localhost:<port>`, `FORCE_HTTPS=false`,
`FILE_STORAGE=local` and random secrets. The repo's `.env` files are
**not read**, because they hold real S3/OAuth credentials. So uploads stay
in the run's `storage/` dir and no OAuth providers are enabled.
**Ready** = the script prints `READY http://localhost:<port> (run-id: <id>)`.
This line only prints when `/_health` returns 200 (DB + Redis) **and** `/`
serves the built SPA. The script then prints `info` (URL, evidence dir, log,
DATABASE_URL).
The database is empty. There is no seed data. The first journey must be
`setup-workspace.mjs` (see Drive). It creates the workspace and admin through
the real first-run screen, and saves the session cookie for later journeys.
To test new code, `down` the run and `up` a new one. The snapshot does not
follow later edits. A rebuild without a new DB is not supported.
Requirements: Docker running (colima here), `node_modules` installed in the
checkout, and Playwright's Chromium in `~/Library/Caches/ms-playwright`
(see Drive).
## Doctor
Run this first when anything looks wrong. It is read-only. Exit code 0
means the instance is worth driving.
```bash
$V/scripts/verify-outline.sh doctor my-run
```
It checks the following: the server pid is alive, the port is listened on by
*our* process tree, the server cwd is the snapshot, both containers are
running, `/_health` returns 200, `/` serves the SPA, and there are no pending
migrations. It also prints the team/user counts (0 teams means `/` shows
workspace setup) and the commit plus uncommitted paths in the snapshot.
Other read-only helpers:
```bash
$V/scripts/verify-outline.sh info my-run # URL, EVIDENCE, SERVER_LOG, DATABASE_URL
$V/scripts/verify-outline.sh logs my-run 200 # tail server log (JSON lines)
$V/scripts/verify-outline.sh psql my-run 'select title from documents' # read-only transaction
$V/scripts/verify-outline.sh list # runs + labelled containers
```
## Drive
The harness is `scripts/drive.mjs`. It runs one journey module in headless
Chromium:
```bash
node $V/scripts/drive.mjs <run-id> <journey.mjs> [--headed] [--fresh] [-- key=value ...]
```
- The journey modules are in `$V/journeys/`. Each default-exports
`async ({ page, context, url, step, click, psql, literal, args, log }) => value`.
`page` already has `baseURL` set, so `page.goto("/home")` works.
`step(name, page?)` saves a numbered screenshot. `click(locator)`
moves the pointer over the element, waits, then clicks (see the rules below). `psql(sql)` returns rows
(`a|b|c`). Put values into SQL with `literal(value)`, never raw. `value` is written to `result.json`.
- The session persists per run in `runs/<id>/browser-state.json`. `--fresh`
starts signed out.
- Browser lookup: `OUTLINE_VERIFY_PLAYWRIGHT` (path to a playwright-core
package), else `node_modules/playwright-core`, else the newest
`~/.npm/_npx/*/node_modules/playwright-core` (the Playwright MCP server's
copy). Chromium: `OUTLINE_VERIFY_CHROME`, else the newest
`ms-playwright/chromium-*` build. The playwright-core version and the cached
Chromium build do not need to match. The Playwright **MCP** tools are set
to use the `chrome` channel, which is not installed here, so they fail.
Use drive.mjs.
The journeys that ship with the skill (see `features/` for what each proves):
```bash
node $V/scripts/drive.mjs my-run $V/journeys/setup-workspace.mjs # always first
node $V/scripts/drive.mjs my-run $V/journeys/create-collection.mjs -- name="Proof"
node $V/scripts/drive.mjs my-run $V/journeys/create-document.mjs -- collection="Proof"
node $V/scripts/drive.mjs my-run $V/journeys/search.mjs -- query=<word> expect="<title>"
node $V/scripts/drive.mjs my-run $V/journeys/share-public.mjs -- doc=/doc/<slug> expect="<body text>"
```
`create-document` returns `title`, `body` (with a letters-only marker) and
`url` in `result.json`. Feed them into `search` and `share-public`:
```bash
R=$(ls -td ~/.cache/outline-verify/evidence/my-run/create-document-*/ | head -1)result.json
node $V/scripts/drive.mjs my-run $V/journeys/search.mjs -- query="$(jq -r '.value.title|split(" ")|last' $R)" expect="$(jq -r .value.title $R)"
node $V/scripts/drive.mjs my-run $V/journeys/share-public.mjs -- doc="$(jq -r .value.url $R | sed 's|^http://localhost:[0-9]*||')" expect="$(jq -r .value.body $R)"
```
To verify a change, write a new journey next to these (copy the closest one).
Use stable handles that exist in this app:
- ARIA names: `button "New collection"`, `dialog "Create a collection"`,
`textbox "Document title"`, `textbox "Editor content"`,
`button "Share"` → `dialog "Share"` → `switch "Publish to internet"`,
`searchbox "Search…"`, sidebar `link "Expand <collection>"`,
`link "Search"`, `main` → `link "New doc"` (scope it: the sidebar's
Personal section has another `button "New doc"`),
`button "Account"`, `button "Document options"`.
- Routes: `/home`, `/search`, `/drafts`, `/collection/<slug>-<urlId>`,
`/doc/<slug>-<urlId>`, `/s/<shareId>` (public), `/settings/*`.
- To find more handles, dump `await page.locator("body").ariaSnapshot()` in a
scratch journey. Do not rely on a `main` landmark: some pages, such as a
collection while it loads or search, do not have one.
Interaction rules that matter here:
- **Use `click(locator)`, not `locator.click()`**, for sidebar items, header
buttons and list rows. `SidebarLink` and document rows re-render on
`pointerenter` (deferred menus, selection checkbox). Playwright's instant
move-and-click then loses the first click: nothing opens and no error shows.
- Type into the editor with `page.keyboard.type` after you click the title
or editor. In the title, `Enter` moves the cursor to the body.
- The body saves over the collaboration websocket, not the API. Poll the DB
(`documents.content::text`) for up to ~30s instead of trusting the screen.
- API-only checks: `curl -s -X POST $URL/api/<method> -H 'Content-Type: application/json' -H "Authorization: Bearer <key>" -d '{}'`.
Create the key in the UI (`/settings/api-and-access`, "API & Access") so that the key also
comes from a real path.
## Evidence
Evidence goes to `~/.cache/outline-verify/evidence/<run-id>/`, which is
**outside** the run dir and survives `down`. Each journey writes
`<journey>-<timestamp>/` with:
- `01-*.png, 02-*.png …` numbered screenshots of the action and the resulting
state, and `FAILED.png` on failure
- `trace.zip`: the full Playwright trace (DOM snapshots + screenshots per
action). Open it with `npx playwright show-trace trace.zip`.
- `console.log`: page errors and console errors/warnings
- `network.log`: every failed `/api` call and every API POST with its status
- `result.json`: pass/fail, error stack, returned value, and the step list
The run-level files are `source.txt` (commit + uncommitted paths under test)
and `server.log`, which `down` copies.
Proof standards:
- Drive the real user path: click what a user clicks. Do not call internal
store setters, `developer.*` endpoints or test factories. `psql` is
read-only and only for asserting side effects.
- Capture the action and the result: a screenshot before the submit and
after it, plus the reload or the fresh context that shows persistence.
- Verify side effects, not only pixels: rows in Postgres (`psql`), files in
`runs/<id>/storage` for uploads, and `network.log` for API status codes.
For things that are visible to others (shares, permissions), check from a
second, signed-out or other-user browser context (see `share-public.mjs`).
- Read `console.log` and `network.log`. A green journey with a 500 or a
pageerror in the log is not a pass.
- No mocks: the instance is real end to end. External integrations (Slack,
Google, S3, SMTP) are not configured at all. A journey that needs one must
report that it cannot be verified here. It must not stub the integration.
- The rate limits are real (only the global per-IP limit is raised). Do not
disable the limits to make a journey pass.
- If a feature lists several entry points in `features/`, a proof that
drives only one of them is incomplete. Say which entry points you covered.
## Cleanup
```bash
$V/scripts/verify-outline.sh down my-run
```
This kills the server process tree recorded in `server.pid` (never by
name). It removes the two containers, copies `server.log` to the evidence
dir, and deletes `runs/<id>` (snapshot, DB, storage, cookies). It then lists
the evidence dir to show that the evidence is still there. If the port
still has a listener afterwards, it prints a warning. Inspect it with `lsof`
and do not kill it blindly. Run `down` after **every** run, including
failed `up` attempts (`up` writes state before the slow steps, so `down`
always works). `list` shows any runs that you left behind.
To delete the evidence itself, remove
`~/.cache/outline-verify/evidence/<run-id>`, but only when the user asks.
## Helpers
| Script | Invocation |
| --- | --- |
| `scripts/verify-outline.sh` | `up [id]`, `doctor <id>`, `info <id>`, `logs <id> [n]`, `psql <id> '<sql>'`, `down <id>`, `list` |
| `scripts/drive.mjs` | `node scripts/drive.mjs <id> <journey.mjs> [--headed] [--fresh] [-- k=v ...]` |
| `journeys/*.mjs` | see Drive; one file per user journey, args via `-- k=v` |
Environment overrides: `OUTLINE_VERIFY_ROOT` (default
`~/.cache/outline-verify`), `OUTLINE_REPO` (the checkout to snapshot; default
is the git toplevel of the cwd), `OUTLINE_VERIFY_PG_IMAGE`,
`OUTLINE_VERIFY_REDIS_IMAGE`, `OUTLINE_VERIFY_PLAYWRIGHT`,
`OUTLINE_VERIFY_CHROME`.
## Conductor caveat
`~/Projects/outline` is mirrored and reset by Conductor from other
worktrees. It can carry another agent's uncommitted diff, and untracked files
there can disappear. Run `up` from the worktree that has your change.
`source.txt` shows exactly what was snapshotted, so check it before you
claim that a run tested your change.
@@ -0,0 +1,24 @@
# Outline feature map
This is the maintained list of user-facing features that `verify-outline`
can drive. Each file covers what the feature is, how a user reaches it, how
to drive it with `scripts/drive.mjs`, and the observable end state that
proves it works.
The instance starts empty. Journeys build on each other in this order:
| Feature | File | Journey | Needs first |
| --- | --- | --- | --- |
| First-run workspace setup and sign-in | [workspace-setup.md](workspace-setup.md) | `journeys/setup-workspace.mjs` | fresh `up` |
| Collections | [collections.md](collections.md) | `journeys/create-collection.mjs` | setup |
| Documents (create, edit, persist) | [documents.md](documents.md) | `journeys/create-document.mjs` | a collection |
| Search | [search.md](search.md) | `journeys/search.mjs` | a document |
| Share to web (public link) | [sharing.md](sharing.md) | `journeys/share-public.mjs` | a document |
Not mapped yet (candidates in priority order): comments
(`button "Comment"` on a doc), inviting members and permissions
(`button "Invite people…"`, the `dialog "Share"` invite box), import/export
(`/settings/import`, `/settings/export`), API keys
(`/settings/api-and-access`), templates, and the archive and trash
(`/archive`, `/trash`). When you add one, add a row here and a file with
the same four sections.
@@ -0,0 +1,42 @@
# Collections
Collections are the top-level containers for documents. They also carry
the default permissions. They appear in the sidebar under "Collections".
## Sub-features
- Create (name, icon/color, default permission, advanced options)
- Open a collection page (`/collection/<slug>-<urlId>`) and expand it in the sidebar
- Edit, archive and delete through the collection menu (not mapped yet)
## How to get to it (user POV)
In the sidebar, under **Collections**, click **New collection**. A dialog
"Create a collection" opens. Type a name and click **Create**. The app
navigates to the new collection, and it appears in the sidebar. The command
bar (⌘K → "New collection") opens the same dialog.
## Driving it with drive.mjs
```bash
node $V/scripts/drive.mjs <id> $V/journeys/create-collection.mjs -- name="Proof"
```
The handles are `button "New collection"`, then
`dialog "Create a collection"`, then its only `textbox`, then
`button "Create"`. After that the URL matches `/collection/` and the sidebar
shows `link "Expand Proof"`.
The proof is `02-collection-page.png` plus exactly one row in `collections`
with that name and `deletedAt is null`.
## Gotchas
- The sidebar's "New collection" ignores an instant click (re-render on
`pointerenter`). Hover, wait 300ms, then click. The journey does this.
- The name input in the dialog has **no accessible name**
(`textbox` with no label). Select it as the only textbox in the dialog.
- `collections.create` has a per-endpoint rate limit. Many collections in a
few minutes on one run can return 429. Check `network.log`.
- The page has no `main` landmark until the collection loads. Wait for the
sidebar link instead.
@@ -0,0 +1,59 @@
# Documents
This is the core of the app: a collaborative ProseMirror editor. The title
saves over the API (`documents.update`). The body saves over the Y.js
collaboration websocket and is stored in `documents.content`.
## Sub-features
- New doc in a collection (it is published at once in the current UI)
- Title editing (`textbox "Document title"`)
- Body editing (`textbox "Editor content"`): typing, `/` block menu,
markdown shortcuts, uploads (`button "Upload file"`), find and replace
- Persistence across a reload, and real-time sync
- Header actions: Share, Star, `button "New child document"`, `button "Document options"`
## How to get to it (user POV)
Open a collection from the sidebar and click **New doc** (top right). An
empty doc opens at `/doc/untitled-<urlId>` with the cursor in the title.
Type a title, press Enter, then type the body. There is no Save button:
changes save on their own.
## Driving it with drive.mjs
```bash
node $V/scripts/drive.mjs <id> $V/journeys/create-document.mjs -- collection="Proof" [title=... body=...]
```
The journey opens the collection with `link "Expand <collection>"` and clicks
`main` → `link|button "New doc"`. It then clicks `textbox "Document title"`, uses
`keyboard.type(title)`, presses `Enter` and uses `keyboard.type(body)`.
The proof has three parts. (1) It polls the DB until the row
`title|published|content contains body` is `<title>|t|t`. (2) It reloads the
page and asserts that the title and body come back from the server. (3) It
takes the screenshots `01-typed.png` and `02-after-reload.png`.
`result.json` has `title`, `body` and `url` for the search and share
journeys.
## Gotchas
- New docs in a collection are **published at once** (`publishedAt` is set),
with an empty title until you type one. There is no "Publish" button in
this flow. The draft flow (`/drafts`, `link "New doc"` on Home →
`/doc/new`) is not mapped yet.
- The body is not saved by the API. Do not assert on `documents.update`
in `network.log`. Poll `content::text` for up to ~30s.
- Use letters-only unique markers. Postgres parses `verify-123` as a
negative-number token, so a numeric marker can never be found through
search.
- Scope "New doc" to `getByRole("main")`. Newer builds have a **Personal**
sidebar section with its own `button "New doc"`, which makes an inline
title input in the sidebar instead of opening the editor.
- Right after a reload, the body can be in the DOM twice for a moment (the
read-only editor and the collaborative editor during the hand-over).
Strict-mode locators then fail. Filter `{ visible: true }` and wait for one
copy. More than one visible copy after ~10s is a real bug.
- Use `page.keyboard.type` after you click. `locator.fill` on the
contenteditable bypasses ProseMirror's input handling.
@@ -0,0 +1,48 @@
# Search
This is full-text search over the documents the user can access
(Postgres `searchVector`), with filters and a "titles only" switch.
## Sub-features
- Query from the Search page (`/search`) or the header searchbox
`searchbox "Search documents ⌘K"` on Home
- Filters: `button "Any collection"`, `button "Any author"`,
`button "Published, Drafts"`, `button "All time"`,
`switch "Search titles only"`, sort `button "Relevance"`
- Open a result. Recent searches (`searches.list`).
## How to get to it (user POV)
Click **Search** in the sidebar, type a word in the big search box and press
Enter. The results list shows the title, the collection and the last update.
Clicking a result opens the doc.
## Driving it with drive.mjs
```bash
node $V/scripts/drive.mjs <id> $V/journeys/search.mjs -- query=<word> expect="<exact doc title>"
```
The handles are `link "Search"` (exact), then `searchbox "Search…"` with
fill and Enter. Then the journey waits for a result `link` whose name
contains the title, takes a screenshot, clicks it, and asserts that
`textbox "Document title"` equals `expect`.
The proof is `01-results.png` with the matching result, `02-opened-result.png`,
and `200 POST /api/documents.search` in `network.log`.
## Gotchas
- Use a letters-only word as the query (see documents.md). Numbers with a
leading hyphen are stored as negative numbers.
- The `searchVector` updates when the document saves. Search right after
`create-document` finished its DB poll, not mid-typing.
- The query is in the `?q=` URL param (`searchPath` in
`app/utils/routeHelpers.ts`), not `?query=`. Wait for the result, not for
the URL.
- The result rows switch to an interactive state (selection checkbox, star,
menu) on the first pointer event. Open a result with `click(locator)` from
drive.mjs. A bare `locator.click()` is swallowed.
- The result link name contains the title, and the sidebar has a link with
the same name. Take the `.last()` match, which is the result list.
@@ -0,0 +1,48 @@
# Sharing: publish to web
The Share dialog on a document controls member access and the public link.
"Publish to web" creates a `shares` row that anyone with the `/s/<shareId>`
link can open without signing in.
## Sub-features
- Publish to web (`switch "Publish to internet"`) and unpublish
- Copy the link (the link icon in the dialog). There are also share options
once published: indexing, child documents, and a custom URL.
- Invite people or groups (`textbox "Add or invite…"`) and change a
member's permission (`Can edit` and so on): not mapped yet
- Collection-level public access (Collection → Share): not mapped yet
## How to get to it (user POV)
Open a document and click **Share** (top right). A popover "Share" lists the
people with access and a "Publish to web" row with a toggle. Turn the toggle
on, then copy the link and open it in a private window.
## Driving it with drive.mjs
```bash
node $V/scripts/drive.mjs <id> $V/journeys/share-public.mjs -- doc=/doc/<slug-urlId> expect="<body text>"
```
The journey hovers and clicks `button "Share"` (exact), then clicks
`dialog "Share"` → `switch "Publish to internet"` and waits for
`aria-checked="true"`. It reads the share id from `shares`
(`published = t`, not revoked). It then opens `/s/<shareId>` in a **new
browser context with no cookies** and waits for the body text there.
The proof is `01-share-dialog-published.png` (toggle on),
`02-public-page-signed-out.png` (content visible while signed out), the
`db:` line with the share row, and `200 POST /api/shares.create`.
## Gotchas
- The journey refuses a doc that is already published. Use a fresh doc from
`create-document`.
- If the toggle does not turn on, look in `network.log` for a 429 on
`shares.create`. Before the skill raised the global per-IP limit, the
production build's static assets used up the default 1000 requests/minute
in a few page loads. The per-endpoint limit for shares still applies.
- The public page renders through the same SPA. A 404 there with a valid
share row usually means the team setting for public sharing is off
(`teams.sharing`).
@@ -0,0 +1,49 @@
# Workspace setup (first run)
On a self-hosted instance with no teams, `/` shows the **Create workspace**
form instead of a login screen. When the form is submitted, it POSTs
`/api/installation.create`. This creates the team and an admin user, sets the
`accessToken` cookie and redirects to `/home`. This is the only sign-in path
on a verification instance, because no OAuth or SMTP providers are configured.
## Sub-features
- Workspace creation (team row, subdomain from the name)
- Admin user creation (`users.role = 'admin'`)
- Sign-in by session cookie and the redirect to `/home`
- Guard: `installation.create` refuses when a team already exists
## How to get to it (user POV)
Open the instance URL on a brand-new install. The page has the heading
"Create workspace" and the fields "Workspace name", "Admin name" and "Admin
email", plus a "Continue →" button.
## Driving it with drive.mjs
```bash
node $V/scripts/drive.mjs <id> $V/journeys/setup-workspace.mjs [-- team="Acme" name="Ada" email=ada@acme.test]
```
The journey fills the three labelled inputs (`getByLabel`), clicks
`button /Continue/` and waits for `/home` and the sidebar navigation. It then
asserts exactly one `teams ⋈ users` row: `<team>|<email>|admin`.
The proof is `02-signed-in-home.png`: the sidebar shows the workspace name
and the admin. The `db:` log line shows the team and the admin row.
`browser-state.json` now holds the session for later journeys.
## Gotchas
- This runs only once per instance. The journey refuses when `teams` is not
empty. To repeat it, `down` and `up` a new run.
- The route is not mounted when `URL` is one of the cloud-hosted URLs
(`env.isCloudHosted`). The skill uses `http://localhost:<port>`, so it is
always self-hosted.
- These are expected in this journey's logs and are not failures:
`401 POST /api/auth.info` and a matching console error (the signed-out
probe before setup), an empty `[pageerror]` from that probe, and
`302 POST /api/installation.create` (the form redirect).
- To sign in as a second user, you need an invite. Email sign-in is
disabled in production without SMTP. A multi-user journey must report that
limit. It must not mint tokens.
@@ -0,0 +1,28 @@
// Create a collection from the sidebar "New collection" dialog.
// Args: name= (default "Verify Collection <time>").
export default async ({ page, click, step, psql, literal, args, log }) => {
const name = args.name ?? `Verify Collection ${Date.now()}`;
await page.goto("/home");
await page.waitForLoadState("networkidle");
const open = page.getByRole("button", { name: "New collection" });
await click(open);
const dialog = page.getByRole("dialog", { name: "Create a collection" });
await dialog.waitFor();
// The name input has no accessible label; it is the only textbox.
await dialog.getByRole("textbox").fill(name);
await step("create-collection-dialog");
await dialog.getByRole("button", { name: "Create" }).click();
await page.waitForURL(/\/collection\//);
await page.getByRole("link", { name: `Expand ${name}` }).waitFor();
await step("collection-page");
const rows = psql(`select name from collections where name = ${literal(name)} and "deletedAt" is null`);
log("db:", rows);
if (rows.length !== 1) {
throw new Error(`expected 1 collection row named ${name}, got ${rows.length}`);
}
return { name, url: page.url() };
};
@@ -0,0 +1,75 @@
// Create a document in a collection through the editor, then prove the title
// and body persisted (reload + database).
// Args: collection= (name of an existing collection, required), title=, body=.
// The editor applies input rules such as smart quotes to body=, so the checks
// use the text that the editor shows.
export default async ({ page, click, step, psql, literal, args, log }) => {
if (!args.collection) {
throw new Error("collection= is required; run create-collection.mjs first");
}
// Letters only: Postgres parses "verify-123" as a negative number token, so
// a numeric marker can never be found through search.
const marker = `verify${Array.from({ length: 8 }, () => "abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random() * 26)]).join("")}`;
const title = args.title ?? `Verify Doc ${marker}`;
const typed = args.body ?? `Body text ${marker}`;
await page.goto("/home");
await page.waitForLoadState("networkidle");
const coll = page.getByRole("link", { name: `Expand ${args.collection}` });
await click(coll);
await page.waitForURL(/\/collection\//);
// Scope to main: the sidebar has its own "New doc" for the Personal section.
const header = page.getByRole("main");
const newDoc = header.getByRole("link", { name: "New doc" }).or(header.getByRole("button", { name: "New doc" })).first();
await click(newDoc);
await page.waitForURL(/\/doc\//);
const titleBox = page.getByRole("textbox", { name: "Document title" });
await titleBox.click();
await page.keyboard.type(title);
await page.keyboard.press("Enter");
await page.keyboard.type(typed);
const body = (await page.getByRole("textbox", { name: "Editor content" }).locator("p").first().innerText()).trim();
if (body !== typed) {
log("editor changed body to:", body);
}
await step("typed");
// Title saves over the API, body over the collaboration websocket; poll the DB.
// jsonb text escapes strings as JSON does, so search for the escaped body.
const escapedBody = JSON.stringify(body).slice(1, -1);
let row = [];
for (let i = 0; i < 30; i++) {
row = psql(
`select title, "publishedAt" is not null, strpos(content::text, ${literal(escapedBody)}) > 0 from documents where title = ${literal(title)} and "deletedAt" is null`
);
if (row[0]?.endsWith("|t|t")) {
break;
}
await page.waitForTimeout(1000);
}
log("db:", row);
if (row[0] !== `${title}|t|t`) {
throw new Error(`document not persisted as published with body: ${JSON.stringify(row)}`);
}
const docUrl = page.url();
await page.reload();
// While loading, a read-only editor and the collaborative editor can both be
// in the DOM; wait for exactly one visible copy so real duplication fails.
const copies = page.getByRole("textbox", { name: "Editor content" }).getByText(body).filter({ visible: true });
await copies.first().waitFor();
for (let i = 0; i < 20 && (await copies.count()) !== 1; i++) {
await page.waitForTimeout(500);
}
if ((await copies.count()) !== 1) {
throw new Error(`body visible ${await copies.count()} times after reload`);
}
const shownTitle = await page.getByRole("textbox", { name: "Document title" }).innerText();
if (shownTitle.trim() !== title) {
throw new Error(`title after reload is ${JSON.stringify(shownTitle)}`);
}
await step("after-reload");
return { title, body, url: docUrl };
};
@@ -0,0 +1,31 @@
// Search for a word from the sidebar Search page and open the matching result.
// Args: query= (a letters-only word, required), expect= (title the results must
// include, required).
export default async ({ page, click, step, args, log }) => {
if (!args.query || !args.expect) {
throw new Error("query= and expect= are required");
}
await page.goto("/home");
await page.waitForLoadState("networkidle");
const nav = page.getByRole("link", { name: "Search", exact: true });
await click(nav);
await page.waitForURL(/\/search/);
const box = page.getByRole("searchbox", { name: "Search…" });
await box.fill(args.query);
await box.press("Enter");
const result = page.getByRole("link", { name: new RegExp(args.expect.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) }).last();
await result.waitFor({ timeout: 10000 });
await step("results");
log("results url:", page.url());
await click(result);
await page.waitForURL(/\/doc\//);
const title = await page.getByRole("textbox", { name: "Document title" }).innerText();
if (title.trim() !== args.expect) {
throw new Error(`opened ${JSON.stringify(title)} instead of ${args.expect}`);
}
await step("opened-result");
return { query: args.query, opened: page.url() };
};
@@ -0,0 +1,31 @@
// First-run workspace setup on an empty instance: the real self-hosted
// onboarding form that POSTs /api/installation.create and signs the admin in.
// Args: team=, name=, email= (defaults below).
export default async ({ page, step, psql, args, log }) => {
const team = args.team ?? "Verify Co";
const name = args.name ?? "Vera Admin";
const email = args.email ?? "admin@verify.test";
if (psql("select count(*) from teams")[0] !== "0") {
throw new Error("instance already has a team; setup only runs on a fresh instance");
}
await page.goto("/");
await page.getByLabel("Workspace name").fill(team);
await page.getByLabel("Admin name").fill(name);
await page.getByLabel("Admin email").fill(email);
await step("setup-form-filled");
await page.getByRole("button", { name: /Continue/ }).click();
await page.waitForURL(/\/home/, { timeout: 20000 });
await page.getByRole("navigation").first().waitFor();
await step("signed-in-home");
const rows = psql(
`select t.name, u.email, u.role from teams t join users u on u."teamId" = t.id`
);
log("db:", rows);
if (rows.length !== 1 || rows[0] !== `${team}|${email}|admin`) {
throw new Error(`unexpected team/user rows: ${JSON.stringify(rows)}`);
}
return { team, email, rows };
};
@@ -0,0 +1,51 @@
// Publish a document to the web from the Share dialog, then open the public
// link in a signed-out browser context and read the content.
// Args: doc= (document path such as /doc/slug-id, required), expect= (body text
// the public page must show, required).
export default async ({ page, click, context, step, psql, literal, args, log }) => {
if (!args.doc || !args.expect) {
throw new Error("doc= and expect= are required");
}
await page.goto(args.doc);
await page.waitForLoadState("networkidle");
const docId = args.doc.split("-").pop();
const share = page.getByRole("button", { name: "Share", exact: true });
await click(share);
const dialog = page.getByRole("dialog", { name: "Share" });
const toggle = dialog.getByRole("switch", { name: "Publish to internet" });
if ((await toggle.getAttribute("aria-checked")) === "true") {
throw new Error("document is already published to the web; use a fresh document");
}
await toggle.click();
await page.waitForFunction(
() => document.querySelector('[role=switch][aria-checked="true"]') !== null
);
await step("share-dialog-published");
const rows = psql(
`select s.id, s.published from shares s join documents d on d.id = s."documentId" where d."urlId" = ${literal(docId)} and s."revokedAt" is null`
);
log("db:", rows);
const [shareId, published] = (rows[0] ?? "").split("|");
if (published !== "t") {
throw new Error(`no published share row for ${docId}: ${JSON.stringify(rows)}`);
}
const anon = await context.browser().newContext({ baseURL: page.url() });
try {
const pub = await anon.newPage();
await pub.goto(`/s/${shareId}`);
// Scope to main: the server also renders a screen-reader-only copy.
await pub.getByRole("main").getByText(args.expect).first().waitFor({ timeout: 15000 });
const cookies = (await anon.cookies()).map((c) => c.name);
if (cookies.includes("accessToken")) {
throw new Error("anonymous context unexpectedly holds an accessToken");
}
await step("public-page-signed-out", pub);
log("public page url:", pub.url());
return { shareUrl: `/s/${shareId}`, publicUrl: pub.url() };
} finally {
await anon.close();
}
};
+203
View File
@@ -0,0 +1,203 @@
#!/usr/bin/env node
// Run a browser journey against a verify-outline instance and capture evidence.
//
// Usage:
// drive.mjs <run-id> <journey.mjs> [--headed] [--fresh] [-- key=value ...]
//
// The journey module default-exports
// `async ({ page, context, url, step, click, psql, literal, args, log }) => value`
// step(name, page?) saves a numbered screenshot, click(locator) hovers first, psql(sql) returns rows of
// read-only SQL, literal(value) quotes a string for that SQL, args holds the key=value pairs, value
// lands in result.json.
// Cookies persist per run in <run-dir>/browser-state.json, so a journey run
// after `setup-workspace.mjs` is already signed in. --fresh ignores them.
//
// Evidence goes to <evidence>/<journey>-<timestamp>/: numbered step
// screenshots, trace.zip (open with `npx playwright show-trace trace.zip`),
// console.log (page errors and console errors), network.log (failed /api
// calls and every POST to /api), result.json.
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import { createRequire } from "node:module";
import os from "node:os";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const verifySh = path.join(here, "verify-outline.sh");
const root = process.env.OUTLINE_VERIFY_ROOT ?? path.join(os.homedir(), ".cache/outline-verify");
const argv = process.argv.slice(2);
const sep = argv.indexOf("--");
const flags = sep === -1 ? argv : argv.slice(0, sep);
const extra = sep === -1 ? [] : argv.slice(sep + 1);
const [runId, journeyPath] = flags.filter((a) => !a.startsWith("--"));
const headed = flags.includes("--headed");
const fresh = flags.includes("--fresh");
if (!runId || !journeyPath) {
console.error("usage: drive.mjs <run-id> <journey.mjs> [--headed] [--fresh] [-- key=value ...]");
process.exit(2);
}
const args = Object.fromEntries(extra.map((kv) => kv.split(/=(.*)/s).slice(0, 2)));
const runDir = path.join(root, "runs", runId);
const stateFile = path.join(runDir, "state.env");
if (!fs.existsSync(stateFile)) {
console.error(`no run '${runId}' (${stateFile}); start one with verify-outline.sh up`);
process.exit(2);
}
const state = Object.fromEntries(
fs
.readFileSync(stateFile, "utf8")
.split("\n")
.filter(Boolean)
.map((l) => l.split(/=(.*)/s).slice(0, 2))
);
const url = state.URL;
/** Newest directory entry matching a pattern, or undefined. */
function newest(dir, re) {
if (!fs.existsSync(dir)) {
return undefined;
}
return fs
.readdirSync(dir)
.filter((d) => re.test(d))
.map((d) => path.join(dir, d))
.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)[0];
}
function loadPlaywright() {
const candidates = [
process.env.OUTLINE_VERIFY_PLAYWRIGHT,
path.join(state.SRC ?? "", "node_modules/playwright-core"),
path.join(state.SRC ?? "", "node_modules/playwright"),
];
const npx = path.join(os.homedir(), ".npm/_npx");
if (fs.existsSync(npx)) {
for (const d of fs.readdirSync(npx)) {
candidates.push(path.join(npx, d, "node_modules/playwright-core"));
}
}
const require = createRequire(import.meta.url);
for (const c of candidates) {
if (c && fs.existsSync(path.join(c, "package.json"))) {
return { lib: require(c), from: c };
}
}
throw new Error(
"playwright-core not found; set OUTLINE_VERIFY_PLAYWRIGHT=/path/to/node_modules/playwright-core"
);
}
function findChrome() {
if (process.env.OUTLINE_VERIFY_CHROME) {
return process.env.OUTLINE_VERIFY_CHROME;
}
const cache =
process.platform === "darwin"
? path.join(os.homedir(), "Library/Caches/ms-playwright")
: path.join(os.homedir(), ".cache/ms-playwright");
const dir = newest(cache, /^chromium-\d+$/);
if (!dir) {
return undefined;
}
const options = [
"chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
"chrome-mac/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
"chrome-linux64/chrome",
"chrome-linux/chrome",
].map((p) => path.join(dir, p));
return options.find((p) => fs.existsSync(p));
}
const journeyName = path.basename(journeyPath).replace(/\.m?js$/, "");
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
const outDir = path.join(state.EVIDENCE, `${journeyName}-${stamp}`);
fs.mkdirSync(outDir, { recursive: true });
const { lib, from } = loadPlaywright();
const executablePath = findChrome();
const browser = await lib.chromium.launch({ headless: !headed, executablePath });
const storage = path.join(runDir, "browser-state.json");
const context = await browser.newContext({
baseURL: url,
viewport: { width: 1400, height: 900 },
storageState: !fresh && fs.existsSync(storage) ? storage : undefined,
});
await context.tracing.start({ screenshots: true, snapshots: true });
const page = await context.newPage();
const consoleLines = [];
const networkLines = [];
page.on("console", (m) => {
if (m.type() === "error" || m.type() === "warning") {
consoleLines.push(`[${m.type()}] ${m.text()}`);
}
});
page.on("pageerror", (e) => consoleLines.push(`[pageerror] ${e.stack ?? e.message}`));
page.on("response", (r) => {
const u = r.url();
if (!u.startsWith(url) || !u.includes("/api/")) {
return;
}
const method = r.request().method();
if (r.status() >= 400 || method === "POST") {
networkLines.push(`${r.status()} ${method} ${u.slice(url.length)}`);
}
});
let n = 0;
const steps = [];
/** Screenshot a page (default: the journey page) as a numbered evidence step. */
async function step(name, target = page) {
n += 1;
const file = `${String(n).padStart(2, "0")}-${name.replace(/[^a-z0-9-]+/gi, "-")}.png`;
await target.screenshot({ path: path.join(outDir, file) });
steps.push(file);
console.log(` step ${file}`);
}
/**
* Click like a person: hover, pause, click. Sidebar links and document rows
* re-render on pointerenter, which swallows an instant Playwright click.
*/
async function click(locator) {
await locator.hover();
await page.waitForTimeout(300);
await locator.click();
}
/** Run read-only SQL against the instance database, returning trimmed rows. */
function psql(sql) {
return execFileSync(verifySh, ["psql", runId, sql], { encoding: "utf8" })
.split("\n")
.filter(Boolean);
}
/** Quote a string as a SQL literal for psql(). */
function literal(value) {
return `'${String(value).replace(/'/g, "''")}'`;
}
const log = (...a) => console.log(" ", ...a);
const journey = (await import(pathToFileURL(path.resolve(journeyPath)).href)).default;
let result = { journey: journeyName, url, ok: false };
console.log(`drive ${journeyName} -> ${url} (playwright ${from}, chrome ${executablePath ?? "default"})`);
try {
const value = await journey({ page, context, url, step, click, psql, literal, args, log });
result = { ...result, ok: true, value: value ?? null };
} catch (err) {
result.error = String(err?.stack ?? err);
await page.screenshot({ path: path.join(outDir, "FAILED.png") }).catch(() => {});
} finally {
await context.storageState({ path: storage }).catch(() => {});
await context.tracing.stop({ path: path.join(outDir, "trace.zip") }).catch(() => {});
await browser.close();
result.steps = steps;
fs.writeFileSync(path.join(outDir, "console.log"), consoleLines.join("\n") + "\n");
fs.writeFileSync(path.join(outDir, "network.log"), networkLines.join("\n") + "\n");
fs.writeFileSync(path.join(outDir, "result.json"), JSON.stringify(result, null, 2) + "\n");
}
console.log(`${result.ok ? "PASS" : "FAIL"} ${journeyName}; evidence: ${outDir}`);
if (!result.ok) {
console.error(result.error);
process.exit(1);
}
+278
View File
@@ -0,0 +1,278 @@
#!/usr/bin/env bash
# Launch, check and tear down an isolated Outline instance for verification.
#
# Usage:
# verify-outline.sh up [run-id] snapshot the checkout, build, migrate, start
# verify-outline.sh doctor <run-id> read-only health check of that instance
# verify-outline.sh info <run-id> print URL, ports and paths for that instance
# verify-outline.sh logs <run-id> [n] tail the server log
# verify-outline.sh psql <run-id> <sql> run read-only SQL against the instance DB
# verify-outline.sh down <run-id> stop and remove what `up` created, keep evidence
# verify-outline.sh list list runs and their containers
#
# Each run gets its own source snapshot, Postgres + Redis containers, free
# port and file storage. It never touches the developer's dev server, the
# docker-compose databases, or the repo's .env files.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO="${OUTLINE_REPO:-$(git rev-parse --show-toplevel 2>/dev/null || (cd "$SCRIPT_DIR/../../../.." && pwd))}"
ROOT="${OUTLINE_VERIFY_ROOT:-$HOME/.cache/outline-verify}"
PG_IMAGE="${OUTLINE_VERIFY_PG_IMAGE:-postgres:latest}"
REDIS_IMAGE="${OUTLINE_VERIFY_REDIS_IMAGE:-redis:latest}"
die() { echo "error: $*" >&2; exit 1; }
log() { echo "[verify-outline] $*" >&2; }
run_dir() { echo "$ROOT/runs/$1"; }
evidence_dir() { echo "$ROOT/evidence/$1"; }
load_state() {
local id="${1:-}"
[[ -n "$id" ]] || die "run-id required (see: $0 list)"
local state
state="$(run_dir "$id")/state.env"
[[ -f "$state" ]] || die "no run '$id' at $state"
# shellcheck disable=SC1090
source "$state"
}
# Exec a command in the snapshot with only this instance's env. The repo's
# .env files are never read: they hold real S3 and OAuth credentials. The
# global rate limit is raised because every static asset of the production
# build counts against it; per-endpoint limits stay as in production. It
# replaces the current shell: call it as `(in_instance ...)` or with `&`.
in_instance() {
cd "$SRC"
exec env -i PATH="$PATH" HOME="$HOME" \
NODE_ENV=production PORT="$PORT" URL="$URL" FORCE_HTTPS=false \
DATABASE_URL="$DATABASE_URL" PGSSLMODE=disable REDIS_URL="$REDIS_URL" \
SECRET_KEY="$SECRET_KEY" UTILS_SECRET="$UTILS_SECRET" \
FILE_STORAGE=local FILE_STORAGE_LOCAL_ROOT_DIR="$RUN_DIR/storage" \
WEB_CONCURRENCY=1 TELEMETRY=false LOG_LEVEL=info \
RATE_LIMITER_REQUESTS=100000 \
"$@"
}
free_port() {
python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1]); s.close()'
}
cmd_up() {
local id="${1:-v$(date +%Y%m%d-%H%M%S)}"
[[ "$id" =~ ^[a-z0-9-]+$ ]] || die "run-id must match [a-z0-9-]+"
local dir src ev
dir="$(run_dir "$id")"
src="$dir/src"
ev="$(evidence_dir "$id")"
[[ -e "$dir/state.env" ]] && die "run '$id' already exists; use doctor, or down it first"
[[ -d "$REPO/node_modules" ]] || die "$REPO/node_modules missing; run yarn install there"
docker info >/dev/null 2>&1 || die "docker is not running (colima start?)"
mkdir -p "$dir/storage" "$ev"
log "snapshot $REPO -> $src"
rsync -a --delete \
--exclude node_modules --exclude /build --exclude /.git --exclude /data \
--exclude '/.env*' --exclude /.claude --exclude /.cursor --exclude /.conductor \
--exclude /server/config/certs --exclude '.DS_Store' \
"$REPO/" "$src/"
ln -sfn "$REPO/node_modules" "$src/node_modules"
{
echo "repo: $REPO"
git -C "$REPO" rev-parse HEAD
git -C "$REPO" status --porcelain
} >"$dir/source.txt" 2>/dev/null || true
cp "$dir/source.txt" "$ev/source.txt"
# A checkout whose package.json is ahead of or behind its node_modules builds
# with confusing resolver errors; fail fast instead.
local missing
missing="$(cd "$src" && node -e '
const p = require("./package.json");
const deps = Object.keys({ ...p.dependencies, ...p.devDependencies });
const fs = require("fs");
console.log(deps.filter((d) => !fs.existsSync(`node_modules/${d}/package.json`)).join(" "));
')"
[[ -z "$missing" ]] || { rm -rf "$dir"; die "node_modules in $REPO does not match its package.json (missing: $missing); run yarn install there or use a checkout that matches"; }
# Write state before any container starts, so `down` can always clean up.
local pg="outline-verify-$id-pg" redis="outline-verify-$id-redis" port
port="$(free_port)"
cat >"$dir/state.env" <<EOF
RUN_ID=$id
RUN_DIR=$dir
SRC=$src
EVIDENCE=$ev
PORT=$port
URL=http://localhost:$port
PG_CONTAINER=$pg
REDIS_CONTAINER=$redis
SECRET_KEY=$(openssl rand -hex 32)
UTILS_SECRET=$(openssl rand -hex 32)
SERVER_LOG=$dir/server.log
PID_FILE=$dir/server.pid
EOF
docker run -d --name "$pg" --label outline-verify="$id" \
-e POSTGRES_USER=user -e POSTGRES_PASSWORD=pass -e POSTGRES_DB=outline \
-p 127.0.0.1::5432 "$PG_IMAGE" >/dev/null
docker run -d --name "$redis" --label outline-verify="$id" \
-p 127.0.0.1::6379 "$REDIS_IMAGE" >/dev/null
log "started containers $pg, $redis"
local pg_port redis_port
pg_port="$(docker port "$pg" 5432/tcp | head -1 | sed 's/.*://')"
redis_port="$(docker port "$redis" 6379/tcp | head -1 | sed 's/.*://')"
cat >>"$dir/state.env" <<EOF
DATABASE_URL=postgres://user:pass@127.0.0.1:$pg_port/outline
REDIS_URL=redis://127.0.0.1:$redis_port
EOF
load_state "$id"
# The postgres image runs its init scripts on a socket-only server, so a
# TCP query only succeeds once the real server is up.
log "waiting for postgres and redis"
local i
for i in $(seq 1 60); do
docker exec "$PG_CONTAINER" psql -h 127.0.0.1 -U user -d outline -tAc 'select 1' >/dev/null 2>&1 && break
[[ $i == 60 ]] && die "postgres not ready after 60s"
sleep 1
done
for i in $(seq 1 30); do
docker exec "$REDIS_CONTAINER" redis-cli ping 2>/dev/null | grep -q PONG && break
[[ $i == 30 ]] && die "redis not ready after 30s"
sleep 1
done
log "building server (swc)"
(cd "$SRC" && node build.js) >"$RUN_DIR/build-server.log" 2>&1 ||
die "server build failed, see $RUN_DIR/build-server.log"
log "building frontend (vite)"
(cd "$SRC" && NODE_ENV=production VITE_CJS_IGNORE_WARNING=true node_modules/.bin/vite build) \
>"$RUN_DIR/build-app.log" 2>&1 || die "frontend build failed, see $RUN_DIR/build-app.log"
log "migrating database"
(in_instance node_modules/.bin/sequelize db:migrate --env production-ssl-disabled) \
>"$RUN_DIR/migrate.log" 2>&1 || die "migration failed, see $RUN_DIR/migrate.log"
log "starting server on $URL"
in_instance nohup node build/server/index.js \
--services=web,websockets,collaboration,worker,cron >"$SERVER_LOG" 2>&1 &
echo $! >"$PID_FILE"
for i in $(seq 1 90); do
if ! kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
tail -40 "$SERVER_LOG" >&2
die "server exited during startup, see $SERVER_LOG"
fi
if [[ "$(curl -s -o /dev/null -w '%{http_code}' "$URL/_health")" == 200 ]] &&
curl -s "$URL/" | grep -q '/static/assets/index\.'; then
log "READY $URL (run-id: $id)"
cmd_info "$id"
return 0
fi
sleep 1
done
die "server not ready after 90s, see $SERVER_LOG"
}
cmd_doctor() {
load_state "$1"
local rc=0 pid tmp
pid="$(cat "$PID_FILE" 2>/dev/null || echo none)"
tmp="$(mktemp)"
check() {
if eval "$2" >/dev/null 2>&1; then echo "ok $1"; else echo "FAIL $1"; rc=1; fi
}
check "server pid $pid alive" "[[ $pid =~ ^[1-9][0-9]*$ ]] && kill -0 $pid"
check "port $PORT listened on by our process tree" \
"lsof -nP -iTCP:$PORT -sTCP:LISTEN -t | grep -qxF \"\$(tree $pid)\""
check "server cwd is snapshot" "lsof -a -p $pid -d cwd -Fn | grep -qx 'n$SRC'"
check "postgres container running" "[ \"\$(docker inspect -f '{{.State.Running}}' $PG_CONTAINER)\" = true ]"
check "redis container running" "[ \"\$(docker inspect -f '{{.State.Running}}' $REDIS_CONTAINER)\" = true ]"
check "GET /_health = 200 (db + redis)" "[ \"\$(curl -s -o /dev/null -w '%{http_code}' $URL/_health)\" = 200 ]"
check "GET / serves the built SPA" "curl -s $URL/ | grep -q '/static/assets/index\.'"
check "no pending migrations" \
"(in_instance node_modules/.bin/sequelize db:migrate:status --env production-ssl-disabled) >$tmp && grep -q '^up ' $tmp && ! grep -q '^down ' $tmp"
rm -f "$tmp"
echo "info teams=$(cmd_psql "$1" 'select count(*) from teams' 2>/dev/null || echo '?') users=$(cmd_psql "$1" 'select count(*) from users' 2>/dev/null || echo '?') (teams=0: / shows workspace setup)"
if [[ "$(wc -l <"$RUN_DIR/source.txt")" -ge 2 ]]; then
echo "info snapshot: $(sed -n 2p "$RUN_DIR/source.txt") + $(($(wc -l <"$RUN_DIR/source.txt") - 2)) uncommitted paths from $(sed -n 1p "$RUN_DIR/source.txt" | cut -d' ' -f2)"
else
echo "info snapshot: $(sed -n 1p "$RUN_DIR/source.txt" | cut -d' ' -f2) (not a git checkout)"
fi
return $rc
}
cmd_info() {
load_state "$1"
cat <<EOF
RUN_ID=$RUN_ID
URL=$URL
EVIDENCE=$EVIDENCE
SERVER_LOG=$SERVER_LOG
STORAGE=$RUN_DIR/storage
DATABASE_URL=$DATABASE_URL
PG_CONTAINER=$PG_CONTAINER
EOF
}
cmd_logs() {
load_state "$1"
tail -n "${2:-100}" "$SERVER_LOG"
}
cmd_psql() {
load_state "$1"
[[ -n "${2:-}" ]] || die "sql required"
docker exec "$PG_CONTAINER" psql -h 127.0.0.1 -U user -d outline -v ON_ERROR_STOP=1 \
-c 'SET default_transaction_read_only = on' -tA -c "$2" | sed '/^SET$/d'
}
# Print a pid and all of its descendants.
tree() {
local p
echo "$1"
for p in $(pgrep -P "$1" || true); do tree "$p"; done
}
cmd_down() {
load_state "$1"
local pid pids
pid="$(cat "$PID_FILE" 2>/dev/null || true)"
if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then
# throng forks a worker; stop the tree we started, never by process name.
pids="$(tree "$pid" | tr '\n' ' ')"
kill $pids 2>/dev/null || true
for _ in $(seq 1 10); do kill -0 $pids 2>/dev/null || break; sleep 1; done
kill -9 $pids 2>/dev/null || true
log "stopped server pids $pids"
fi
if lsof -nP -iTCP:"$PORT" -sTCP:LISTEN >/dev/null 2>&1; then
log "WARNING: port $PORT still has a listener; inspect with lsof before killing anything"
fi
docker rm -f "$PG_CONTAINER" "$REDIS_CONTAINER" >/dev/null 2>&1 || true
log "removed containers"
mkdir -p "$EVIDENCE"
cp "$SERVER_LOG" "$EVIDENCE/server.log" 2>/dev/null || true
rm -rf "$RUN_DIR"
log "removed $RUN_DIR; evidence kept at $EVIDENCE"
ls -la "$EVIDENCE"
}
cmd_list() {
echo "runs:"
ls -1 "$ROOT/runs" 2>/dev/null | sed 's/^/ /' || true
echo "containers:"
docker ps -a --filter label=outline-verify --format ' {{.Names}}\t{{.Status}}'
}
case "${1:-}" in
up) cmd_up "${2:-}" ;;
doctor) cmd_doctor "${2:-}" ;;
info) cmd_info "${2:-}" ;;
logs) cmd_logs "${2:-}" "${3:-}" ;;
psql) cmd_psql "${2:-}" "${3:-}" ;;
down) cmd_down "${2:-}" ;;
list) cmd_list ;;
*) sed -n '2,13p' "$0"; exit 1 ;;
esac