Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 143 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
name: CI

on:
push:
branches: [main]
pull_request:

# PR runs share a group per ref and superseded runs are cancelled (each
# push re-plans anyway), which stops stale fan-outs from starving the
# runner pool. Main pushes get a unique group each: convergence runs plan
# --changed per commit, and GitHub replaces *pending* runs in a shared
# group even with cancel-in-progress false — a superseded main run's
# components would silently never converge.
concurrency:
group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}

permissions:
contents: read
packages: write
id-token: write

jobs:
plan:
runs-on: ubuntu-latest
outputs:
job-matrix: ${{ steps.matrix.outputs.job-matrix }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- uses: sourceplane/orun-action@v1.2.0
with:
version: v2.56.2
- env:
# Surface the best-effort catalog auto-sync (execution.state.autopushCatalog).
# A successful push prints "✓ pushed catalog …"; ORUN_VERBOSE also makes
# any skip/failure visible instead of silent.
ORUN_VERBOSE: "1"
run: |
set -euo pipefail

plan_args=(
--from-ci github
--event-file "$GITHUB_EVENT_PATH"
--intent intent.yaml
--output plan.json
--changed
)

orun plan "${plan_args[@]}"
- id: matrix
run: |
echo "job-matrix=$(jq -c '[.jobs[] | {"job-id": .id, "job-name": .checkName}]' plan.json)" >> "$GITHUB_OUTPUT"
- uses: actions/upload-artifact@v7
with:
name: orun-plan
path: plan.json

run:
needs: plan
runs-on: ubuntu-latest
if: ${{ needs.plan.outputs.job-matrix != '[]' && needs.plan.outputs.job-matrix != '' }}
strategy:
fail-fast: false
# Stagger the fan-out: every lane hits the lease-bound resolve at job
# start, and an unbounded herd saturated it twice. The orun DAG already
# serializes dependents, so capped parallelism costs little wall-clock.
max-parallel: 8
matrix:
include: ${{ fromJson(needs.plan.outputs.job-matrix) }}
name: ${{ matrix.job-name }}
steps:
- uses: actions/checkout@v6
- uses: actions/download-artifact@v8
with:
name: orun-plan
- name: Log in to GHCR
uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: sourceplane/orun-action@v1.2.0
with:
version: v2.56.2
# exec-id is the RUN id alone (no attempt suffix): a `gh run rerun
# --failed` then RESUMES the same orun execution — jobs that succeeded in
# a prior attempt stay completed, so re-run lanes' cross-job dependencies
# are already satisfied instead of waiting forever on lanes that are not
# re-running (the partial-rerun deadlock). --retry re-opens THIS lane's
# job when it terminally failed in a prior attempt (no-op on first
# attempts) — together they make `gh run rerun --failed` a true resume.
- run: |
# --retry only on re-run attempts: on a fresh attempt a failed
# upstream is a genuine failure and dependents must fail fast; on a
# resume (gh run rerun --failed) the upstream's own retry lane will
# re-open it, so lanes wait out the race instead.
retry_flag=""
if [ "${GITHUB_RUN_ATTEMPT:-1}" -gt 1 ]; then retry_flag="--retry"; fi
# EVERY RUN REPORTS TO THE PLATFORM, a pull request's included.
#
# A PR lane resolves its secrets like any other (a verify lane still
# reads the wiring its fixture stands in for, an infra lane plans
# against the real account), and a job's secret refs are resolved
# before its first step whatever its profile does — so a PR run
# without remote state failed every lane that declares one:
#
# ✗ cloudflare-d1.stage.terraform: secret resolution failed: local
# runs resolve secrets only from ORUN_SECRET_<KEY> overrides
#
# and a phase's PR could never be verified before it merged. This
# used to drop the state flag on PRs, on the belief that the backend
# refuses a pull_request OIDC token by design. It does not: the
# exchange's only gate is the repo link's CI settings (oidcEnabled,
# allowedRefPattern, allowedEnvironments — identity-worker
# oidc-exchange.ts), and the resource-hidden `not_found` seen at the
# time is exactly what an UNLINKED repository answers, push or PR.
# Remote state on a PR also puts the PR's runs in front of the
# platform, which renders runs on refs/pull/<n> as that PR's row.
# Fork PRs get no OIDC token from GitHub at all and still fail
# closed. Nothing mutating runs here: deploy/apply profiles are gated
# on triggerRef github-push-main.
state_flag="--remote-state"
orun run \
--plan plan.json \
--runner github-actions \
$state_flag \
--job "${{ matrix.job-id }}" \
--exec-id "${{ github.run_id }}" \
$retry_flag
env:
# GITHUB_TOKEN is the only credential CI holds — GitHub-issued and
# ephemeral. Every provider credential (the Cloudflare token and
# account id — this baseline has no second provider) is an
# orun-managed secret:
# brokered fresh per run from the workspace's integrations, resolved
# lease-bound by the jobs that declare it (profile secretBindings or
# component secretEnv), and log-redacted. Nothing provider-shaped is
# stored in GitHub.
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
DOCKER_CONFIG: /home/runner/.docker
40 changes: 40 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
node_modules/
dist/
.wrangler/
.turbo/
coverage/
*.tsbuildinfo
.env
.env.local
*.log
plan.json

# Terraform
.terraform/
*.tfstate
*.tfstate.backup
crash.log
.workspace/

# orun per-job staged workspaces and object-model caches.
#
# `**/` because a pattern containing a slash is anchored to THIS directory,
# so the root-anchored form missed `testing/rehearsal/.orun/` — an intent
# that lives in a subdirectory caches beside itself, and a `plan` run there
# offered 40 content-addressed blobs to the next `git add -A`.
**/.orun/runs/
**/.orun/

# BF6: rendered wrangler configs for wiring-templated workers (api-edge pilot)
apps/api-edge/wrangler.jsonc
apps/config-worker/wrangler.jsonc
apps/events-worker/wrangler.jsonc
apps/membership-worker/wrangler.jsonc
apps/projects-worker/wrangler.jsonc
apps/identity-worker/wrangler.jsonc
apps/billing-worker/wrangler.jsonc
apps/metering-worker/wrangler.jsonc
apps/notifications-worker/wrangler.jsonc
apps/admin-worker/wrangler.jsonc
apps/integrations-worker/wrangler.jsonc
apps/webhooks-worker/wrangler.jsonc
11 changes: 11 additions & 0 deletions .rebrand/values.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"reponame": "new-test",
"productname": "new-test",
"productdomain": "new-test.dev",
"apibaseurl": "https://api.new-test.dev",
"subdomain": "nexo-7be",
"orunWorkspace": "org_c126e518fd9b4cae9706f760c9f8551b",
"githuborg": "pullely",
"epicSlug": "infra-baselining",
"domain": false
}
11 changes: 11 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "Verify Task",
"type": "shell",
"command": "STATE_FILE=\"${STATE_FILE:-ai/state.json}\"; ORCHESTRATOR_MODEL=\"${ORCHESTRATOR_MODEL:-gpt-5.5}\"; echo \"=== verify-orchestrator ===\" && hermes chat --yolo --model poolside/laguna-m.1:free --provider openrouter -q \"Act as agents/orchestrator.md\" && sleep 30 && TASK_PROMPT=\"$(jq -r '.task_agent // empty' \"$STATE_FILE\")\" && test -n \"$TASK_PROMPT\" || { echo \"No task_agent found in $STATE_FILE\"; exit 1; }; echo \"=== verify-tasker ===\" && hermes chat --yolo --model deepseek/deepseek-v4-flash:free --provider nous -q \"$TASK_PROMPT\" && sleep 30 && OPEN_PR_COUNT=\"$(gh pr list --state open --limit 100 --json number --jq 'length')\" && if [ \"$OPEN_PR_COUNT\" -gt 0 ]; then echo \"Skipping new-task-orchestrator because $OPEN_PR_COUNT open PR(s) exist.\"; gh pr list --state open; else echo \"=== new-task-orchestrator ===\"; codex exec --skip-git-repo-check --model \"$ORCHESTRATOR_MODEL\" --dangerously-bypass-approvals-and-sandbox \"Act as agents/orchestrator.md\"; fi",
"inAgents": true
}
]
}
177 changes: 177 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
# new-test

