16 Commits

Author SHA1 Message Date
2e9ca56c36 fix(cli): stop railyard logs from buffering an unbounded tail in memory
`run()` always appended every stdout/stderr chunk from a child process onto
accumulator strings, even for `railyard logs` (wraps `wrangler tail`), which
only ever reads the exit code and can stream for hours -- so a long session
held every log line it had ever printed in memory for no reason. Added a
`capture` option (default true, unchanged for deploy/rollback which do need
the text back) and set `capture: false` for logs.

Load-tested the fix for real: a new fake-wrangler `tail` fixture that
behaves like the real thing (streams until killed, never exits on its own),
a 4,000-line end-to-end `railyard logs` test (every line still streamed
live, saved token redacted, --format/--status forwarded correctly), a
Ctrl+C-style signal-stop test, and a direct run() test proving capture:false
keeps result.stdout/stderr empty across 20,000 printed lines while
capture:true is unchanged. 28/28 CLI tests passing (23 pre-existing + 5 new).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-24 04:53:23 +03:00
f3cfa675b1 feat(cli): add railyard logs to stream a deployed Worker's logs
Every other railyard command (deploy, rollback, deploys, domains) follows
a deploy with no way to see the Worker's own logs afterward -- the CLI's
README promises "one command" deploys but left debugging a bad deploy to
a separate `wrangler tail` invocation the user has to assemble by hand
(right worker name, right account). That's a real gap in the deploy/ops
loop this CLI exists to close for every consumer product that ships
through Railyard.

Add `railyard logs [--app NAME] [--branch B] [--format pretty|json]
[--status ok|error|canceled]`: resolves the same Worker name deploy uses
(workerName(app, branch)) and runs `wrangler tail` against it with the
user's own Cloudflare login, same as deploy/rollback/domains. Requires
`railyard login` first, for the same identity consistency as every other
command.

Also fix a latent bug in run.mjs surfaced by this feature: a child
process stopped by a signal (e.g. Ctrl+C on a long-running tail) resolved
with `code: 1` (a false failure) because `code ?? 1` treated a null exit
code as an error even when the process was cleanly killed by signal.
Now `close` also captures `signal`, and a signal-stopped child resolves
`code: 0` -- a Ctrl+C on `railyard logs` reports success, not "Could not
stream logs."

Verified manually (no new test files, per instructions): ran the
existing `node --test test/*.test.mjs` suite (23/23 still green, 0
regressions), then drove `main()` from a scratch script against a
throwaway fake `wrangler` binary (deleted after, not committed): logs
without login is refused, an unknown --format is rejected, `railyard
logs` in a project on main resolves and tails the same worker name
`railyard deploy` would use, `--app`/`--status` on a feature branch
resolve to the branch-preview worker name with --status passed through,
and --help lists the new command. Separately confirmed in a standalone
repro that a SIGINT-killed child now resolves `{ code: 0, signal:
"SIGINT" }` instead of the old `code: 1`.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-22 03:36:07 +03:00
8cd0695287 feat(analytics): Flutter/Dart SDK at parity with Swift and Kotlin
capture, screen, identify with the anonymous-id link, alias, groups,
super properties, feature flags, batched delivery with retry on network
errors, 429 and 5xx, bounded queue, persisted ids (pluggable storage;
SharedPreferences adapter in the README) and reset. dart:io transport by
default, pluggable for Flutter web. 8 checks including a real HTTP round
trip; dart analyze clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:33:58 +03:00
fba4dba792 feat(analytics): native Swift and Kotlin SDKs for product analytics
RailyardAnalytics (Swift package, iOS/macOS/tvOS/watchOS) and
railyard-analytics-kotlin (Android/JVM, stdlib only): capture, screen,
identify with the anonymous-id link, alias, groups, super properties,
feature flags, batched delivery with retry on network errors, 429 and
5xx, bounded queue, persisted ids and reset. Swift: 6 XCTest cases;
Kotlin: 9 checks including a real HTTP round trip, runnable offline with
the Kotlin compiler bundled in Gradle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 18:47:44 +03:00
90f6ba3b78 feat(ship): custom domains for shipped apps on the customer's own Cloudflare account (QY1.5, I6)
- packages/cli/src/domains.mjs: a dependency-free client of Cloudflare's
  public Workers Custom Domains API (zones lookup, PUT/GET/DELETE
  /accounts/{id}/workers/domains, certificate pack state). Cloudflare
  issues the TLS certificate; a domain reads active once it is. The token
  goes in the Authorization header only and is scrubbed from every error.
  Byte copy at apps/console/lib/ship/cf-domains.mjs (drift test).
