10 Commits

Author SHA1 Message Date
c3b7edcf6d feat(console): GET /api/v1/rail/status, one aggregated health check for the rail
Consumer products (Rally, Menivor, Scribase, ...) and operators currently
have no single place to ask "is the rail actually up" -- they'd have to
probe Mint, Rago, Relay and Abacus separately before routing real traffic.

Adds lib/rail-status.ts (pure, injectable fetch per the repo's own transport
invariant) that checks every configured service in parallel with a bounded
per-service timeout, and GET /api/v1/rail/status that wires it to four new
optional env vars (MINT_HEALTH_URL, RAGO_HEALTH_URL, RELAY_HEALTH_URL,
ABACUS_HEALTH_URL -- unset services read "not_configured" and are excluded
from the verdict, so this degrades cleanly on any partial deployment).
Overall reads ok/degraded/down/unconfigured; HTTP status is 200 for
ok/degraded and 503 for down/unconfigured so a caller that only checks the
status code still gets the right answer without parsing the body.

TDD: 7 new tests in lib/rail-status.test.ts (all services healthy, one down
degrades the rest, a thrown network error reads down not an unhandled
rejection, a hung service times out instead of blocking forever, an unset
service skips the network call and is excluded from the verdict, zero
configured services reads unconfigured not a false ok, every service down
reads down). Full console suite: 166 pass (164 + the pre-existing env-only
failure in add-app-component.test.ts, unrelated -- missing root node_modules
in this sandbox, not a code regression).

Not deployed: the console Worker's deploy needs
~/.config/products-keys/railyard-console.env (not present on this machine)
and a working wrangler/pnpm toolchain (corepack's pnpm cache is broken here,
and the workspace root node_modules does not exist), so this could not be
shipped to railyard.ereboslab.com from this session -- noted in NOTES.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-21 18:39:35 +03:00
65acbbd9a3 feat(insights): page speed per app with deploy markers, a web package that measures it, and the join to errors (PY3.3)
RYP-G3 in Wave P.
- @railyard/insights-web: page views (with client-side route changes),
  events, identify, and LCP, INP, CLS, FCP and TTFB per page view, sent once
  when the page is hidden or the route changes; no cookies, no storage, Do
  Not Track and consent respected. src/metrics.ts adapts MIT-licensed code
  (NOTICE keeps the licence) with two changes that match Chrome's field
  reporting: LCP stops at the first input, and INP picks its percentile from
  the page's interaction count. On six worked fixtures (after-click paint,
  two shift windows with a post-input shift, prerender activation, 120
  interactions, multi-event interactions) every metric and the p75 are
  within 10% of Chrome's values.
- Edge collector and ingest carry `performance` events (the five metrics,
  in the upstream ranges) into upstream event type 5 rows.
- Insights GET /api/v1/tenants/{org}/vitals: p75 per app, per UTC day, and
  in the day before and after each given deploy time (up to 10); ratings
  from the published thresholds; org-scoped (SQL test with hand p75s).
- Console: the Page speed screen (only with RAILYARD_REPLAY_LIVE=1) and the
  Scribase bridge `insights` answer gain `vitals` (p75 cells and one marker
  per deploy from the console's own deploy records, so a deploy is marked on
  the next read); a vitals failure never hides the rest of the tab.

The Scribase Analytics sub-tab (carve-out) joins these markers to the
environment's error issues: "This deploy raised errors by N" links to the
Errors tab.

Tests: console 128/128 (view model, bridge marker, flag gate, copy lint),
insights-web 12/12 (fixtures, client, copy), insights fork 12/12, edge
19/19, tsc clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 04:05:42 +03:00
6baaadf91a feat(insights): identify and people, saved cohorts, retention by property, breakdowns, CSV and JSON export, delete by user (PY3.2)
RYP-F1 in Wave P. Everything scoped by the org through website.team_id with
bound parameters only; tested at the SQL level on a throwaway cluster with
the upstream migrations plus the fork's 90 and 91.