Reusable **Cloudflare-only** multi-tenant SaaS starter, built as an
[Orun](https://opencode.ai/docs) component-native desired-state repo. Identity,
organizations, projects, RBAC, audit, metering, billing, webhooks, and
notifications ship as separate bounded-context Cloudflare Workers behind a single
public edge API, with a Next.js console on Workers + Static Assets — and
Cloudflare D1 as the database, so Cloudflare is the only provider in the loop.

## Live deployment

<!-- 08-docs:begin -->
_Not yet recorded — run [`08-docs`](docs/phases/08-docs.md) after
`06-console` to fill this section from verified live state
([manifest](ai/context/deployment.md) · [operating contract](ai/context/operations.md))._
<!-- 08-docs:end -->

## Status

- **Runtime is live, per environment, through Orun.** The edge API, the
bounded-context Workers, and the console deploy to `stage` and `prod` via
`orun run` (no direct Wrangler/Terraform/pnpm in CI).
- **Data plane is provisioned by Terraform:** a Cloudflare D1 database per
environment and the `api-edge` idempotency KV namespace. Terraform state
lives in the Orun Cloud HTTP state backend; provider credentials are
BROKERED per-run from the workspace's Cloudflare connection (no AWS, no
long-lived secrets at rest).
- **Database migrations** run through the `db-migrate` component against D1's
REST API (plan on PRs, apply on merge to `main`).
- **Billing** is live end-to-end via the Polar adapter (embedded checkout,
plan changes, multi-org fan-out).
- **Known credential-blocked tails**: full production OAuth/magic-link auth
and Stripe require human-supplied credentials. The notifications email
provider is Cloudflare Email Service (`cloudflare-email`, no API key — the
`send_email` binding is the credential); it needs one-time account setup:
Workers Paid plan and the sending domain verified in Email Service
(DKIM/SPF).
- The `dev` environment is verify-only (no provisioned database by design).