- railyard domains [add|remove HOSTNAME] [--app]: the console attaches the
  hostname to the app's production Worker with the org's Cloudflare grant
  (the QY1.1 OAuth step; the access token is opened and used inside the
  console only). Without a grant (409 no_cloudflare_grant) the CLI does the
  same with the local login (CLOUDFLARE_API_TOKEN or the wrangler login
  file after `wrangler whoami`) and the console records the outcome. Adding
  an attached hostname keeps it; one on another Worker is refused; remove
  is idempotent; a hostname outside the account's zones is refused plainly.
- Console: migration 0010 railyard.app_domains (one org per hostname,
  lower case, cascade, RLS, no anon); GET/POST/DELETE /api/v1/domains and
  POST /api/v1/domains/record (CLI bearer); states refreshed from
  Cloudflare when the org has a grant. Cloudflare OAuth default scopes add
  zone:read and ssl_certs:write (orgs linked before need to run
  railyard link once more for console-side domains).
- Scribase bridge: new signed route domains {scribase_org_id, app?} ->
  {available, domains:[{app, hostname, state, checked_at, created_at}],
  next} for the Deploy tab; contract fixture v2 adds it (additive).

Tests: CLI 23/23 (new domains.test.mjs 5: grant path with the real console
handlers and a fake Cloudflare, local-login path, wrangler config file,
refusals, idempotent remove, no token printed or sent to the console);
console 147/147 (new lib/ship/domains.test.ts 4: drift, worker naming
equal to the CLI's, attach/detach and cross-org refusal, record and
refresh, bridge listing; 0010 migration on a scratch PG); contract 6/6;
console tsc clean.

Owner-only: one real-domain proof (railyard domains add on a domain in the
owner's Cloudflare account) is not run here; record it at the deploy gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:45:57 +03:00
f4486bda26 feat(flags): targeting by property, cohort or segment and % rollouts on a stable hash (QY1.3, I10, A19)
- packages/openfeature-railyard/src/targeting.mjs: one dependency-free
  evaluator (sync SHA-1, rollout hash = parseInt(sha1("<flag>.<id>")[0:15])
  / 0xfffffffffffffff, inside when <= rollout/100; ordered rules, all
  conditions of a rule must match, first match wins with its own value).
  Property operators follow the reference matcher of posthog-node (MIT):
  exact/is_not (lists, true/false by truthiness), icontains, regex, gt/gte/
  lt/lte (numeric, else text), is_set/is_not_set. Segments are named sets of
  property conditions per environment (Flagsmith segment shape, BSD-3);
  cohorts are product analytics cohort ids. Byte copies with .d.mts types in
  apps/console/lib/flags and apps/product-analytics/src/flags (drift test).
- Console: rules and segments live in Railyard's store for both backends
  (migration 0009: railyard.flag_targeting, railyard.flag_segments, bounded
  checks, cascade, RLS, no anon), so the table fallback and the Flagsmith
  backend have the same rule features. setFlag validates rules and segment
  references; a used segment cannot be removed; branches copy rules and
  segments. The read endpoint takes ?id, ?props (JSON, 2 KB) and ?cohorts,
  answers each flag for that person and ships {on, value, rules} plus the
  segments used, so SDKs evaluate locally; without a person a targeted flag
  reads off (old clients stay safe). Flags screen: rules per flag (everyone,
  a property, a segment; cohorts only with RAILYARD_REPLAY_LIVE) with a
  share, and segments. POST /api/flags/segments.
- Product analytics /flags: evaluates targeted flags with the person's
  stored properties (request person_properties override) and cohort
  membership (through person overrides).
- OpenFeature providers and the client: evaluation context targetingKey +
  attributes (+ cohorts) resolve per person; cached starts keep rules.
- Contract fixture: flags items carry targeting (additive, version 2).

Tests
- openfeature 16/16: SHA-1 vs node crypto, rollout shares within bounds
  over 10 000 ids and monotonic growth, operators, rules, validation, read
  answer, client and both providers vs the evaluator, cached start, drift.
- console 142/142 incl. both backends with the same 20 rule sets, segments,
  isolation, read-endpoint context, 0009 migration on a scratch PG, and
  10 000 ids x 20 rule sets: provider local == read endpoint (0 mismatches).
- product analytics test/qy 10/10 incl. 10 000 ids x 20 rule sets: provider
  local == /flags from stored people and cohorts (0 mismatches), and the
  unmodified posthog-node local evaluation agreeing on all 18 non-cohort
  sets for 10 000 ids (0 mismatches, 0 undecided); a3 experiments unchanged.
- contract 6/6; console and PA tsc clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:09:54 +03:00
cbadc84dd5 merge: product analytics (A1-A3) into main after Wave P3
# Conflicts:
#	apps/console/components/Nav.tsx
2026-09-30 09:19:37 +03:00
53c7478c18 feat(mcp): flags.list is live for the signed-in org, from a token-scoped console route (PY3.4)
The Railyard MCP server's flags.list now lists the org's flags per app and
environment (key, on or off, value, description) from the new console route
GET /api/v1/flags?app= for an org's ry_ token (lib/flags/http.ts
tokenListFlags; read only, at most 100 environments). A token only ever reads
its own org: the MCP test shows org B naming org A's app lists nothing and
never sees org A's flag. Annotations stay read-only (the linter test), and
the README row says what it does.