- Identify: the edge collector (contract v1.1, additive) and the page tag
  accept `identify(userId, traits)` and a `user` on any event. Insights links
  the session (upstream session_link and session.distinct_id) and keeps one
  profile per (app, user) with first and last seen and merged traits
  (migration 91_railyard_people). Before this, an identify from the collector
  made Insights refuse the whole batch.
- Saved cohorts: performed (with min times), not performed, trait equals and
  first seen within; counts are live. On fixtures a cohort equals a
  hand-written SQL count (two definitions).
- Retention by property (country, language, screen, trait.<key>; day or week
  periods), breakdowns (path, referrer, country, language, screen, event,
  hostname, data.<key>, trait.<key>).
- Export: events (31 days) or profiles, JSON or CSV, 100,000 rows; formula
  cells defused.
- Delete by user id: one statement removes events, event data, session data,
  revenue, replay and heatmap rows, links, sessions and the profile in the
  org's apps only; recorded in railyard_erasure; a pending request is retried
  by POST /api/v1/erasure/sweep (hourly), so it is done within 24 h.
- Console /api/v1/insights/* for an org's ry_ token: the org comes from the
  token, app names resolve to the org's own app, the platform token never
  leaves; served only with RAILYARD_REPLAY_LIVE=1 (denylist rule
  railyard-slot-replay), else 503 "arriving".
- New packages: @railyard/insights-react-native (offline queue, identify kept
  across restarts, reset, consent) and @railyard/insights-server (server
  track and identify; profiles, cohorts, retention, breakdown, export,
  deleteUser through the console). No dependencies.

Env: RAILYARD_REPLAY_LIVE (console). Migration: insights
91_railyard_people (idempotent; scratch Postgres only).

Tests: insights fork 9/9 (depth SQL incl. isolation, cohort vs hand SQL,
erasure), edge 18/18, console 125/125 (tsc clean), RN 3/3, server 5/5
(incl. copy lint), CLI 18/18. The upstream vitest suite runs in the image
build on box 2 or CI (not on the Mac).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 03:35:37 +03:00
014f62b224 feat(ship): ship on push through the customer's own GitHub Actions and Cloudflare, with no token shown (PY3.1)
RYP-E3 in Wave P. ADR RY-0004 records the evidence that path A exists
(Cloudflare self-managed OAuth clients, changelog 2026-06-03, authorization
code flow only) and builds it; path B stays the written fallback; path C
stays rejected.

- railyard link: one URL; at most two consents in the browser (install the
  Railyard GitHub App on the repo, then Cloudflare's own consent screen with
  PKCE), each skipped when done before; then one pull request from the App on
  railyard/ship-on-push adding .github/workflows/railyard.yml. Nothing is
  pushed to a default branch. The installation id GitHub sends back is not
  trusted; the App's view of the repo decides.
- The workflow holds no key: it asks GitHub for an OIDC token (audience = the
  console) and runs `railyard ci`. The console checks issuer, audience,
  expiry and signature, the stable repository_id, the Railyard workflow ref
  only, push/workflow_dispatch on branches only, and a paused org; it answers
  with a short-lived Cloudflare access token (sealed refresh token rotated and
  resealed; a cached access token reused while 10 min are left).
- railyard ci masks the token first, deploys exactly like railyard deploy,
  never opens a login, and reports with a fresh OIDC token. The console
  records the deploy (branch and commit from the token) and writes one
  preview comment on the branch's pull request, edited on later pushes.
- Signed App webhooks drop links on uninstall or repo removal.
- GET /api/v1/github/manifest creates the App (owner item Y4); the done page
  shows one command that pipes the App key into wrangler secrets.
- Migration 0007_ship.sql (idempotent; scratch Postgres only): installations,
  links (one per repo), sealed Cloudflare grants, link sessions; RLS on, no
  anon/authenticated grants.
- Off until RAILYARD_SHIP_ON_PUSH_LIVE=1 and every name is set (routes 503;
  copy stays "arriving" under denylist rule railyard-slot-ship-on-push).

Env: RAILYARD_SHIP_ON_PUSH_LIVE, GITHUB_APP_ID, GITHUB_APP_SLUG,
GITHUB_APP_PRIVATE_KEY, GITHUB_APP_WEBHOOK_SECRET, CLOUDFLARE_OAUTH_CLIENT_ID,
CLOUDFLARE_OAUTH_CLIENT_SECRET, CLOUDFLARE_OAUTH_SCOPES (optional); reuses
RAILYARD_CREDENTIALS_KEY.

Tests: console 122/122 (ship 12, migration 0007 on a scratch cluster), tsc
clean; CLI 18/18 (link and ci 5, copy lint). The 5-minute push-to-live run on
a real repo and Cloudflare account is owner-run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 03:10:35 +03:00
5ccd834941 feat(watch): uptime checks with a public status page per app and owner email through Rally Send (PY2.2)
RYP-E4, dispatch 4.2 PY2.2 (Railyard side):
- lib/watch: checks (public https app addresses only; IPs, private names and
  our own hosts refused), 20 per org, a status page slug each. The box 1
  agent reads GET /api/v1/watch/agent/checks (ids and URLs only, bearer
  WATCH_AGENT_TOKEN) and posts results to /api/v1/watch/agent/results.
  Two failures in a row turn a check red; each change emails the owner once
  through Rally Send (product railyard, from status@, idempotency key per
  change; a failed send is retried on the next result). Older, unknown and
  future results change nothing.
- /status/<slug>: live results only (state, share of the last checks, bars),
  the check's name and never its address or any host or vendor name.
- The Watch screen: add by address, pause or resume, open the status page.
- Bridge route uptime (contract cases, uptime_check_keys): a check for the
  given address, or the app's latest live deploy; the first result is the
  slot's proof (check_result).
- Gated on RAILYARD_WATCH_LIVE (denylist rule railyard-slot-watch): off, no
  check runs, the pages 404, the nav has no Watch item and the slot answers
  arriving. The copy test lints each gated surface with the flag and proves it
  checks the flag first.
- Migration 0006 (watch_checks, watch_status; https only, history capped at
  90, cascades with the org).

Tests: watch 10/10, bridge 25/25, contract 3/3, migration 7/7 (0006 twice on a
scratch cluster), watch copy 7/7, console 108/108 with the bundle build,
tsc clean, SDK 7/7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:24:06 +03:00
332446652a feat(flags): Railyard Flags behind the add-on, the Flags screen and the OpenFeature SDK (PY2.1)
RYP-E2 and SP-E6, dispatch 4.2 PY2.1 (Railyard side):
- lib/flags: flag environments per app environment (a Scribase environment
  or branch), each with a public client key that reads that one environment.
  Two backends, one surface: the unmodified Flagsmith server (one Flagsmith
  organisation per Railyard org, a project per app, an environment per env;
  FLAGS_API_URL + FLAGS_ADMIN_TOKEN) and, as the fallback the dispatch names
  when the box 2 gate keeps Flagsmith down, the console's own tables
  (migration 0005). An environment keeps the backend it was made on.
- A branch environment starts with its parent's flags (copy_from), then
  changes alone.
- GET /api/v1/flags/client?key=: CORS-open, cached 15 s when keyed by URL;
  the first read by an app is the slot's proof (first_flag_read).
- Bridge route flags (contract: id_format, three cases, flags_item_keys);
  BRIDGE_SLOTS.flags landed.
- The Flags screen (nav item) flips with one click and adds a flag by key;
  POST /api/flags writes only the signed-in org's environments.
- packages/openfeature-railyard: a zero-dependency polling client (30 s,
  offline start from storage, back-off) and OpenFeature client and server
  providers, with Expo and Next.js examples.

Tests: flags core 11/11 (both backends, a fake of the Flagsmith API, tenant
isolation, branch copies, a 502 that leaves nothing half made), bridge 19/19,
contract 3/3, migration 6/6 (0005 twice on a scratch cluster), console 85/85
with the bundle build, tsc clean, SDK 7/7 (a flip reaches the app within 60 s
in the worst cache timing on a fake clock; copy lint on docs and the screen).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 23:58:12 +03:00
4016a68d18 feat(ai): BYOK AI gateway for Scribase projects with per-key caps, traces and a secure connect page (PY1.4)
Railyard side of PY1.4 (ADR RY-0003). Acceptance:
1. Bridge `ai` gives a Scribase project environment one key (ry_ai_..., shown
   once, to the Scribase control plane only, stored here as SHA-256; `rotate`
   revokes the old one) and a one-time link to /connect/ai (15 minutes), the
   only place a provider key is typed. It is sealed with AES-256-GCM under
   RAILYARD_CREDENTIALS_KEY, bound to org and provider, and only a
   four-character hint is ever read back.
2. BYOK only: POST /api/v1/ai/chat/completions (OpenAI-compatible) refuses
   with 403 byok_required when the org has not connected the provider the
   model names, and never calls Relay then. When it does call, the customer's
   key fills that provider's slot and every other slot carries a refusal
   marker, so Relay (caller credential wins) can never use our keys, not even
   on failover; a test pins the slot list to Relay's PROVIDER_KEY_SLOTS.
   Credentials in a request body are refused.
3. Daily and monthly token caps per key (429 with the period); usage (atomic
   rpc) and one trace per call (model, provider, status, tokens, latency),
   read per project key by the bridge `ai_usage` route for the Scribase tab;
   Relay traces carry tensorzero::tags for the same filter.
4. Copy says "your provider bills you directly"; no credits are included
   anywhere (copy lint over the connect page and every gateway message).
apps/relay/config/tenants/README.md records the tenant rules.

Migration: apps/console/db/migrations/0003_ai_gateway.sql (idempotent;
applied twice to a scratch local cluster by test/migration.test.ts).
Env: RELAY_URL (var), RELAY_TENANT_KEY, RAILYARD_CREDENTIALS_KEY (secrets).

Tests: console 63/63 (gateway 6, bridge 12, migration 3, repo 5), tsc clean,
tests/contract 3/3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:44:04 +03:00
71336987dd feat(bridge): Scribase bridge creates the bound Railyard org, one-time CLI claims and slot proofs; denylist 2026-09-29.3 (PY1.0)
PY1.0 acceptance (C8 delta check on main f919636; Wave E Y-0 to Y-5 merged):
1. Denylist .3 (gtm/policy, published by this package) adds portfolio-ott-drm
   and portfolio-ott-comparison (DRM, Netflix-style, your own Netflix beyond
   Menivor), addon-unlaunched (ADDON_LIVE), rally-capacity-purchase
   (RALLY_CAPACITY_PURCHASE_LIVE) and at-cost (allowed only next to a live
   price source). Re-vendored byte for byte; every new rule has failing
   fixtures (policy/test/fixtures/denylist-3-new-phrases.json); .2 fixtures kept.
2. apps/console/app/api/v1/bridge/scribase/{orgs,claims,proof}: signed
   (Standard Webhooks, RAILYARD_SCRIBASE_BRIDGE_SECRET), replay-proof calls from
   Scribase control-api. The first call creates the Railyard org bound to the
   Scribase org id (deterministic owner id, no second sign-up) and mirrors the
   add-on into the entitlement (plan "addon"); a lapsed add-on pauses the org
   and keeps its data. Keys go only to the Scribase CLI: a claim is a one-time,
   pre-approved device code (120 s) exchanged at /api/v1/device/token; a grep
   test keeps every bridge handler free of stdout, stderr and log writes.
3. proof answers {slot, state, live, proof:{kind,id,at}, next}; slots whose
   package has not landed answer "arriving".
Contract: tests/contract/fixtures/scribase-bridge/contract.json, run by
tests/contract/scribase-bridge.test.ts; the Scribase carve-out tests the same file.

Migration: apps/console/db/migrations/0002_scribase_bridge.sql (idempotent;
applied twice to a scratch local cluster only by test/migration.test.ts).
Env: RAILYARD_SCRIBASE_BRIDGE_SECRET (secret; unset keeps the bridge off).

Tests: console npm test 48/48, tests/contract 2/2, policy 11/11, cli 9/9, mcp 9/9,
tsc --noEmit clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 18:39:24 +03:00
eb26c4d38a feat(cli): railyard deploy with branch previews, deploy records and rollback (RYP-D4, Y-3)
npx railyard (zero dependencies):
- login: device flow against the console; the org token is saved 0600
  and never printed; no option takes a key or token.
- deploy: detects Next.js (OpenNext build for Workers), Vite, Astro
  (static output) or plain static; anything else stops with one line
  that says what to change (SvelteKit, Remix, Nuxt, server Astro...).
  Uses wrangler's own OAuth login on the user's machine, names the
  Worker <app> on main and <app>-<branch> elsewhere, and records URL,
  commit, branch, framework, duration and status in the console.
- rollback: wrangler rollback to the previous successful version id of
  the same branch, recorded with rollback_of.
- deploys: lists recent deploys.

Console: /api/v1/deploys (POST record, GET list) and /api/v1/deploys/:id
with org-scoped bearer tokens; the first deploy of a new app name creates
the app within the plan's limits; a paused or card-less org is refused
with 402. The Apps screen lists recent deploys.

Tests: the CLI runs against a mocked wrangler and the real console
device-flow and deploy code over local HTTP (login, main deploy, branch
preview, records, rollback, OpenNext path, failure, refusals, no token
in any output); deploy service tests cover org isolation and input
validation; README and CLI strings pass the copy lint. The run on a
real Cloudflare account is owner-run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:54:03 +03:00
247e860a16 feat(console): Railyard console with Scribase sign-in and the Dodo test-mode money ladder (RYP-D1, Y-2)
Next.js console for Cloudflare Workers (OpenNext config, wrangler.jsonc)
with data in the console's own Scribase project, schema railyard
(migration 0001: orgs, org_members, apps, deploys, entitlements,
billing_events, api_tokens, device_codes; idempotent, RLS on, no anon
grants).

- Sign-in with Google or GitHub through Scribase Auth (PKCE), user read
  from the auth server, org and entitlements row created, signed
  HttpOnly session.
- Money ladder (pure, immutable): $1 card check credited back to the
  customer wallet, 14-day trial with the plan's limits, $19 a month or
  $190 a year, pause switch and one-click cancel (ends at the next
  billing date; a trial ends now).
- Webhook: Standard Webhooks signature and timestamp verified, replays
  ignored by unique message id, signed checkout metadata, other brands
  ignored, a refund of the card check reverses the credit and the
  trial, a failed wallet call releases the id for the provider's retry.
- Apps, Usage and Billing screens, one primary action each; Add app
  shows the deploy command and the Insights tag in two clicks.
- CLI device-flow login and org-scoped hashed tokens for Y-3.
- Test mode only: the live payment host is refused unless the owner
  sets RAILYARD_DODO_LIVE=1.

Tests (node --test, 25): journey from sign-in to entitlements and the
snippet, refund, pause and cancel, webhook security, ladder, tokens and
org isolation, PostgREST repo, a component test of Add app with the copy
lint, a next build grep for sentinel secrets in the client bundle, and
the migration applied twice on a scratch Postgres.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:35:24 +03:00