## Why Cloudflare-only

One provider means one consent, one token, and one place to look when
something breaks. The cost is D1's shape, and this baseline is explicit about
it rather than quiet:

- **No interactive transactions.** D1 offers atomic `batch()` for a statement
list decided up front, not a transaction held open across reads and writes.
`executor.transaction(...)` therefore runs its statements in order with no
rollback; every call site is a place a reviewer should look first. Prefer a
single statement with `RETURNING`, or an upsert with `ON CONFLICT`, where
all-or-nothing actually matters.
- **SQLite types.** Timestamps are ISO-8601 text, JSON documents are text,
booleans are 0/1. `@saas/db/json` owns the decoding so row mappers never
guess.
- **No schemas.** The bounded-context boundary is a table-name prefix
(`identity_users`, `membership_organizations`) enforced by the
repositories — which is where it was actually enforced under Postgres too.

## Instantiating products

This baseline births new products from one artifact — `repo-blueprint.yaml`,
run by `orun new` (**[BOOTSTRAP.md](BOOTSTRAP.md)** →
[docs/phases/](docs/phases/README.md)). It declares nine idempotent phases —
scaffold, foundation, infrastructure, workers, workers-restore, edge,
console, optional domain, docs — each landing a verified slice, each
selectable with `--phase <name>`. Products receive **product-only content**
(source, infra, CI, their own docs); none of this baseline's machinery
ships, and a product's docs speak only about the product.

## Prerequisites

- Node.js >= 20 (CI and components run on Node 22)
- pnpm >= 10 (`npm install -g pnpm`)
- (Optional, for local Orun validation) the `kiox` CLI on your `PATH`. `kiox`
pins the Orun provider declared in `kiox.yaml`; invoke Orun as
`kiox -- orun ...`.

## Getting Started

```bash
# Install all workspace dependencies
pnpm install

# Type-check / lint / test / build across the workspace (Turborepo)
pnpm typecheck
pnpm lint
pnpm test
pnpm build
```

## Workspace Layout