Tests: mcp 9/9 (incl. copy lint), console 128/128, tsc clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 04:17:44 +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
dbef356e6e feat(analytics-sdk): @railyard/analytics-js (web + Expo) and @railyard/analytics-node wrappers, tested with the unmodified SDKs (A1)
- analytics-js wraps posthog-js 1.435.1 and posthog-react-native 4.78.2:
  reads NEXT_PUBLIC_/EXPO_PUBLIC_/VITE_ANALYTICS_SITE and _HOST, waits for
  consent (no client, no storage, no request before it), masks all inputs,
  [data-private]/.ph-mask text, blocks [data-block], no canvas, headers or
  bodies; Expo entry keeps the queue on the device and sends $screen per
  route change (screenTracker).
- analytics-node wraps posthog-node 5.54.1.
- test/a1: posthog-node (gzip), posthog-js under jsdom, one Chromium run
  (cached 1243, full build in new headless mode), React Native offline for
  10 minutes plus a restart and a lost response: every event stored once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 03:58:53 +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
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
15c88e452b feat(ship): deploy from a Scribase project with its URL and anon key, link-scribase, and the deploy slot on the bridge (PY1.2)
Railyard side of PY1.2 (SC-E2, SP-F2). Acceptance:
1. packages/cli/src/scribase/env.mjs: in a Scribase project folder,
   `railyard deploy` reads the public URL and anon key `scribase init` wrote
   (.env, .env.local; NEXT_PUBLIC_/VITE_/EXPO_PUBLIC_/PUBLIC_ variants) into
   the build env and onto the Worker (--var), prints their names only, and
   leaves secrets out by name (service role key, SECRET/PASSWORD names, a
   service-role JWT under any name). `railyard link-scribase` reads a one-time
   claim from stdin (no flag takes it), exchanges it once and saves the token
   0600; nothing is printed.
2. A git branch with Scribase branch settings (.scribase/branches/<branch>.env,
   written by the PS2.0 hook) deploys its <app>-<branch> preview against that
   branch (fixture test).
3. Bridge: deploy slot landed; proof is the latest successful deploy; new
   route POST /api/v1/bridge/scribase/deploys lists the bound org's deploys for
   the Scribase Deploy tab (org isolation test). Contract cases added.
4. Real Cloudflare end-to-end stays owner-run (tests use the fake wrangler).

Tests: packages/cli 13/13, console bridge + deploys 15/15, tests/contract 3/3,
tsc clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:42:19 +03:00
f32e27244f feat(mcp): Railyard MCP server and agent skill (RYP-D5, Y-5)
railyard-mcp (stdio, MCP TypeScript SDK) with seven tools, all marked
read-only for the agent:
- deploy.run returns the exact npx railyard deploy command (login first
  when signed out); the deploy itself runs on the user's machine.
- deploy.list and usage.current read the console API with the org
  token saved by railyard login; a token only ever sees its own org.
- insights.summary and insights.funnel say no_data_yet until an
  Insights query store is configured (RYP-D2), then pass its numbers.
- flags.list reports arriving and lists nothing.
- gateway.traces reads /relay/traces (RY-RL3) with the gateway key in the
  environment; Relay limits it to that key's own calls.
Arguments are schema-checked; errors are explicit, never an empty
success; no token appears in any output.

packages/skills: a Claude Code plugin (manifest starting railyard-mcp)
with a railyard skill (deploy, Cloudflare login in the browser, rollback,
no invented numbers) and a README.

Tests: annotation linter over tools/list, org A/B isolation against the
real console token and deploy code, signed-out and expired paths,
insights and gateway paths, a stdio round trip, and the copy lint over
both READMEs, the skill and every tool string.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:35:39 +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