```
apps/api-edge Public HTTP entry point (Cloudflare Worker)
apps/identity-worker Users, sessions, API keys, OAuth
apps/membership-worker Organizations, members, invitations, role assignments
apps/projects-worker Projects and environments
apps/policy-worker Deny-by-default RBAC evaluation
apps/events-worker Domain events, audit log, observability
apps/config-worker Settings, feature flags, secret metadata
apps/metering-worker Usage ingestion, quotas, rollups
apps/billing-worker Plans, subscriptions, invoices (Polar adapter)
apps/notifications-worker Email delivery and preferences
apps/webhooks-worker Outgoing webhooks: signing, delivery, replay
apps/admin-worker Audited admin/support workflows
apps/web-console-next Next.js console (Cloudflare Workers + Static Assets)

packages/contracts Shared API, tenancy, event, and error types + validators
packages/policy-engine RBAC evaluation logic
packages/db D1 executor, migration harness, manifest, and runner
packages/sdk TypeScript SDK (contract-driven)
packages/cli `new-test` CLI
packages/notifications-client Notifications client
packages/shared Generic helpers (IDs, errors) — no domain logic
packages/testing Test fixtures and utilities

infra/terraform/cloudflare-d1 D1 database provisioning (stage/prod)
infra/terraform/cloudflare-kv api-edge idempotency KV namespace
infra/terraform/cloudflare-domain Zone adoption + console custom domain
infra/db-migrate Database migration runner component

tooling/tsconfig Shared TypeScript configurations
tooling/eslint Shared ESLint configuration
tooling/wire Deploy-time wrangler config renderer
tests/* Per-component contract and verifier test suites
```

Execution contracts (the composition stack) are not vendored here. They are
consumed from the published catalog at
`oci://ghcr.io/sourceplane/stack-tectonic`, pinned to an explicit version in
`intent.yaml`. Composition changes are made in
[sourceplane/stack-tectonic](https://github.com/sourceplane/stack-tectonic),
released there, and adopted here by bumping the pinned tag.

## CI

CI is powered by [Orun](https://opencode.ai/docs) with the local Stack Tectonic
composition stack. `.github/workflows/ci.yml` calls only `orun plan` and
`orun run` — no direct `pnpm`, `turbo`, Wrangler, or Terraform commands run in
GitHub Actions. The Orun runtime is pinned in `kiox.yaml` (resolved digest in
`kiox.lock`); the workflow's `orun-action` `version:` matches that pin.

### Local Orun Verification

```bash
kiox -- orun compositions lock --intent intent.yaml
kiox -- orun validate --intent intent.yaml
kiox -- orun plan --changed --intent intent.yaml --output plan.json
kiox -- orun run --plan plan.json --dry-run --runner github-actions
```

Use `--changed` for PR-scoped checks; use a full plan when validating
environment promotion or cross-component dependencies (`--view dag`).

## Infrastructure

Terraform provisions the D1 database and the `api-edge` KV namespace for
`stage` and `prod`. Both roots carry `adopt.tf`, which imports an existing
resource at plan time instead of colliding with it — so a re-bootstrap over a
half-torn-down attempt heals rather than fails. Credentials are brokered per
run from the workspace's Cloudflare connection and Terraform state lives on
the platform; nothing provider-shaped is stored in this repo or in GitHub.
See `specs/core/access-and-infra.md` for the access model.

## Adding a New Component

1. Create the directory under `apps/`, `packages/`, `tests/`, or `infra/`.
2. Add a `component.yaml` with the appropriate `spec.type` — one of
`cloudflare-worker-turbo`, `cloudflare-workers-assets-turbo`, `terraform`,
`db-migrate`, or `turbo-package` — plus `subscribe.environments` and the
typed `parameters` the composition schema requires.
3. Orun discovers it automatically on the next plan (`discovery.roots` covers
`apps/`, `infra/`, `packages/`, `tests/`). Validate with
`kiox -- orun validate --intent intent.yaml`.

See `specs/core/orun-golden-path.md` for the intent/component/composition layer
rules before changing CI, infra, or `intent.yaml`.
Loading
Loading