diff --git a/.changeset/headless-backend.md b/.changeset/headless-backend.md new file mode 100644 index 0000000..db6c3e0 --- /dev/null +++ b/.changeset/headless-backend.md @@ -0,0 +1,84 @@ +--- +'@swirls/spools': minor +'@swirls/create-spools': minor +--- + +Spools is headless. It is the backend for custom business software, behind an HTTP API, and draws nothing: the +front end is yours, on any framework. + +**Removed.** The interface a Spool came with is gone, with everything that existed only to +describe it: + +- The pages, views and components (`@swirls/spools/pages/*`, `ui/*`, `theme.css`, + `auth/*/ui`), the framework's own server functions, and the starter's `src/routes`, + `src/spool.ui.ts`, `vite.config.ts` and build. +- Layouts (`ui` in `spool.config.json`, `spools ui`), in-app guides (`guides`, + `@swirls/spools/guides`, the `guide_progress` table) and alerts. +- A module's browser half, routes, guides and sections. +- From the config: an object's `icon` and `sections`; a view's `type`, `columns`, `groupBy` + and stored calculations (a view is now a named filter and sort, and `records.list` takes + `pageSize`, `fields` and `calculations`); a role's `record`, `hide` and `home.create`; + `home.create`, `home.counts` and `home.links`; `assistant.greeting` and + `assistant.suggestions`. +- `bun create @swirls/spools --headless`: there is one template, and it is headless. +- Starting without a vault's keys. A production server does not start without the `CS_*` + variables (`vault: cipherstash()`) or `VAULT_KEY` (`vault: aes()`), and on your own + machine a stand-in seals until they are set. + +**What a Spool is now.** + +- **Operations.** Everything a Spool does for whoever asks is defined once, as an operation + (`@swirls/spools/operations`). +- **The server.** `headlessServer()` from `@swirls/spools/headless` answers the API and + every endpoint a Spool has (sign-in, files, the assistant, webhooks, cron), with no web + framework, and takes `routes` for endpoints of your own. A new Spool's `src/server.ts` is + that, and `bun run dev` serves it with no build. +- **The HTTP API.** `httpApi()` from `@swirls/spools/http` answers every operation at + `POST /api/v1/`, on any server, and describes itself at `GET /api/v1` and as OpenAPI + 3.1 at `/api/v1/openapi.json`. A caller is known by the session cookie on the same site, a + sign-in token from a front end you name, or an API key. The access list, record scopes, + role access and record rules apply to every one of them. +- **API keys.** `spools keys create --name ... --as ` makes a key for a script or a + service, once the server says `keys: true`. It acts as that teammate, can be read-only, + and ends after 90 days unless you say otherwise. What is kept is sealed by the vault. +- **A typed client.** `createClient()` from `@swirls/spools/client` knows every + operation and, through the `src/spool.types.ts` that `spools gen` writes, every field of + your objects. +- **Query options.** `createQueries` from `@swirls/spools/query` gives every operation as + query and mutation options for TanStack Query. +- **React hooks.** `useListState`, `useRecordForm` and `useRelationSearch` from + `@swirls/spools/react` hold the state of a list, a record's form and a relation picker, + and draw nothing. The rules they are made of are in `@swirls/spools/state`, for any + framework. +- **In a TanStack Start app.** `serveApi` from `@swirls/spools/api/http` mounts the API as + two route files, `startClient` from `@swirls/spools/start/client` asks it in-process on the + server and over HTTP in the browser, and `staffHandler` from `@swirls/spools/handlers` checks + who is asking in your own server functions. `examples/tanstack-start` is a small front + end that uses all of it. +- **Clerk without TanStack Start.** `clerk()` from `@swirls/spools/auth/clerk/backend` reads + the session from the request with Clerk's backend SDK. +- **Better Auth in an app.** `betterAuth({ bearer: true })` lets a phone or desktop app + carry its session as a bearer token. +- **Where your front end is.** `frontEnd` in `defineSpool` says where its sign-in, + integrations and unsubscribe pages are, for the few answers that send a browser to one. + Without an unsubscribe page the server answers the link in an email itself. +- **Routes that check who is calling.** `headlessServer` refuses to start with a route + whose handler was not made with `apiRoute`, `cronRoute` or `publicRoute`. +- **More in the answers.** `marketing.get` answers the tag report with install code and each + ad's click rate and costs, `files.startUpload` takes a `contentType`, and + `@swirls/spools/state` has the search matching and the marketing checks. + +**Renamed.** The names that said `crm` say `spool`: `spool.config.json`, `src/spool.types.ts`, +`bun run gen`, `defineSpool({ config })`, `spoolConfig()`, `SpoolConfig`, `staffHandler`, +`StaffUser`, `SpoolRecord` and the rest, and `spool_event` and the `spool_*` workflows in +`.swirls` files. [Upgrading](https://spools.codes/docs/upgrading) has the whole list. + +**Built-in modules.** Email sequences, mailbox and calendar sync, marketing and contact +tracking are modules now, from `@swirls/spools/modules`. A Spool has each only when it lists +it: add `modules: [sequences, mailbox, marketing, contactTracking]` to `defineSpool` to keep +all four. Without one, its tables are not made, its operations and routes are not there, and +its part of the config is refused. `session.get` answers the ones listed as `features`. + +This version changes the tables: it adds `api_keys`, and removes `guide_progress` and the +`type` column of `saved_views`. After updating run `bun run gen`, then `bun run db:push` +or your migration. See [Upgrading](https://spools.codes/docs/upgrading). diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cd2f460..ff0ab09 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,9 +50,9 @@ jobs: - name: Check generated files working-directory: apps/starter run: | - bun run crm:gen - git diff --exit-code -- prisma crm.config.schema.json \ - || (echo "::error::Run 'bun run crm:gen' in apps/starter and commit the result" && exit 1) + bun run gen + git diff --exit-code -- prisma spool.config.schema.json src/spool.types.ts \ + || (echo "::error::Run 'bun run gen' in apps/starter and commit the result" && exit 1) # The scope tests run on a Spool of their own, whose Prisma schema is generated too. - name: Check the scope tests' generated schema working-directory: packages/spools @@ -66,12 +66,6 @@ jobs: run: bun run lint - name: Test run: bun run test - - name: Build the starter - working-directory: apps/starter - run: | - bun run build - git diff --exit-code -- src/routeTree.gen.ts \ - || (echo "::error::Run 'bun run build' in apps/starter and commit src/routeTree.gen.ts" && exit 1) integration: name: integration (${{ matrix.store }}) @@ -150,30 +144,6 @@ jobs: working-directory: apps/starter run: swirls doctor - e2e: - runs-on: blacksmith-4vcpu-ubuntu-2604 - timeout-minutes: 15 - steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 - with: - bun-version: 1.4.4 - - name: Install - run: bun install --frozen-lockfile - - name: Install Chromium - run: bunx playwright install --with-deps chromium - - name: Test in a browser - run: bun run test:e2e - - name: Keep the report - if: failure() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: playwright-report - path: | - apps/starter/e2e/playwright-report/ - apps/starter/e2e/test-results/ - retention-days: 7 - deploy-docs: if: >- github.event_name == 'push' && github.ref == 'refs/heads/main' && diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 99a7fae..a779ab9 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -23,11 +23,13 @@ "**/coverage/**", "**/routeTree.gen.ts", "**/prisma/schema.*", - "**/crm.config.schema.json", + "**/spool.config.schema.json", + "**/spool.types.ts", "**/migrations/**", "**/supabase/**", "**/docs-manifest.json", "packages/create-spools/template/**", + "packages/create-spools/template-headless/**", "tools/oxlint/anti-slop/**", "bun.lock", ".agent/**", diff --git a/.oxlintrc.json b/.oxlintrc.json index 79a0b0c..7aa6f42 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -17,8 +17,10 @@ "**/.flox/**", "**/routeTree.gen.ts", "**/prisma/schema.d.ts", + "**/spool.types.ts", "**/migrations/**", "packages/create-spools/template/**", + "packages/create-spools/overrides/**", ".agent/**", ".agents/**", ".claude/**", @@ -184,7 +186,7 @@ } }, { - "files": ["**/*.config.ts", "**/*.config.e2e.ts"], + "files": ["**/*.config.ts"], "rules": { "effecttsgo/node-builtin-import": "off", "effecttsgo/process-env": "off" @@ -206,7 +208,7 @@ }, { "files": [ - "packages/spools/src/crm/extensions.ts", + "packages/spools/src/core/extensions.ts", "packages/spools/src/server/runtime/agents.ts", "packages/spools/src/server/store/objects.ts" ], @@ -215,7 +217,12 @@ } }, { - "files": ["packages/spools/src/crm/filters.ts", "packages/spools/src/crm/options.ts"], + "files": [ + "packages/spools/src/core/filters.ts", + "packages/spools/src/core/options.ts", + "packages/spools/src/core/list-state.ts", + "packages/spools/src/core/record-state.ts" + ], "rules": { "anti-slop/no-unknown-parameters": "off", "anti-slop/no-known-value-widening": "off" @@ -232,7 +239,7 @@ } }, { - "files": ["packages/spools/src/server/**", "apps/starter/src/routes/api/**"], + "files": ["packages/spools/src/server/**"], "excludeFiles": [ "packages/spools/src/server/runtime/**", "packages/spools/src/server/env.ts", @@ -268,13 +275,11 @@ "no-restricted-imports": [ "error", { - "paths": [ - { - "name": "@tanstack/react-start/server", - "message": "The request belongs to the boundary (packages/spools/src/server/runtime/boundary.ts); a program reads it from CurrentRequest." - } - ], "patterns": [ + { + "group": ["@tanstack/**", "react", "react/**", "react-dom", "react-dom/**"], + "message": "The server is free of any web framework, so a Spool runs with none (docs/architecture.md). TanStack Start is bound in packages/spools/src/start.ts and start-client.ts, and React in react.ts." + }, { "group": ["**/app/extensions", "**/spool.server"], "message": "The framework never imports the app. Read it from the Spool (packages/spools/src/server/spool.ts)." @@ -311,6 +316,10 @@ "error", { "patterns": [ + { + "group": ["@tanstack/**", "react", "react/**", "react-dom", "react-dom/**"], + "message": "The server is free of any web framework, so a Spool runs with none (docs/architecture.md). TanStack Start is bound in packages/spools/src/start.ts and start-client.ts, and React in react.ts." + }, { "group": ["**/app/extensions", "**/spool.server"], "message": "The framework never imports the app. Read it from the Spool (packages/spools/src/server/spool.ts)." @@ -341,28 +350,14 @@ } }, { - "files": ["packages/spools/src/server/*.functions.ts"], - "rules": { - "spools/server-function-files": "error" - } - }, - { - "files": ["packages/spools/src/api/**", "apps/starter/src/routes/**"], + "files": ["packages/spools/src/api/**"], "rules": { "spools/route-adapters": "error" } }, { - "files": [ - "packages/spools/src/crm/**", - "packages/spools/src/pages/**", - "packages/spools/src/views/**", - "apps/starter/src/routes/**", - "apps/starter/src/router.tsx", - "apps/starter/src/start.ts", - "apps/starter/src/spool.ui.ts" - ], - "excludeFiles": ["apps/starter/src/routes/api/**", "packages/spools/src/crm/codegen.ts"], + "files": ["packages/spools/src/core/**"], + "excludeFiles": ["packages/spools/src/core/codegen.ts"], "rules": { "no-restricted-imports": [ "error", @@ -370,11 +365,11 @@ "patterns": [ { "group": ["effect", "effect/*"], - "message": "Effect is server-only: it must not reach the browser bundle. Call a server function instead; see docs/server-code.md." + "message": "This code is shared with the browser (a front end imports it through @swirls/spools/state), and Effect is server-only; see docs/server-code.md." }, { "group": ["@clerk/**", "better-auth", "better-auth/*"], - "message": "Pages reach the auth provider with useAuth() (packages/spools/src/crm/ui/auth.tsx), so any adapter works; see docs/adapters.md." + "message": "Only an auth adapter (packages/spools/src/adapters/auth) talks to an auth provider; see docs/adapters.md." }, { "group": [ @@ -385,7 +380,7 @@ "@swirls/spools/email/*", "@swirls/spools/files/*" ], - "message": "Pages never import an adapter. The app chooses its adapters in src/spool.server.ts and src/spool.ui.ts; see docs/adapters.md." + "message": "Code shared with the browser never imports an adapter. The app chooses its adapters in src/spool.server.ts; see docs/adapters.md." } ] } diff --git a/AGENTS.md b/AGENTS.md index 2081576..9bd9da2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,30 +22,39 @@ Use one of these types: `build`, `chore`, `ci`, `docs`, `feat`, `fix`, `perf`, ` ## The repository This repository is a framework, an app that uses it, and the website. The framework is -`packages/spools` (`@swirls/spools`). `apps/starter` is a working Spool: a config-driven CRM -served from `/`, where the framework is developed. `packages/create-spools` makes a new app -from it. `apps/docs` is the website, whose documentation is `docs/`. Stack: TanStack Start -(Vite), Effect, Tailwind v4, and whichever services the Spool chose. This file is the map for +`packages/spools` (`@swirls/spools`): the backend for custom business software, of which a CRM is the first. It is the backend alone, behind an +HTTP API, and draws nothing. A front end is an app's own, on any framework. +`apps/starter` is a working Spool: a config-driven Spool's server, where the framework is +developed. `packages/create-spools` makes a new app from it. `examples/tanstack-start` is a +small front end on a Spool. `apps/docs` is the website, whose documentation is `docs/`. +Stack: Bun, Effect, and whichever services the Spool chose. This file is the map for coding agents. Read `docs/architecture.md` first. In the rest of this file `P` is `packages/spools/src`, and a path that starts with `src/`, -`swirls/`, `prisma/` or `crm.config.json` is in `apps/starter`. +`swirls/`, `prisma/` or `spool.config.json` is in `apps/starter`. ## Golden rules -- **The CRM is defined by `crm.config.json`.** Objects, fields, views, actions, - automations, campaigns and an app's own guides live there (contract: - `P/crm/config-schema.ts`, docs: `docs/configuration.md`). After editing it, run - `bun run crm:gen` then, if `DATABASE_URL` is set, `bun run db:push`. Never hand-edit - `prisma/schema.prisma`, `prisma/schema.json`, `prisma/schema.d.ts` or - `crm.config.schema.json`: they're generated, and CI fails if they drift. -- **A Spool chooses its services in `src/spool.server.ts`** (`defineSpool`), and auth's - browser half in `src/spool.ui.ts`. The framework asks for **ports** (`Store`, `Auth`, +- **The Spool is defined by `spool.config.json`.** Objects, fields, views (a named filter and + sort), actions, automations and campaigns live there (contract: + `P/core/config-schema.ts`, docs: `docs/configuration.md`). After editing it, run + `bun run gen` then, if `DATABASE_URL` is set, `bun run db:push`. Never hand-edit + `prisma/schema.prisma`, `prisma/schema.json`, `prisma/schema.d.ts`, + `spool.config.schema.json` or `src/spool.types.ts`: they're generated, and CI fails if they drift. +- **A Spool chooses its services in `src/spool.server.ts`** (`defineSpool`). The framework asks for **ports** (`Store`, `Auth`, `FileStore`, `Email`, `Vault`, `Agents`, `RateLimiter`, and `Tokens`, which an auth adapter may also give) and never imports an adapter, a vendor's SDK or the app: lint refuses it. Adapters are in `P/adapters//` (`docs/adapters.md`). Feature sets a Spool - plugs in are `modules` in the same file, their browser halves in `src/spool.ui.ts` - (`docs/modules.md`). + plugs in are `modules` in the same file (`docs/modules.md`). +- **Built-in features are opt-in modules.** Email sequences, mailbox and calendar sync, marketing + and contact tracking (`FEATURES` in `P/core/features.ts`) are modules from + `@swirls/spools/modules` (`P/modules.ts`), and a Spool has each only when it lists it + (`spool().features`). A feature's tables are `featureTables` in `P/server/store/tables.ts`, its + operations say `feature`, its routes in `P/headless.ts` and tools in `P/server/tools.ts` name + it, and its schedule starts in `P/server/entry.ts` only when it is on. Code that works for + another feature asks `hasFeature` (`P/server/features.ts`) before it touches one's tables, + and iterates `presentSystemTables()`, never `systemTables`. The starter lists all four, which + is what makes it a CRM. Tests: `tests/integration/features.test.ts`, on a Spool with one. - **Extend, don't patch.** App-specific server code goes in `src/app/extensions.ts` (handlers, hooks, run-target kinds, email transport, integration providers, the file layout). Only change `packages/spools` when adding a framework capability. @@ -59,49 +68,45 @@ In the rest of this file `P` is `packages/spools/src`, and a path that starts wi first few rows of each of many groups, `find` takes `perGroup`: never one query for each row of a page. Anything new must work on every store: run the integration tests on each (`TEST_STORE`). -- **All data access goes through `P/server`.** Components call server functions - (`P/server/*.functions.ts`) and never import server modules. Every CRM server - function's handler is `crmHandler(...)`, which checks the session and the allowlist, - and every `/api` handler uses a route adapter (`apiRoute`, `cronRoute`, - `publicRoute`, `toolRoute`) from `P/server/runtime/boundary.ts`. +- **Spools draws nothing.** No page, component, stylesheet or layout belongs in the + framework, and nothing in the config says how anything looks. What a front end needs is + an operation's answer, or state with no markup in `P/react.ts` over pure rules in + `P/core/*.ts` (published as `@swirls/spools/state`). docs/front-ends.md +- **Everything a Spool does for whoever asks is an operation** (`P/server/operations`), + answered by the HTTP API. Every `/api` handler uses a route adapter (`apiRoute`, + `cronRoute`, `publicRoute`, `toolRoute`) from `P/server/runtime/boundary.ts`, and an + app's own server function is `staffHandler(...)`, which checks the session and the + allowlist. - **Server code is written with Effect** (docs/server-code.md). Export `Effect.fn("module.name")(function* () { ... })`, fail with a typed error from `P/server/runtime/errors.ts` (its `message` is what staff read), and read env through `Config`. Lint refuses the old way (promises, `throw`, `fetch`, `process.env`) - everywhere but the few files `.oxlintrc.json` leaves out. Effect never goes in browser - code or `src/app/**`. -- **The app's config and extensions come from the Spool** (`spool()`, `crmConfig()`, + everywhere but the few files `.oxlintrc.json` leaves out. Effect never goes in code a + browser loads (`P/core/**`, `P/react.ts`, `P/client.ts`, `P/query.ts`) or `src/app/**`. +- **The app's config and extensions come from the Spool** (`spool()`, `spoolConfig()`, `getObject(key)` in `P/server/spool.ts`), read when they are used. There is one Spool per process. - **Agents never touch the database.** Workflows and the assistant call the tool API (`P/server/tools.ts`). Add a capability there, then a tool workflow in `swirls/assistant.swirls`. -- **A page is three pieces**: route options in `P/pages/.tsx`, what it renders in - `P/views/.tsx` (loaded lazily; reaches its route with `getRouteApi`), and a - three-line file in `src/routes` that mounts it. An endpoint is handlers in - `P/api/.ts` and its file in `src/routes/api`. A new page or endpoint needs the - route file here, and a line in the changeset telling apps to add it. -- **Browser code imports `P/crm/naming.ts` for helpers**, not `config-schema.ts` - (which pulls Zod and the config schema into the browser bundle). Type-only - imports are fine. Pages reach the auth provider with `useAuth()` (`P/crm/ui/auth.tsx`). -- **Page code draws a moment with ``** (`P/crm/ui/kit.tsx`), never by calling - `relativeTime(...)` during render: "3 minutes ago" differs between the server that draws a - page and the browser that takes it over, and React rebuilds the tree over the difference. - `packages/spools/tests/unit/relative-time.test.ts` reads `P/crm/ui`, `P/views` and `P/pages` - and fails for one that does. +- **An endpoint is handlers in `P/api/.ts`**, given its address in `routes` in + `P/headless.ts`. An app on TanStack Start mounts the same handlers in its own route + files, so a new endpoint gets a line in the changeset telling those apps to add it. +- **Code a browser loads imports `P/core/naming.ts` for helpers**, not `config-schema.ts` + (which pulls Zod and the whole config schema into a front end's bundle). Type-only + imports are fine. - **System columns.** Every object's table has `createdAt`, `updatedAt`, `createdBy`, `lastActivityAt`, `lastContactedAt` and `nextTaskDue` - (`SYSTEM_COLUMNS` in `P/crm/filters.ts`). They can be shown, sorted and + (`SYSTEM_COLUMNS` in `P/core/filters.ts`). They can be shown, sorted and filtered, not edited, and their names can't be used as field keys. - **System tables** are described in `P/server/store/tables.ts`, not the config. They - aren't CRM objects: no hooks or automations, and their keys (`tasks`, `notes`, - `reports`, `workflows`, `integrations`, `marketing`, `files`, `assistant`) can't be used as object - keys. An adapter may add its own (`tables`), which must not depend on the environment. + aren't Spool objects: no hooks or automations, and an object whose table would be one of + them (`tasks`, `notes`, `activities`) is refused. An adapter may add its own (`tables`), which must not depend on the environment. - **Timeline summaries are sentence fragments** that follow the actor's name ("changed Stage to Won", "added a note: Pricing call"): lower-case, no full stop. - **Single business per deployment**, deny-by-default `access` allowlist. Everyone on it reaches every record unless the config gives a role `access` (role access, below) or has - `scopes` (record scopes: `P/crm/scopes.ts`, docs/security.md#record-scopes). With scopes + `scopes` (record scopes: `P/core/scopes.ts`, docs/security.md#record-scopes). With scopes every store is behind the guard in `P/server/store/scope.ts`, which narrows each call to the scopes of whoever the request is for (`CurrentAccess`). Don't work around it: code with nobody signed in (a cron route, a schedule, a script) runs inside `asSystem(...)` or it is @@ -115,27 +120,27 @@ In the rest of this file `P` is `packages/spools/src`, and a path that starts wi record carries a copy of its record's scope, which is stale after a change to `scopes.objects` until `spools scopes backfill` (`P/server/scope-backfill.ts`). A scope a resolver says someone holds counts only when it is one of this Spool's (`holdableScopes` in - `P/crm/scopes.ts`; every resolver is behind `Scopes.holdable`), and someone who can change + `P/core/scopes.ts`; every resolver is behind `Scopes.holdable`), and someone who can change no record changes nothing that is the whole business's either: a write to Marketing or to a - shared connection starts with `mustChange` (`P/server/scopes.ts`). A control that - changes something is shown by `useWriteReach()` (`P/crm/ui/write-reach.ts`; the rules are - `writeReach` in `P/crm/scopes.ts`), so whoever can't make a change isn't offered it. That is - for the page's sake only: the guard is what refuses. + shared connection starts with `mustChange` (`P/server/scopes.ts`). What a front end + offers someone is `writeReach` in `P/core/scopes.ts` and `pageReach` in `P/core/reach.ts` + (pure, in `@swirls/spools/state`). That is for the front end's sake only: the guard is + what refuses. - **Encryption:** fields marked `"encrypted"` are stored as plaintext because `@cipherstash/stack-prisma` 1.2.1 only supports Prisma Next 0.17, not Prisma 8. - `crm:gen` warns about each one. Don't remove the markers. + `gen` warns about each one. Don't remove the markers. - **Record rules and role access are the data layer's.** An object's `unique`, `lock` and `appendOnly` and a field's `immutable`, `readonly`, `audit` and `untrusted` - (`P/crm/rules.ts`, pure; config keys in `P/crm/rules-schema.ts`) are enforced in + (`P/core/rules.ts`, pure; config keys in `P/core/rules-schema.ts`) are enforced in `P/server/records.ts` through `P/server/record-rules.ts`, for every caller, and `readonly` and `audit` in `P/server/service.ts` (a person's write is one with an `actor`; `null` is the server). A uniqueness rule is a (partial) unique index on every store and refuses with `Conflict`, never a `DatabaseError`. Role `access` is `CurrentObjectAccess` (`P/server/object-access.ts`), set by the boundary for a person and from `assistant.deny` for the tool API, and carried into the app's promise code as scopes are (`fromHook`, `runServer`): anything new that reads records, or rows hung off them, checks it (`mustSee`, - `mustEdit`, `seen`, `hiddenObjects`); a denied object is "not found". Pages hide what either - refuses (`fieldEditable`, `pageReach`), for their own sake only. + `mustEdit`, `seen`); a denied object is "not found". A front end hides what either + refuses (`fieldEditable`, `pageReach`), for its own sake only. - **`asSystem` is what marks the server's own work.** Both forms (the Effect one in `P/server/scopes.ts`, the promise one in `P/server/extension-api.ts`) set `SystemWork` (`P/server/runtime/access.ts`), which is carried into the app's promise code with the rest. @@ -147,53 +152,50 @@ In the rest of this file `P` is `packages/spools/src`, and a path that starts wi ## Where things go -- **CRM object, field, view, action, automation, campaign.** `crm.config.json` → `bun run crm:gen` → `bun run db:push` +- **Spool object, field, view, action, automation, campaign.** `spool.config.json` → `bun run gen` → `bun run db:push` - **App-side action handler (`"run": "local:"`).** `handlers` in `src/app/extensions.ts` - **Record lifecycle logic (validate, react to changes).** `hooks` in `src/app/extensions.ts` - **New run-target kind (`"run": ":"`).** `runTargets` in `src/app/extensions.ts` -- **A feature set as a module (objects, code, private tables, settings, panels, pages).** The contract is `P/crm/modules.ts` (`defineModule`, `defineModuleSettings`, `moduleTable`; published as `@swirls/spools/module`); how modules and the app are put together, and every clash refused, is `P/crm/compose.ts`, called by `defineSpool` (`P/server/spool.ts`), so the server and `spools gen` agree. Modules are listed in `modules` in `src/spool.server.ts` (order is hook order, the app's last), their settings under `modules.` in `crm.config.json`, their browser halves in `src/spool.ui.ts` (`defineSpoolUi`; slots in `P/crm/ui/slots.tsx`, which entries show in `P/crm/slots.ts`). The app replaces a module's part only through `overrides` in `defineSpool`. Private tables are read and written with `moduleTables` (`P/server/extension-api.ts`), never as CRM objects. `spools modules` (`P/cli/modules.ts`) lists the route files modules expect. Example and tests: `examples/modules/approvals`, `packages/spools/tests/unit/modules.test.ts`, `tests/integration/modules.test.ts`; docs/modules.md -- **New field type.** `P/crm/field-types.ts` + `P/crm/ui/fields.tsx` (compiler lists what's missing) -- **New view type.** `viewSchema` in `P/crm/config-schema.ts` + `P/crm/ui/views.tsx` -- **Pipelines: dependent select options (`dependsOn`, `when`), win `probability`.** Rules in `P/crm/options.ts` (no Zod, shared by server and client); enforced on every write in `P/server/records.ts` -- **Swirls workflow (`"run": "swirls:"`).** `swirls/.swirls`, root `inputSchema: crm_event`; validate with `swirls doctor`. Started by `Agents.executeWorkflow` (the port `P/server/runtime/agents.ts`; the Swirls adapter `P/adapters/agents/swirls`: workflow ids cached a minute, the `agentsRead`/`agentsRun` policies; a start is never retried) +- **A feature set as a module (objects, code, private tables, settings).** The contract is `P/core/modules.ts` (`defineModule`, `defineModuleSettings`, `moduleTable`; published as `@swirls/spools/module`); how modules and the app are put together, and every clash refused, is `P/core/compose.ts`, called by `defineSpool` (`P/server/spool.ts`), so the server and `spools gen` agree. Modules are listed in `modules` in `src/spool.server.ts` (order is hook order, the app's last), their settings under `modules.` in `spool.config.json`. The app replaces a module's part only through `overrides` in `defineSpool`. Private tables are read and written with `moduleTables` (`P/server/extension-api.ts`), never as Spool objects. `spools modules` (`P/cli/modules.ts`) lists what each module contributes. A module's own endpoint is handlers the app names under `routes` in `headlessServer`. Example and tests: `examples/modules/approvals`, `packages/spools/tests/unit/modules.test.ts`, `tests/integration/modules.test.ts`; docs/modules.md +- **New field type.** `P/core/field-types.ts` (compiler lists what's missing), and what a form does with it in `P/core/record-state.ts` +- **Pipelines: dependent select options (`dependsOn`, `when`), win `probability`.** Rules in `P/core/options.ts` (no Zod, shared by server and client); enforced on every write in `P/server/records.ts` +- **Swirls workflow (`"run": "swirls:"`).** `swirls/.swirls`, root `inputSchema: spool_event`; validate with `swirls doctor`. Started by `Agents.executeWorkflow` (the port `P/server/runtime/agents.ts`; the Swirls adapter `P/adapters/agents/swirls`: workflow ids cached a minute, the `agentsRead`/`agentsRun` policies; a start is never retried) - **Assistant capability.** A tool in `P/server/tools.ts` (each returns an Effect; a typed failure reaches the agent as `{ ok: false, error }`), served by `toolRoute` at `/api/swirls/tools/*`, + a tool workflow in `swirls/assistant.swirls` -- **The Ask page (the assistant's chat).** `P/pages/assistant.tsx` and `P/views/assistant.tsx`, parts `P/crm/ui/assistant.tsx`, pure helpers (chat groups, titles, tool steps, linked records) `P/crm/assistant.ts`. Its chats are listed in the shell's sidebar in place of the navigation (`OWN_SIDEBAR` and `useShell().panel` in `P/crm/ui/shell.tsx`). The agent engine keeps the chats; the server side gets one only through `Agents.chat` (`P/server/runtime/agents.ts`), which `E2E_ASSISTANT=stub` swaps for canned replies (`e2e/assistant-stub.ts`). Name, greeting and suggested prompts: `assistant` in `crm.config.json`. docs/swirls.md#the-assistant -- **Email sequences (campaigns).** When each email is due, and sending hours, in `P/crm/sequences.ts` (pure). The engine is `P/server/campaigns.ts`: an enrolment is a row in `sequence_runs`, and `tick` sends what is due. `startSequences` forks `sequenceSchedule` (a tick now, then once a minute) on a server that stays up; on a serverless host a cron job calls `/api/cron/sequences` (`P/api/sequences.ts`). Nothing is kept in memory or on disk. A run is taken with one `Store.update` that checks and changes it (`hold`), never by reading then writing, or two ticks send the same email. Every send carries an `idempotencyKey`, and only a send that has one is retried (the `resend` policy). Transport: the app's `email.send`, else the `Email` port (`P/server/runtime/email.ts`); templates, unsubscribe tokens and suppression in `P/server/email.ts`; unsubscribing in `P/server/email.functions.ts`. Tests replace `Email` and `Sequences` (`P/server/sequences.ts`) through `installStandIns`; docs/campaigns.md -- **Generic CRM UI.** `P/crm/ui/*` (`kit.tsx` primitives, `shell.tsx`, `views.tsx`, `workspace.tsx`), pages `P/pages`, `P/views`; their files `src/routes/_crm/**` (a pathless layout: they map to `/`, `/tasks`, `/$object`) -- **Alerts: what the CRM says to whoever is using it.** `P/crm/ui/alerts.tsx`: `AlertsProvider` (one, in the shell) holds and draws them, `useAlerts()` raises them (`show`, `change`, `dismiss`, `during`), and `onAlert` in `defineSpoolUi` hears every one. A layout raises one with `@Alert` (`alertAction` in `P/crm/openui/specs.ts`, handled in `render.tsx`). The CRM's own parts report a refused save or an action's end through it, never in a line of their own. A save that works says nothing. docs/alerts.md -- **Layouts: pages and record pages a Spool lays out itself (`ui` in `crm.config.json`, OpenUI Lang).** The schema, who is shown which and the config's checks in `P/crm/layouts.ts` (pure, shared). The Spools kit is ours, not a vendor's: each component's name, arguments and description in `P/crm/openui/specs.ts`, the tools' names and shapes in `P/crm/openui/tools.ts`, a `records` or `summary` tool's `where` as filters in `P/crm/openui/where.ts`, what a `summary` makes of the records it read and where records stand on `Steps` in `P/crm/openui/summary.ts` (pure), and checking a layout and the agent prompt in `P/crm/openui/check.ts` (no React: `spools gen` and `spools ui check|prompt` in `P/cli/ui.ts` run it). What draws each component is `P/crm/ui/openui/components.tsx`; the renderer, loaded only by a page that has a layout, `P/crm/ui/openui/render.tsx`; what each tool does `P/crm/ui/openui/tools.ts`, which calls the server functions the CRM's own pages use plus `layoutRecordsFn` and `layoutSummaryFn` (`P/server/layouts.ts`; a summary reads every match through `listRecords`, a page at a time, up to `MAX_SUMMARY_ROWS`), so a layout is presentation only and never a way around access. A new kit component is a spec, a renderer (`kit` must satisfy every spec's name) and a row in docs/layouts.md. Pages: `P/pages/custom.tsx` (`/pages/$page`), `P/views/record-layout.tsx` (chosen by `RecordPage` in `P/views/record.tsx`; `?view=classic` is the classic page). An app's own components: `defineLayoutComponent` in `P/crm/ui/slots.tsx`. Only `@openuidev/lang-core` and `@openuidev/react-lang` are imported, never a ready-made component kit. docs/layouts.md -- **CRM colours.** Override `.crm { --c-accent: … }` in `src/styles.css`; tokens are in `P/crm/ui/theme.css` -- **Saved views, footer calculations.** `P/server/views.ts` -- **Speed of moving between pages.** The browser keeps the session and what relation pickers were last given between pages (`P/crm/memory.ts`, pure; wired in `P/crm/ui/session.ts`), and the router reuses a page's data for a few seconds and refreshes it behind after that (`P/crm/ui/router.tsx`). After any change, call `router.invalidate()`: it reloads the page and forgets what was remembered. Lists ask for related records by title only (`relations: "titles"` in `listRecords`) and boards for the card's fields only (`fields`); look up many titles with `recordTitlesOf`, never one `getRecord` per row. On Vercel or another serverless host (`config.serverless`), `/api/cron/warm` keeps the function from going cold (docs/deployment.md) -- **Logged calls and meetings, team activity report.** Kinds, outcomes, date ranges and the per-person counts in `P/crm/activity.ts` (pure, shared); storage and queries in `P/server/workspace.ts` -- **Teammates' mail and calendar, sending from their mailbox.** Through the Google or Microsoft account they sign in with (the auth provider keeps its tokens) and any mailbox they connected on the Integrations page. Scopes and what they allow in `P/crm/mailbox.ts` (pure, shared); sign-in accounts and the auth provider's tokens through the `SignIns` service (`P/server/sign-ins.ts`); accounts from both sources, tokens, provider calls (the `mailApi` policy: reads retried on 429/5xx with `Retry-After`, sends never repeated) and sending in `P/server/mailbox.ts`; provider readers (Gmail, Graph), matching addresses to records, `ingest` and the schedule (`syncSchedule`, a fiber started by `startSync` in `src/server.ts`) in `P/server/sync.ts`; cron entry `src/routes/api/cron/mail-sync.ts`; panel `P/crm/ui/mailbox.tsx`. Synced activities carry `externalId` and go through `addActivityOnce`; docs/mailbox.md -- **Files.** A file browser over the `FileStore` port (`P/server/runtime/files.ts`), whose adapters are `P/adapters/files/*`. Names and limits in `P/crm/files.ts` (pure, shared); breadcrumbs, listing, record folders (`record_folders`), uploads (`file_uploads`) and the library in `P/server/files.ts`; server functions `P/server/files.functions.ts`; handlers `P/api/file.ts`, `P/api/upload.ts`; the browser `P/crm/ui/files.tsx`, used by the Files page and a record's Files tab. An object opts in with `files: { folders, under }`; top-level `files` names the shared library. Tests of the FlashDrive adapter use ``createFakeStore`from`@swirls/spools/testing` (`P/testing/fake-file-store.ts`)`; an app's hooks reach record folders through `@swirls/spools/extensions`; docs/files.md -- **Accounts teammates connect (more mailboxes, other services).** OAuth flow, token refresh and the built-in Google and Microsoft providers in `P/server/integrations.ts`; tokens are sealed by the `Vault` port (`P/server/runtime/vault.ts`; adapters `P/adapters/vault/*`; no plaintext fallback) before they reach the `integrations` table; token exchange and refresh go through `HttpClient` with the `oauth` policy. Handlers `P/api/integration-*.ts`, page `P/pages/integrations.tsx`. An app adds a provider under `integrations` in `src/app/extensions.ts` and gets tokens from `getAccessToken` in `@swirls/spools/extensions`. A connection is its teammate's own unless its provider says `shared: 'team'` or `shared: 'group'` (with `groups`, and `canManage` for who may connect and disconnect): the row says whose it is (`shared`, `groupKey`), its tokens are sealed for that (`ownerOf`), the signed `state` carries it (`readState`), and nothing about a shared connection may depend on its connector still being on the access list. Who may use one is decided in one place (`usableBy`), who may manage one in another (`mayManage`), and what the page is sent is built in `connectionsOverview`. A token renewal runs beside whoever asked for it (`tokenOnce`), never inside their request: a request is interrupted when its browser goes away, and a renewal must finish. Tests use `Vault.layerTest` through `installStandIns`; docs/integrations.md -- **Marketing: the website's tags, social posts, ad results.** Set up under `marketing` in `crm.config.json`, which is what makes the Marketing page appear. Tags (how each is found in a page, its install code), post limits and UTM parameters in `P/crm/marketing.ts` (pure, shared). The engine is `P/server/marketing.ts`: the site scan (the `website` policy), posts (`marketing_posts`) and ad results (`marketing_ads`). Networks are a registry (`P/server/marketing-networks.ts`): the built-in ones (linkedin, x, facebook; meta, google) call each API through `HttpClient` with the `marketingApi` policy (reads retried, a post never), and an app adds or replaces one under `marketing` in `src/app/extensions.ts`. A network gets its token from the environment or from a teammate's connection (`accessToken`); the OAuth providers for the built-in ones are in `P/server/marketing-providers.ts` and are offered on the Integrations page only while the config uses them. A channel or ad account is reached `direct` (that code) or `via: "swirls"` (`publish_` / `ads_` through `Agents.executeWorkflow`, answered by the tools `post_result` and `save_ads`); `site_profile` is always a workflow. A post is taken with one `Store.update` (`hold`) and never sent twice: a `NetworkFailure` that is `uncertain` leaves a note to look at the channel first. Scheduling and publishing are server functions only (`P/server/marketing.functions.ts`): the tool API can draft and nothing more. `tick` publishes what is due (`startMarketing`, or `/api/cron/marketing` on a serverless host). Tests replace `MarketingSource` (`P/server/marketing-source.ts`), `Agents` and `fetch` through `installStandIns`. Workflows: `swirls/marketing.swirls` (`site_profile`) and `examples/swirls/marketing-networks.swirls` (every network, for `via: "swirls"`); docs/marketing.md -- **Tasks, notes, favourites, reports, CSV export.** `P/server/workspace.ts` + `P/server/workspace.functions.ts`; CSV parsing in `P/crm/csv.ts` -- **Choosing a related record.** `P/crm/ui/relation-picker.tsx`: `RelationInput` (forms), `RelationPopover` (inline editing), `RelationSearch` (the list filter). It searches the server as you type (`searchTitles` in `P/server/records.ts`, through `searchRelationFn`); never send a page the list of records a relation could point at. A value known only by its id gets its title from `titles` when the page has it (a list sends the ones its filters name) or from `relationTitlesFn`. CSV import matches names on the server (`matchTitles`) -- **Many-to-many relations (`"type": "relations"`).** A field with no column: its links are rows of a table of their own, described in `P/server/store/objects.ts` (`linkTables`, `linkSide`: which column is this record's, which the other's, and the relation from the object's table to its links). Names, limits and which side owns the table (the one without `inverse`) in `P/crm/links.ts` (pure, shared). Only `P/server/records.ts` reads and writes links (`withLinks`, `writeLinks`, `removeLinks`), through the store with ordinary conditions. `withLinks` reads the links of a whole page in two reads for each field, however many links a row has: a count for each row, then the first of each row's with `perGroup` (never one read for each row); `changeRecord` says what a write linked and let go, which `service.ts` puts on the timeline. Written as `Ids`: a list replaces the set (refused when the record holds more than a read shows), `{ add, remove }` changes it, and the interface always sends the second (`P/crm/links-form.ts`, pure: the change a form sends, and whether a picker knows a record is held). A write to links happens with its records held, always in the one order (`holdRecords`, over `inHoldOrder` in `P/server/store/hold.ts`: by table name, then id), which is what keeps two changes to the same links from deadlocking or writing a pair twice. A change holds its record and the records it names (`holdRecord`), a new record holds the records it names before it is made, and a delete holds its record. Links whose other end is not held are held themselves, after the records and before the first link is written (`holdLinks`: links tables by name, a table's rows by id, all of a change's fields together): the ones a list that replaces lets go of, and every link of a record being deleted. Never write a link first and hold a record after, never hold one end and then the other, and never hold or write links field by field in the order an object has its fields. Their tests run on a Spool of their own (`packages/spools/tests/support/relations-spool.ts`), which on Postgres needs `bun run db:push:relations` first. Filters (`anyOf`, `allOf`, `noneOf`) compile to `related` conditions in `P/server/filter-query.ts`. The picker is `RelationsInput` in `P/crm/ui/relation-picker.tsx`. A field key must never reach a store `select`, order or `where` unless its type has a column (`fieldTypes[type].column`) +- **The assistant's chat.** Pure helpers (chat groups, titles, tool steps, linked records) `P/core/assistant.ts`; operations `P/server/operations/assistant.ts`; the streaming endpoint `P/api/assistant-stream.ts`. The agent engine keeps the chats; the server side gets one only through `Agents.chat` (`P/server/runtime/agents.ts`). Its name, and what it is denied: `assistant` in `spool.config.json`. docs/swirls.md#the-assistant +- **Email sequences (campaigns).** When each email is due, and sending hours, in `P/core/sequences.ts` (pure). The engine is `P/server/campaigns.ts`: an enrolment is a row in `sequence_runs`, and `tick` sends what is due. `startSequences` forks `sequenceSchedule` (a tick now, then once a minute) on a server that stays up; on a serverless host a cron job calls `/api/cron/sequences` (`P/api/sequences.ts`). Nothing is kept in memory or on disk. A run is taken with one `Store.update` that checks and changes it (`hold`), never by reading then writing, or two ticks send the same email. Every send carries an `idempotencyKey`, and only a send that has one is retried (the `resend` policy). Transport: the app's `email.send`, else the `Email` port (`P/server/runtime/email.ts`); templates, unsubscribe tokens and suppression in `P/server/email.ts`; unsubscribing in `P/server/operations/email.ts`. Tests replace `Email` and `Sequences` (`P/server/sequences.ts`) through `installStandIns`; docs/campaigns.md +- **What a front end is built on.** The typed client `P/client.ts`; query and mutation options `P/query.ts`; React hooks that hold state and draw nothing `P/react.ts` (`useListState`, `useRecordForm`, `useRelationSearch`), over pure rules in `P/core/list-state.ts`, `P/core/record-state.ts`, `P/core/links-form.ts` and `P/core/reach.ts`, published together as `@swirls/spools/state` (`P/state.ts`). `createClient` marks, in types only, which objects it was made for (`MadeFor`), which is how `createQueries` knows them. Tests: `tests/unit/client.test.ts`, `query.test.ts`, `react.test.ts`, `list-state.test.ts`, `record-state.test.ts`. A working one: `examples/tanstack-start`. docs/front-ends.md +- **Pages the server sends a browser to.** It draws none, and knows where three of the front end's are: `frontEnd` in `defineSpool` (`P/server/front-end.ts`: `toPage`, `pageFrom`). Never write a front end's address into a handler. The link in an email is answered by `P/api/unsubscribe.ts` when the front end has no page for it. An app's route under `routes` in `headlessServer` must be made by a route adapter (`madeByAdapter` in `P/server/runtime/boundary.ts`), or the server does not start +- **Saved views, calculations over a list.** `P/server/views.ts`. A view is a named filter and sort (`{ id, label, sort, filters }`); which columns, cards or totals a list shows is the front end's, asked for with `fields` and `calculations` on `records.list` +- **Reading many records cheaply.** Lists ask for related records by title only (`relations: "titles"` in `listRecords`) and for the fields they show only (`fields`); look up many titles with `recordTitlesOf`, never one `getRecord` per row. On Vercel or another serverless host (`config.serverless`), `/api/cron/warm` keeps the function from going cold (docs/deployment.md) +- **Logged calls and meetings, team activity report.** Kinds, outcomes, date ranges and the per-person counts in `P/core/activity.ts` (pure, shared); storage and queries in `P/server/workspace.ts` +- **Teammates' mail and calendar, sending from their mailbox.** Through the Google or Microsoft account they sign in with (the auth provider keeps its tokens) and any mailbox they connected on the Integrations page. Scopes and what they allow in `P/core/mailbox.ts` (pure, shared); sign-in accounts and the auth provider's tokens through the `SignIns` service (`P/server/sign-ins.ts`); accounts from both sources, tokens, provider calls (the `mailApi` policy: reads retried on 429/5xx with `Retry-After`, sends never repeated) and sending in `P/server/mailbox.ts`; provider readers (Gmail, Graph), matching addresses to records, `ingest` and the schedule (`syncSchedule`, a fiber started by `startSync` in `src/server.ts`) in `P/server/sync.ts`; cron entry `P/api/mail-sync.ts`; operations `P/server/operations/mailbox.ts`. Synced activities carry `externalId` and go through `addActivityOnce`; docs/mailbox.md +- **Files.** Folders and files over the `FileStore` port (`P/server/runtime/files.ts`), whose adapters are `P/adapters/files/*`. Names and limits in `P/core/files.ts` (pure, shared); breadcrumbs, listing, record folders (`record_folders`), uploads (`file_uploads`) and the library in `P/server/files.ts`; operations `P/server/operations/files.ts`; handlers `P/api/file.ts`, `P/api/upload.ts`. An object opts in with `files: { folders, under }`; top-level `files` names the shared library. Tests of the FlashDrive adapter use ``createFakeStore`from`@swirls/spools/testing` (`P/testing/fake-file-store.ts`)`; an app's hooks reach record folders through `@swirls/spools/extensions`; docs/files.md +- **Accounts teammates connect (more mailboxes, other services).** OAuth flow, token refresh and the built-in Google and Microsoft providers in `P/server/integrations.ts`; tokens are sealed by the `Vault` port (`P/server/runtime/vault.ts`; no plaintext fallback), whose adapters are CipherStash (`P/adapters/vault/cipherstash`, the one a new Spool starts with) and AES under a key the app keeps (`P/adapters/vault/aes`, `VAULT_KEY`): a production server does not start without its vault's variables, and outside production without them `P/adapters/vault/stand-in.ts` seals with a key that is in the source (`vaultFor` and `aesVaultFor` say which), so a new vault adapter does the same and never seals with nothing or stores plaintext; token exchange and refresh go through `HttpClient` with the `oauth` policy. Handlers `P/api/integration-*.ts`, operations `P/server/operations/integrations.ts`. An app adds a provider under `integrations` in `src/app/extensions.ts` and gets tokens from `getAccessToken` in `@swirls/spools/extensions`. A connection is its teammate's own unless its provider says `shared: 'team'` or `shared: 'group'` (with `groups`, and `canManage` for who may connect and disconnect): the row says whose it is (`shared`, `groupKey`), its tokens are sealed for that (`ownerOf`), the signed `state` carries it (`readState`), and nothing about a shared connection may depend on its connector still being on the access list. Who may use one is decided in one place (`usableBy`), who may manage one in another (`mayManage`), and what a front end is sent is built in `connectionsOverview`. A token renewal runs beside whoever asked for it (`tokenOnce`), never inside their request: a request is interrupted when its browser goes away, and a renewal must finish. Tests use `Vault.layerTest` through `installStandIns`; docs/integrations.md +- **Marketing: the website's tags, social posts, ad results.** Set up under `marketing` in `spool.config.json`. Tags (how each is found in a page, its install code), post limits and UTM parameters in `P/core/marketing.ts` (pure, shared). The engine is `P/server/marketing.ts`: the site scan (the `website` policy), posts (`marketing_posts`) and ad results (`marketing_ads`). Networks are a registry (`P/server/marketing-networks.ts`): the built-in ones (linkedin, x, facebook; meta, google) call each API through `HttpClient` with the `marketingApi` policy (reads retried, a post never), and an app adds or replaces one under `marketing` in `src/app/extensions.ts`. A network gets its token from the environment or from a teammate's connection (`accessToken`); the OAuth providers for the built-in ones are in `P/server/marketing-providers.ts` and are offered for connecting only while the config uses them. A channel or ad account is reached `direct` (that code) or `via: "swirls"` (`publish_` / `ads_` through `Agents.executeWorkflow`, answered by the tools `post_result` and `save_ads`); `site_profile` is always a workflow. A post is taken with one `Store.update` (`hold`) and never sent twice: a `NetworkFailure` that is `uncertain` leaves a note to look at the channel first. Scheduling and publishing are operations only (`P/server/operations/marketing.ts`): the tool API can draft and nothing more. `tick` publishes what is due (`startMarketing`, or `/api/cron/marketing` on a serverless host). Tests replace `MarketingSource` (`P/server/marketing-source.ts`), `Agents` and `fetch` through `installStandIns`. Workflows: `swirls/marketing.swirls` (`site_profile`) and `examples/swirls/marketing-networks.swirls` (every network, for `via: "swirls"`); docs/marketing.md +- **Tasks, notes, favourites, reports, CSV export.** `P/server/workspace.ts` + `P/server/operations/workspace.ts`; CSV parsing in `P/core/csv.ts` +- **Choosing a related record.** A picker searches the server as someone types (`searchTitles` in `P/server/records.ts`, the operation `records.searchTitles`; the hook `useRelationSearch` in `P/react.ts`); never send a front end the list of records a relation could point at. A value known only by its id gets its title from `titles` when the answer has it (a list sends the ones its filters name) or from `records.titles`. CSV import matches names on the server (`matchTitles`) +- **Many-to-many relations (`"type": "relations"`).** A field with no column: its links are rows of a table of their own, described in `P/server/store/objects.ts` (`linkTables`, `linkSide`: which column is this record's, which the other's, and the relation from the object's table to its links). Names, limits and which side owns the table (the one without `inverse`) in `P/core/links.ts` (pure, shared). Only `P/server/records.ts` reads and writes links (`withLinks`, `writeLinks`, `removeLinks`), through the store with ordinary conditions. `withLinks` reads the links of a whole page in two reads for each field, however many links a row has: a count for each row, then the first of each row's with `perGroup` (never one read for each row); `changeRecord` says what a write linked and let go, which `service.ts` puts on the timeline. Written as `Ids`: a list replaces the set (refused when the record holds more than a read shows), `{ add, remove }` changes it, and a form always sends the second (`P/core/links-form.ts`, pure: the change a form sends, and whether a picker knows a record is held; `useRecordForm` uses it). A write to links happens with its records held, always in the one order (`holdRecords`, over `inHoldOrder` in `P/server/store/hold.ts`: by table name, then id), which is what keeps two changes to the same links from deadlocking or writing a pair twice. A change holds its record and the records it names (`holdRecord`), a new record holds the records it names before it is made, and a delete holds its record. Links whose other end is not held are held themselves, after the records and before the first link is written (`holdLinks`: links tables by name, a table's rows by id, all of a change's fields together): the ones a list that replaces lets go of, and every link of a record being deleted. Never write a link first and hold a record after, never hold one end and then the other, and never hold or write links field by field in the order an object has its fields. Their tests run on a Spool of their own (`packages/spools/tests/support/relations-spool.ts`), which on Postgres needs `bun run db:push:relations` first. Filters (`anyOf`, `allOf`, `noneOf`) compile to `related` conditions in `P/server/filter-query.ts`. A field key must never reach a store `select`, order or `where` unless its type has a column (`fieldTypes[type].column`) - **Links under record scopes, and the order rows are held in.** A links table with a scoped object at either end is marked `scope: { kind: 'link' }` (`P/server/store/objects.ts`) and has no scope column: the guard (`P/server/store/scope.ts`) narrows it through its two relations, so a link is read by whoever reads each scoped record it joins and written by whoever writes them, never joins two scopes, and blocks a move or a delete that would leave it across scopes or remove it out of the caller's reach. Read and write links through `records.ts` as before; nothing there checks scopes itself. Rows are held in one order (`inHoldOrder` and `holdAll` in `P/server/store/hold.ts`): records by table name and then id, then rows of links tables by table name. `holdRecords` and `holdLinks` in `records.ts` and the guard's own holds all go through it, and anything new that holds rows of more than one table must too: there is no second implementation. With scopes, what a change names includes the scoped records its relation fields point at (`namedBy`). A `find` with `perGroup` is narrowed like any other: the scope is in the condition, and the backend cuts each group after it. Only a database adapter touches what is under the guard (`sqlBackend`, `findWith`, `rowsOf`): `packages/spools/tests/unit/scopes.test.ts` fails if framework code imports them. A line on a shared record's timeline counts scoped records and never names them (`namesOutOfScope` in `P/server/service.ts`). Tests: `packages/spools/tests/integration/scopes-links.test.ts`, on the fixture `tests/fixtures/scoped.config.json` (run `bun run test:scopes:gen` in `packages/spools` after changing it). docs/security.md#record-scopes - **A test's own Spool (a fixture config, modules).** `openFixtureStore` in `packages/spools/tests/support/fixture-store.ts`: a PGlite of its own, or on `TEST_STORE=postgres|prisma` a database beside `DATABASE_URL` (`_`) pushed with the Spool's own Prisma schema, as an app's would be. Every new suite that defines a Spool uses it, so it runs on every store - **An app's own door for outside callers.** No framework concept: an app builds it behind `publicRoute` from small helpers in `@swirls/spools/extensions` (docs/extending.md#building-your-own-door): `bearerToken`, `callerAddress` (`TRUST_PROXY`), `verifyToken` (the auth adapter's optional `tokens`, the `Tokens` port `P/server/runtime/tokens.ts`; Clerk's keyring `P/adapters/auth/clerk/keyring.ts`, no network call per token), `hitLimit`/`consumeLimit` (the `RateLimiter` port `P/server/runtime/rate-limit.ts`, adapters `P/adapters/rate-limits/*`; app buckets are `app:`), `idempotent` (`P/server/idempotency.ts`, `idempotent_requests`; the claim is the insert, the work runs as it would without a key; app callers are `app:`, staff `staff:`), `changedSinceAs`, `sealText`/`openText`, `writeKeptFields`. Promise wrappers in `P/server/extension-api.ts`, Effect forms in `P/server/callers.ts`, `P/server/runtime/boundary.ts` (`idempotent`). What must hold across servers (a claim, a limit) is raced from runtimes of the test's own (`tests/support/servers.ts`), in the door world (`tests/integration/door-world.ts`). - **Record CRUD.** `P/server/records.ts` (data) under `P/server/service.ts` (hooks, timeline, automations) -- **Record rules, role access, change signals, live pages.** Rules: `P/crm/rules.ts` (pure), `P/server/record-rules.ts` (checks, `Conflict` from a database refusal with `clashOr`, the `spools rules` pre-flight `uniqueViolations`), the indexes in `P/server/store/schema-sql.ts` (`conditionSql`, PGlite) and `P/crm/codegen.ts` (Prisma `@@index(..., unique: true, where:)`); tests `tests/integration/rules.test.ts` on `tests/fixtures/rules.config.json`. Role access: `objectAccess` in `P/crm/roles.ts`, enforcement `P/server/object-access.ts`, every read path walked in `tests/integration/role-access.test.ts`. Signals: the `change_signals` table, `P/server/signals.ts` (`touchRecord`/`touchHanging` queue with `afterCommit` in `P/server/store/store.ts`; `changedSince`, `changedSinceFor`), `changedSinceFn` in `P/server/crm.functions.ts`, the pages' hook `P/crm/ui/live.ts` (`live` in the config). docs/configuration.md#record-rules, docs/roles.md#access -- **Filters and sorting.** What a condition is, the operators each field type has (and each encryption mode allows), relative dates (in days for every date, and to the minute for a `datetime`: `MINUTE_OPS`) and `cleanFilters` in `P/crm/filters.ts` (pure, shared). `P/server/filter-query.ts` turns conditions into a store predicate for `listRecords` and `countMatching`. Everything that arrives from a page address, a saved view, the config or the assistant goes through `cleanFilters` first: it drops what the config doesn't allow and cuts a filter back to the size limits declared beside it (a filter fits in a link, so its cost must be bounded). Server function validators check shape only and never refuse a filter for its size or contents. The filter box, chips and editors are `P/crm/ui/filter-bar.tsx`; what typed text offers is `P/crm/suggest.ts` (pure). Filters and sort a person changes live in the list page's address (`f`, `s`) until saved to the view. docs/search-and-filters.md -- **Search (Cmd+K).** Records are matched in the browser against an index of titles and unencrypted `searchable` fields: matching, ranking and the index store in `P/crm/search.ts` (pure), built by `quickIndex` in `P/server/search.ts`, held by `searchIndex` in `P/crm/ui/session.ts`. Never put an `encrypted` field other than the title in it, nor long text. Notes, emails, calls and tasks are searched by `deepSearch` (Postgres full-text indexes declared in `P/crm/codegen.ts`). The palette is `P/crm/ui/search.tsx` -- **Guides (the tours that show people around).** What a guide is, the built-in ones, which is offered where and the config checks in `P/crm/guides.ts` (pure, shared). An app replaces, turns off or adds guides under `guides` in `crm.config.json`, never in framework files; the welcome is offered first, then guides for one object, then the rest. Steps point at `data-guide` anchors (listed in `ANCHORS`); a step whose anchor is missing from the page is left out, so write each step to be true whenever its anchor is there. What each person has finished or dismissed is the `guide_progress` table (`P/server/guides.ts`, server functions in `P/server/guides.functions.ts`, which take no user id); it reaches the browser with the session, so offering a guide must never add a request. The offer, the step card and the Help menu are `P/crm/ui/guides.tsx`: nothing in it may be modal or take focus unasked. `CRM_GUIDES=off` stops offers (the e2e harness sets it). When a page gains or loses something a guide mentions, update the guide and docs/guides.md with it -- **Last activity, last contacted, next task due.** Columns on every object's table, recomputed by `refreshStats` in `P/server/records.ts` whenever an activity or task is written (`addActivity`, the task functions in `workspace.ts`). Which activity kinds count is in `P/crm/filters.ts`. Write activities through `addActivity`, or run `bun run db:stats` afterwards (it exits non-zero if any object fails) -- **Tables and the schema.** Described in `P/server/store/tables.ts` (system) and `objects.ts` (from the config). `P/crm/codegen.ts` (pure) turns them into Prisma's schema for `spools gen` (`P/cli/gen.ts`); `P/server/store/schema-sql.ts` into the SQL PGlite makes for itself. A change here must leave `prisma/schema.json` as it was unless it means to change the database +- **Record rules, role access, change signals.** Rules: `P/core/rules.ts` (pure), `P/server/record-rules.ts` (checks, `Conflict` from a database refusal with `clashOr`, the `spools rules` pre-flight `uniqueViolations`), the indexes in `P/server/store/schema-sql.ts` (`conditionSql`, PGlite) and `P/core/codegen.ts` (Prisma `@@index(..., unique: true, where:)`); tests `tests/integration/rules.test.ts` on `tests/fixtures/rules.config.json`. Role access: `objectAccess` in `P/core/roles.ts`, enforcement `P/server/object-access.ts`, every read path walked in `tests/integration/role-access.test.ts`. Signals: the `change_signals` table, `P/server/signals.ts` (`touchRecord`/`touchHanging` queue with `afterCommit` in `P/server/store/store.ts`; `changedSince`, `changedSinceFor`), the operation `changes.since` in `P/server/operations/core.ts` (`live` in the config says how often a front end should ask). docs/configuration.md#record-rules, docs/roles.md#access +- **Filters and sorting.** What a condition is, the operators each field type has (and each encryption mode allows), relative dates (in days for every date, and to the minute for a `datetime`: `MINUTE_OPS`) and `cleanFilters` in `P/core/filters.ts` (pure, shared). `P/server/filter-query.ts` turns conditions into a store predicate for `listRecords` and `countMatching`. Everything that arrives from a page address, a saved view, the config or the assistant goes through `cleanFilters` first: it drops what the config doesn't allow and cuts a filter back to the size limits declared beside it (a filter fits in a link, so its cost must be bounded). An operation's input schema checks shape only and never refuse a filter for its size or contents. Filters and sort a person changes live in a list page's address (`f`, `s`) until saved to the view: `P/core/list-state.ts` reads and writes that address, and `useListState` holds it. docs/search-and-filters.md +- **Search.** A front end matches records itself against an index of titles and unencrypted `searchable` fields: matching, ranking and the index store in `P/core/search.ts` (pure), built by `quickIndex` in `P/server/search.ts`. Never put an `encrypted` field other than the title in it, nor long text. Notes, emails, calls and tasks are searched by `deepSearch` (Postgres full-text indexes declared in `P/core/codegen.ts`) +- **Last activity, last contacted, next task due.** Columns on every object's table, recomputed by `refreshStats` in `P/server/records.ts` whenever an activity or task is written (`addActivity`, the task functions in `workspace.ts`). Which activity kinds count is in `P/core/filters.ts`. Write activities through `addActivity`, or run `bun run db:stats` afterwards (it exits non-zero if any object fails) +- **Tables and the schema.** Described in `P/server/store/tables.ts` (system) and `objects.ts` (from the config). `P/core/codegen.ts` (pure) turns them into Prisma's schema for `spools gen` (`P/cli/gen.ts`); `P/server/store/schema-sql.ts` into the SQL PGlite makes for itself. A change here must leave `prisma/schema.json` as it was unless it means to change the database - **A database adapter, or the store port.** `P/server/store/store.ts` (the port, `Backend`, `makeStore`), `sql.ts` (conditions as Postgres SQL, pure), `sql-store.ts` (a store over Effect's `SqlClient`); adapters `P/adapters/database/*`; what a store promises is `packages/spools/tests/unit/store.test.ts`. docs/database.md -- **Auth.** The port `P/server/runtime/auth.ts` (directory, `session`, `handle`) and `P/crm/ui/auth.tsx` (browser half); adapters `P/adapters/auth/*`. Who may use the CRM is `P/server/users.ts`, from the config's access list and the verified email. docs/auth.md +- **Auth.** The port `P/server/runtime/auth.ts` (directory, `session`, `handle`); adapters `P/adapters/auth/*`. Who may use the Spool is `P/server/users.ts`, from the config's access list and the verified email. docs/auth.md - **What an app may import.** `exports` in `packages/spools/package.json`; listed for people in docs/api.md - **A `spools` command.** `P/cli/.ts`, named in `P/cli/main.ts`, with a row in docs/api.md and, when an app runs it often, a script in `apps/starter/package.json` - **Documentation.** `docs/.md`, each listed in `apps/docs/src/nav.ts`. `bun run index-docs` in `apps/docs` rewrites `apps/docs/src/docs-manifest.json`, and `apps/docs/src/docs.test.ts` fails when it is stale, a page is missing from the menu, or a link between pages or to a file in the repository leads nowhere. What an existing app must do after an update goes in `docs/upgrading.md` and the changeset. What a new Spool's agent is told is `packages/create-spools/overrides/AGENTS.md` - **What a new Spool starts as.** `apps/starter`, through `packages/create-spools/scripts/template.ts`, with `packages/create-spools/overrides` on top. `bun run check:package` makes one from the packed packages and runs it - **Env vars.** `.env.example`, the `Config` declaration (and `features` entry, for the boot report) in `P/server/runtime/config.ts`; required ones in `P/server/env.ts` - **New server module.** `P/server/.ts` with `Effect.fn` functions; tests use `run`/`failure` (integration) or `testRuntime` with fake layers (unit) from `@swirls/spools/testing` (`P/testing/run.ts`). docs/server-code.md -- **New server function or API route.** `.handler(crmHandler("name", ({ data, user }) => program))` (or `publicHandler` for signed-out pages); routes use an adapter from `P/server/runtime/boundary.ts`. Lint enforces both +- **New API route, or an app's own server function.** Routes use an adapter from `P/server/runtime/boundary.ts`; an app on TanStack Start writes `.handler(staffHandler("name", ({ data, user }) => program))` (or `publicHandler` for signed-out callers). Lint enforces both - **Errors staff see.** A `Schema.TaggedError` with a staff-readable `message` (shared ones in `P/server/runtime/errors.ts`, a module's own next to it), added to `StaffError`. The boundary shows the message as it is; anything else is logged in full and rethrown - **New outside service, time limits and retries.** A port in `P/server/runtime/` with a stand-in, an adapter in `P/adapters//` (only it imports the SDK; HTTP goes through Effect's `HttpClient`, never `fetch`), a row in `policies.ts` (`withPolicy`), its option in `defineSpool` and its layer in `appLayer` (`runtime/app.ts`) +- **Something the Spool does for whoever asks (a new operation).** An operation in `P/server/operations/.ts` (`staff` or `open` from `define.ts`: name `area.verb`, `kind`, `summary`, zod `input`, `run`), listed in `P/server/operations/index.ts`. Nothing more binds it: the HTTP API (`httpApi` in `P/server/http.ts`, `@swirls/spools/http`) answers every listed operation at `POST /`, and the typed client (`P/client.ts`) knows it by name, so the name and the shape of its input and answer are a public contract: changing one is a breaking change. `callAs` (`P/server/api.ts`) runs one from server code as a teammate. The server's side imports no web framework: TanStack Start is bound in `P/start.ts` (which tells the boundary how to reach a server function's request, `P/server/runtime/host.ts`) and `P/start-client.ts`, React in `P/react.ts`, and `packages/spools/tests/unit/framework-free.test.ts` fails for anything else. For an app on TanStack Start: `serveApi` (`P/api/http.ts`) is the API as an endpoint's handlers, mounted by two route files of the app's (`examples/tanstack-start/src/routes/api`); `startClient` (`P/start-client.ts`, `@swirls/spools/start/client`) is the typed client that asks the API in this process on the server and over HTTP in the browser, and names the server only inside `.server(...)` because the browser loads the file too; `createQueries` (`P/query.ts`, `@swirls/spools/query`) gives operations as query and mutation options and imports nothing but the client's types. `headlessServer` (`P/headless.ts`, `@swirls/spools/headless`) is a whole Spool with no web framework, which the starter's `src/server.ts` serves: the HTTP API, every handler in `P/api` at its address (`routes`), and the app's own under the `routes` option. A caller of the HTTP API is known by the session cookie (same site only), a sign-in token (`tokens.authorizedParties`) or an API key (`P/server/api-keys.ts`, the `api_keys` table, `spools keys` in `P/cli/keys.ts`): a key acts as one teammate through `forStaff`, never as the system, and no operation makes one. Keys are taken only with `keys: true` on `httpApi`, end after `DEFAULT_DAYS` unless made with `neverExpires`, and are kept sealed by the `Vault` for their own row (`sealKey`: the hash of the secret and the row's user, read-only flag and expiry), which is what a key is judged by, so a row written by hand or changed opens nothing and a Spool with no vault has no keys: anything new a row says a key may do goes under the seal. A read-only key is refused every `write` operation, and its reads run with `ReadOnlyCaller` (`P/server/runtime/access.ts`) set: anything a read does on the side outside the database (making the file library) checks it. An operation a front end is built on says what it answers (`answer`, schemas in `P/server/operations/answers.ts`), which the OpenAPI document carries and `tests/integration/http.test.ts` holds each real answer to. An idempotent answer is sealed for its caller's access (`accessMark` in `P/server/runtime/boundary.ts`), so a repeat after their access changed is withheld. The types of an app's records for its own front end are written by `spools gen` (`P/core/codegen-types.ts`, pure, to `src/spool.types.ts`). Clerk's adapter is `P/adapters/auth/clerk/core.ts`, given its client and session by `server.ts` (TanStack Start) or `backend.ts` (no web framework: the cookie only, never a bearer token). Tests: `tests/integration/http.test.ts`, `tests/unit/clerk-backend.test.ts`, `tests/unit/codegen-types.test.ts`. docs/front-ends.md - **Calling Effect code from promise code.** `src/app/extensions.ts`: `@swirls/spools/extensions` (`P/server/extension-api.ts`). Scripts: `runServer(program)` and `disposeRuntime()` from `P/server/runtime/app.ts`. Never `await` a framework function directly: it returns an Effect, and awaiting it does nothing - **Calling promise code from Effect code.** The app's own hooks, handlers and settings: `fromHook` (`runtime/errors.ts`) @@ -202,7 +204,7 @@ In the rest of this file `P` is `packages/spools/src`, and a path that starts wi At the root, over every workspace: ```sh -bun run dev # the starter on :3000 and the website on :8788 +bun run dev # the starter's API on :3000 and the website on :8788 bun run demo # the starter alone bun run docs # the website alone bun run verify # everything below @@ -217,56 +219,43 @@ bun run check:package # builds and packs the packages, makes a new Spool fr bun run changeset ``` -`bun run test:e2e` runs the browser tests (Playwright, Chromium) in `apps/starter/e2e/tests` against the stubbed-sign-in build, on seeded databases of their own; it is not part of `verify`, and CI runs it as the `e2e` job. One of its servers is the starter with record scopes laid over its config (`e2e/scoped.ts`, seeded by `e2e/seed-scoped.ts`, tests in `scopes.e2e.ts`); a test is one of its people by the `e2e_as` cookie. -Connecting accounts is tested there against a stand-in OAuth provider (`e2e/provider.ts`) and the providers in `e2e/extensions.ts`; a second person is the teammate the `e2e_as` cookie names (`e2e/spool.server.ts`). The staff and scoped servers both use the provider, and both have the harness's tags. `E2E_PORT` moves its six ports (default 4310 to 4315). -The starter has no many-to-many relation, so the harness adds a Tags object to its config for those tests (`e2e/tags.ts`, switched on by `E2E_TAGS=on`, which `e2e/serve.ts` sets) and seeds it (`e2e/seed.ts`); the starter's own config and schema stay as they are. -The first run needs `bunx playwright install chromium`. When a page's roles, labels or wording change, change the tests that read them. - In `apps/starter`: ```sh -bun run dev # http://localhost:3000; with no keys set, PGlite and the development sign-in +bun run dev # the API on http://localhost:3000/api/v1; with no keys set, PGlite and the development sign-in bun run db:seed # demo data -bun run crm:gen # config -> Prisma schema + JSON Schema + contract emit (spools gen) +bun run gen # config -> Prisma schema + JSON Schema + contract emit (spools gen) bun run db:push # sync the database at DATABASE_URL to the contract (prisma db update) bun run db:stats # refill last activity / last contacted / next task due bun run swirls:check # swirls doctor -bun run build && bun run start # production server (server.prod.ts) -bun run demo # built copy on localhost:3100 with the development sign-in; for tunnels (HOST=:: for the whole network), never for production or real data +bun run start # production server (src/server.ts with NODE_ENV=production) ``` Bun loads `.env` from the folder a command runs in, so the app's is `apps/starter/.env`. `DATABASE_URL` in a command's environment wins over it, and an empty one means PGlite (`DATABASE_URL= bun run dev`). Check what it points at before running anything that writes. -## Bun, Vite and the server +## Bun and the server -- Bun is the package manager, script runner, test runner and runtime - (`bunx --bun vite`). TanStack Start requires Vite, so use Vite for the app - rather than `Bun.serve()` HTML imports. Prefer Bun APIs elsewhere (`Bun.file`, - `Bun.$`, `bun:test`, `bun:sqlite`). +- Bun is the package manager, script runner, test runner and runtime. Prefer Bun APIs + (`Bun.file`, `Bun.$`, `bun:test`, `bun:sqlite`). The framework has no build of its own to + run: the starter is `bun src/server.ts`. Vite is only in `apps/docs` and + `examples/tanstack-start`, which are TanStack Start apps. - Run the Prisma CLI as `bun --bun x prisma …` so Bun loads `.env` (Node won't, and there's no dotenv). -- `src/server.ts` is the custom Start server entry: it defines the Spool, then - `serveSpool` (`P/server/entry.ts`) logs the env report and starts the two schedules - (sequence emails, mailbox sync). `server.prod.ts` serves `dist/` with - `Bun.serve`, and on SIGTERM/SIGINT stops taking requests and disposes the Effect - runtime (closing the database pool). +- `src/server.ts` is the starter's server: it defines the Spool, then serves + `headlessServer` (`P/headless.ts`) with `Bun.serve`, which starts the schedules (sequence + emails, mailbox sync, marketing). On SIGTERM/SIGINT it stops taking requests and disposes + the Effect runtime (closing the database pool). An app on TanStack Start wraps its server + entry in `serveSpool` (`P/server/entry.ts`) instead. - One Effect runtime per process (`runtime()` in `P/server/runtime/app.ts`), built on first use and kept on `globalThis`, so a dev reload doesn't open a second pool. -- Production must run with `BUN_RUNTIME_TRANSPILER_CACHE_PATH=0` (set in - `bun run start` and the Dockerfile). Otherwise Bun can reuse modules transpiled - in dev mode and SSR crashes with `context._currentValue`. - - In this repository `@swirls/spools` is its source, so a change shows at once. What npm gets is `packages/spools/dist`: JavaScript and declarations, built by - `packages/spools/scripts/assemble.ts`. Either way TanStack Start compiles its server - functions, because it has `@tanstack/react-start` as a peer dependency. Files named - `*.server.ts` can't be imported by browser code, and `*.client.ts` can't be imported - by the server: that is why the browser halves are in `spool.ui.ts`. -- `bunfig.toml` uses hoisted installs so the app and the framework share one React. -- `packages/spools` is type-checked with the starter's generated route tree, which is how a - view knows its page's data. + `packages/spools/scripts/assemble.ts`. `P/start.ts`, `P/start-client.ts` and `P/react.ts` + are loaded by browsers too, so the server's half of each is said only where a bundler + drops it (`tests/unit/framework-free.test.ts`). +- `bunfig.toml` uses hoisted installs so an app and the framework share one React. ## Prisma 8 notes @@ -279,8 +268,6 @@ Prisma migrates every Postgres, and is one of the database adapters - Generated ids use `@onCreate(uuid())`. Dates are `DateString`, money is `NumericString(14, 2)` (both come back as strings). - Its raw SQL refuses `null` and `Date` parameters; `store/sql.ts` writes them out. -- Server functions can't return `unknown`-typed values (Start checks - serializability): give records concrete types, or JSON-encode. ## Swirls DSL diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 15f4131..8f1cee9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -34,7 +34,7 @@ bun install --frozen-lockfile There is nothing to sign up for. With no keys set, the starter keeps its records in a Postgres inside the server (`apps/starter/.data/pglite`) and signs you in as `dev@example.com`. ```bash -bun run dev # the starter at http://localhost:3000, the website at http://127.0.0.1:8788 +bun run dev # the starter's API at http://localhost:3000/api/v1, the website at http://127.0.0.1:8788 bun run verify # build, type checks, tests, lint, and formatting checks bun run fmt # oxfmt (write) bun run fmt:check # oxfmt --check @@ -72,22 +72,14 @@ bun install bun run verify ``` -To see the starter signed out, as someone else, or with canned assistant replies: +To see the starter signed out, or as someone else: ```bash DEV_AUTH_SIGNED_OUT=1 bun run demo DEV_AUTH_EMAIL=someone@else.test bun run demo # not on the access list -E2E_ASSISTANT=stub bun run --cwd apps/starter dev:e2e # on :3100 ``` -To test the starter's interface in a browser (Chromium, with Playwright), run `bun run test:e2e` from the root. It builds the starter with the stubbed sign-in, starts it on seeded databases of its own under `apps/starter/e2e/.data`, and runs the tests in `apps/starter/e2e/tests`. One server is the starter with record scopes laid over its config (`e2e/scoped.ts`), for the tests of what each branch's people see. It uses ports 4310 to 4315 (4313 is a stand-in OAuth provider for the Integrations page, 4315 a stand-in file store); set `E2E_PORT` to move them. For the tests of many-to-many relations it adds a Tags object to the starter's config there (`apps/starter/e2e/tags.ts`), without changing the starter. -The first run needs the browser: `bunx playwright install chromium`. - -To run the React Doctor audit: - -```bash -bun run doctor -``` +A small front end on the starter's config is in [`examples/tanstack-start`](./examples/tanstack-start): `bun run dev` there serves it on port 3200. ## Find your way around @@ -106,19 +98,19 @@ bun run doctor ## Prepare a change for review -Keep a pull request focused on one problem. Follow the surrounding code conventions and explain any change to public behavior. A change to the tables or to `crm.config.json` needs a word on what people with data in them have to do. +Keep a pull request focused on one problem. Follow the surrounding code conventions and explain any change to public behavior. A change to the tables or to `spool.config.json` needs a word on what people with data in them have to do. Some things we hold to: - **Extend, don't patch.** A change should add or use an extension point, so that nobody has to edit the framework to get what they need. - **Ports, not vendors.** The framework asks for a port and never imports an adapter, a vendor's SDK, or the app. Lint refuses it. An adapter that can't keep a port's promise is a reason to talk before bending the port. - **A new adapter** passes the tests the others do and works without an account in CI. See [writing an adapter](https://spools.codes/docs/adapters#write-your-own). -- **Config first.** If a feature can be expressed in `crm.config.json`, add it to the schema with validation and a clear message, to the generator if it affects storage, and to the [configuration reference](./docs/configuration.md). -- **Rules and access live in the data layer.** A record rule or role access is checked in `packages/spools/src/server/records.ts` for every caller, never only in a page or a server function. Anything new that reads records, or rows hung off them, checks role access and works under the record-scope guard. `asSystem` is what marks the server's own work: nothing else lifts either. -- **A feature set is a module, not a patch.** Something an app could plug in (its objects, code, tables, panels) is written with the public APIs as a [module](./docs/modules.md), as [`examples/modules/approvals`](./examples/modules/approvals) is. The framework never learns a module's nouns. +- **Config first.** If a feature can be expressed in `spool.config.json`, add it to the schema with validation and a clear message, to the generator if it affects storage, and to the [configuration reference](./docs/configuration.md). +- **Rules and access live in the data layer.** A record rule or role access is checked in `packages/spools/src/server/records.ts` for every caller, never only in an operation or an endpoint. Anything new that reads records, or rows hung off them, checks role access and works under the record-scope guard. `asSystem` is what marks the server's own work: nothing else lifts either. +- **A feature set is a module, not a patch.** Something an app could plug in (its objects, code, tables, settings) is written with the public APIs as a [module](./docs/modules.md), as [`examples/modules/approvals`](./examples/modules/approvals) is. The framework never learns a module's nouns. - **No built-in door for outsiders.** An endpoint for people who are not teammates is the app's own, behind `publicRoute`, from the helpers in `@swirls/spools/extensions`. A change there keeps each helper to one job, and says in [Security](./docs/security.md#your-own-door) what it guarantees. -- **Pages draw times with ``**, so the server and the browser draw the same. A test reads the source for it. -- **Generated files are committed.** Run `bun run crm:gen` in `apps/starter` after changing the config or the tables, and `bun run build` after adding a route. CI fails when they are out of date. +- **Spools draws nothing.** No page, component or stylesheet goes in the framework. What a front end needs is an operation's answer, or state with no markup in `@swirls/spools/react` over pure rules in `@swirls/spools/state`. +- **Generated files are committed.** Run `bun run gen` in `apps/starter` after changing the config or the tables. CI fails when they are out of date. Every commit follows [Conventional Commits](https://www.conventionalcommits.org/), and so does the pull request's title. diff --git a/README.md b/README.md index 08f5107..d89d581 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # Spools -**Vibe code your entire CRM on rock-solid engineering.** +**The backend for business software you vibe code.** -Spools is an open source CRM framework. It gives your coding agents the sign-in, data layer, security, search, email and tests, so they only write what is specific to your business. A CRM built with it is called a Spool. +Spools handles sign-in, access rules, data, search, email and files behind an HTTP API with a typed client, so your coding agents only write what is specific to your business. They write the front end you want too, on Next.js, TanStack Start or anything else. When an agent writes something that would skip an access check, lint or the server refuses it. A new Spool starts as a working CRM, and you change it into what your business runs on. Spools is open source, and an app built with it is called a Spool. [Website](https://spools.codes) · [Documentation](https://spools.codes/docs) · [Quickstart](https://spools.codes/docs/quickstart) · [Contributing](./CONTRIBUTING.md) @@ -10,18 +10,19 @@ Built and maintained by the team at [Swirls](https://swirls.ai). ## Why Spools -Your agents write a config, choose the services and add your own code. Spools handles everything underneath: +Your agents write a config, choose the services and add your own code. Spools already does the rest: -- **Access checked on every request.** Pages and endpoints check the session and the access list. Lint refuses one your agent writes without the check. -- **Roles the server enforces.** A role can be denied an object or left to read it, and a branch kept to its own records. The check is in the data layer, for every page, search, export and your own code. +- **Access checked on every request.** Every operation checks the session and the access list. Lint refuses an endpoint your agent writes without the check. +- **Roles the server enforces.** A role can be denied an object or left to read it, and a branch kept to its own records. The check is in the data layer, for every read, search, export and your own code. - **Typed Postgres tables.** Each object is a table in your database, with migrations and row-level security. -- **Rules that hold for every writer.** Unique values, locked and append-only records, and fields set once are each a line of config, kept for the interface, imports, the assistant and your own code alike. A field can also be left to the server to write. +- **Rules that hold for every writer.** Unique values, locked and append-only records, and fields set once are each a line of config, kept for every front end, imports, the assistant and your own code alike. A field can also be left to the server to write. - **Each email sent once.** Sequences keep their place through a restart, and two servers never send the same email. - **Each post sent once.** Social posts go out when a teammate approves them, to LinkedIn, X, Facebook or a network you add, and never twice. -- **Secrets kept on the server.** Tokens are sealed before they are stored, and the build fails if server code built on Effect reaches the browser. -- **Time limits on outside calls.** Failures are typed with [Effect](https://effect.website), and calls are retried where that is safe. -- **Modules.** A feature set (its objects, code, tables and panels) plugs into any Spool, and a clash with yours is refused, never silently won. -- **More than 1,300 tests.** The server tests run on all three database adapters. +- **Secrets kept on the server.** Tokens are sealed before they are stored, and a front end is given nothing but what the API answers. +- **Time limits on outside calls.** Every call to another service has a time limit, and is retried only when a repeat is safe. +- **Any front end.** A Spool draws nothing. It answers an HTTP API, with a typed client that knows every field of your objects, query options for TanStack Query, and React hooks for the state of a list, a record form and a relation picker. +- **Modules.** A feature set (its objects, code, tables and settings) plugs into any Spool, and a clash with yours is refused when the Spool starts. +- **More than 1,300 tests.** The server tests run on every database Spools supports. Most changes are a few lines you can read. The framework updates as a package, so you never merge it. You can [import your records](https://spools.codes/docs/coding-agents#moving-from-another-crm) from HubSpot, Salesforce or a spreadsheet. @@ -32,18 +33,18 @@ Read [building with coding agents](https://spools.codes/docs/coding-agents) and Install [Bun](https://bun.sh) 1.4 or later, then make a Spool: ```bash -bun create @swirls/spools my-crm -cd my-crm +bun create @swirls/spools my-app +cd my-app bun run db:seed bun run dev ``` -Open http://localhost:3000. You need no accounts. Until you choose real services, records go in a Postgres inside the server and you are signed straight in. A production build refuses to start that way. +The API is on http://localhost:3000/api/v1, and `curl localhost:3000/api/v1` lists everything it does. You need no accounts. Until you choose real services, records go in a Postgres inside the server and every request is taken as you. A production server refuses to start that way. [Front ends](https://spools.codes/docs/front-ends) has what to build yours on, and [`examples/tanstack-start`](./examples/tanstack-start) is a small one that works. Or let your coding agent do all of it. Paste this into Claude Code, Cursor or Codex: ```text -Read https://md.spools.codes/prompt.md and follow it to build my CRM with Spools +Read https://md.spools.codes/prompt.md and follow it to build my business software with Spools ``` Once you have a Spool, open the folder in your agent and say what you need: @@ -58,53 +59,66 @@ Once you have a Spool, open the folder in your agent and say what you need: // src/spool.server.ts import { defineSpool } from '@swirls/spools' import { swirls } from '@swirls/spools/agents/swirls' -import { clerk } from '@swirls/spools/auth/clerk' +import { clerk } from '@swirls/spools/auth/clerk/backend' import { postgres } from '@swirls/spools/database/postgres' import { resend } from '@swirls/spools/email/resend' import { drive, s3Blobs } from '@swirls/spools/files/drive' -import { aes } from '@swirls/spools/vault/aes' +import { cipherstash } from '@swirls/spools/vault/cipherstash' -import crm from '../crm.config.json' with { type: 'json' } +import config from '../spool.config.json' with { type: 'json' } import extensions from './app/extensions' export default defineSpool({ - crm, // your business + config, // your business extensions, // your code auth: clerk(), database: postgres(), files: drive({ blobs: s3Blobs() }), email: resend(), - vault: aes(), + vault: cipherstash(), agents: swirls(), }) ``` -Each page and endpoint is a small file in `src/routes`. Delete one to drop a page, or write your own. +And a front end asks it by name, with your objects' fields typed: -| Import | What it is | -| --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | -| `@swirls/spools` | `defineSpool` | -| `@swirls/spools/extensions` | For `src/app/extensions.ts`: hooks, handlers, and the record functions | -| `@swirls/spools/module`, `ui/slots` | What a [module](https://spools.codes/docs/modules) is written with | -| `@swirls/spools/auth/*`, `database/*`, `files/*`, `email/*`, `vault/*`, `agents/*`, `rate-limits/*` | The adapters that ship with it | -| `@swirls/spools/adapter` | What an adapter is written with | -| `@swirls/spools/pages/*`, `api/*`, `ui/*` | Pages, endpoints, and interface parts for your route files | +```ts +import { createClient } from '@swirls/spools/client' + +import type { SpoolObjects } from './spool.types' // generated from spool.config.json + +const spool = createClient({ baseUrl: '/api/v1' }) +const { rows } = await spool.records('deals').list({ q: 'renewal' }) +await spool.records('deals').update(rows[0].id, { stage: 'won' }) +``` + +| Import | What it is | +| --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| `@swirls/spools` | `defineSpool` | +| `@swirls/spools/extensions` | For `src/app/extensions.ts`: hooks, handlers, and the record functions | +| `@swirls/spools/module` | What a [module](https://spools.codes/docs/modules) is written with | +| `@swirls/spools/modules` | The [built-in modules](https://spools.codes/docs/modules#built-in-modules): email sequences, mailbox sync, marketing, contact tracking | +| `@swirls/spools/auth/*`, `database/*`, `files/*`, `email/*`, `vault/*`, `agents/*`, `rate-limits/*` | The adapters that ship with it | +| `@swirls/spools/adapter` | What an adapter is written with | +| `@swirls/spools/headless`, `http`, `operations`, `handlers` | The server, the HTTP API, every operation, and the checks for endpoints of your own | +| `@swirls/spools/client`, `query`, `react`, `state` | For a [front end](https://spools.codes/docs/front-ends): the typed client, query options, hooks | +| `@swirls/spools/start`, `start/client`, `api/*` | A Spool inside a TanStack Start app of your own | ## Parts -| Part | Ships with | Without one | -| ------------ | ----------------------------------------------------------------------------------- | ------------------------------------------- | -| `auth` | Clerk, Better Auth, a development sign-in | Required | -| `database` | Any Postgres through Effect SQL, PGlite in the server, Prisma 8 (release candidate) | Required | -| `files` | Your database with a local disk or any S3 bucket, FlashDrive | The Files pages say files aren't set up | -| `email` | Resend, or your own function | Emails are logged | -| `vault` | CipherStash, AES-256-GCM | No outside tokens are stored | -| `agents` | Swirls | Workflows are skipped, the assistant is off | -| `rateLimits` | Counts in the server's memory, or in your database | Counted in memory, per instance | +| Part | Ships with | Without one | +| ------------ | ----------------------------------------------------------------------------------- | ----------------------------------------------------------- | +| `auth` | Clerk, Better Auth, a development sign-in | Required | +| `database` | Any Postgres through Effect SQL, PGlite in the server, Prisma 8 (release candidate) | Required | +| `files` | Your database with a local disk or any S3 bucket, FlashDrive | File operations say files aren't set up | +| `email` | Resend, or your own function | Emails are logged | +| `vault` | CipherStash, or AES under a key you keep. Production needs its keys | No secrets are stored, so no connected accounts or API keys | +| `agents` | Swirls | Workflows are skipped, the assistant is off | +| `rateLimits` | Counts in the server's memory, or in your database | Counted in memory, per instance | Every database adapter runs the same integration tests. See [choosing adapters and writing your own](https://spools.codes/docs/adapters). -A feature set of your own, or someone else's, plugs in as a [module](https://spools.codes/docs/modules): `modules: [approvals]` in the same file. [`examples/modules/approvals`](./examples/modules/approvals) is a worked one. +Feature sets plug in as [modules](https://spools.codes/docs/modules) in the same file. Four come with the framework (email sequences, mailbox and calendar sync, marketing, contact tracking), and listing them is what makes the starter a CRM. A feature set of your own, or someone else's, goes in the same list: `modules: [sequences, approvals]`. [`examples/modules/approvals`](./examples/modules/approvals) is a worked one. ## Before deploying @@ -114,16 +128,17 @@ Spools is early software (0.x). It works end to end, and minor versions may incl ### Status -| Area | State | -| ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| Config, records, views, search, tasks, notes, reports, CSV, actions, sequences | Unit and integration tested on PGlite, Postgres through Effect SQL, and Postgres through Prisma | -| Modules, record rules, role access, live updates, idempotent requests, rate limits | Unit and integration tested on the same three stores, each on a Spool of its own | -| Interface | Browser tests cover access, records, the board, search, import, tasks and the assistant | -| Swirls workflows, assistant, tool API | `swirls doctor` clean and the tool API tested; not yet run against a live project | -| Better Auth, Resend, FlashDrive, S3, the AES vault | Tested against stand-ins; not yet run against live accounts | -| Marketing: the website check, posts, ad results, and each built-in network | Tested against stand-ins; not yet run against live LinkedIn, X, Meta or Google Ads accounts | -| Clerk, CipherStash, the Swirls adapter | Only the code around the service is tested; not yet run against live accounts | -| Field encryption in the database | Not yet | +| Area | State | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| Config, records, views, search, tasks, notes, reports, CSV, actions, sequences | Unit and integration tested on PGlite, Postgres through Effect SQL, and Postgres through Prisma | +| Modules, record rules, role access, live updates, idempotent requests, rate limits | Unit and integration tested on the same three stores, each on a Spool of its own | +| Swirls workflows, assistant, tool API | `swirls doctor` clean and the tool API tested; not yet run against a live project | +| The HTTP API, the typed client, API keys, the server | Unit and integration tested on the same three stores; a new Spool is made from the packed packages and run | +| Query options, React hooks and their state rules | Unit tested; `examples/tanstack-start` uses them | +| Better Auth, Resend, FlashDrive, S3 | Tested against stand-ins; not yet run against live accounts | +| Marketing: the website check, posts, ad results, and each built-in network | Tested against stand-ins; not yet run against live LinkedIn, X, Meta or Google Ads accounts | +| Clerk, CipherStash, the Swirls adapter | Only the code around the service is tested; not yet run against live accounts | +| Field encryption in the database | Not yet | What's next is in the [roadmap](./ROADMAP.md). @@ -136,16 +151,16 @@ bun install bun run dev ``` -The starter CRM runs at http://localhost:3000 and the website at http://127.0.0.1:8788. `bun run verify` runs the build, types, tests, lint and formatting. CI also runs the tests on Postgres and Prisma, makes a new Spool from the packed packages, and runs `swirls doctor`. +The starter's API runs at http://localhost:3000/api/v1 and the website at http://127.0.0.1:8788. `bun run verify` runs the build, types, tests, lint and formatting. CI also runs the tests on Postgres and Prisma, makes a new Spool from the packed packages, and runs `swirls doctor`. -| Path | What it is | -| ------------------------ | -------------------------------------------------------------------- | -| `packages/spools` | `@swirls/spools`, the framework | -| `packages/create-spools` | `@swirls/create-spools`, which makes a new Spool | -| `apps/starter` | A working Spool: what `create-spools` copies, and where work happens | -| `apps/docs` | Source for [spools.codes](https://spools.codes) | -| `examples` | Adapters and a module written outside the framework | -| `docs` | The documentation | +| Path | What it is | +| ------------------------ | ----------------------------------------------------------------------- | +| `packages/spools` | `@swirls/spools`, the framework | +| `packages/create-spools` | `@swirls/create-spools`, which makes a new Spool | +| `apps/starter` | A working Spool: what `create-spools` copies, and where work happens | +| `apps/docs` | Source for [spools.codes](https://spools.codes) | +| `examples` | Adapters, a module and a small front end, written outside the framework | +| `docs` | The documentation | ## Help and contributions diff --git a/RELEASE.md b/RELEASE.md index ffa2755..7d071b2 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -21,7 +21,7 @@ Spools uses SemVer and Changesets. - Stable releases use the npm `latest` tag. Preview releases use Changesets prerelease mode and the `next` tag. -The version of `crm.config.json` (`"version": 1`) is separate. It changes only when the format +The version of `spool.config.json` (`"version": 1`) is separate. It changes only when the format breaks. A change to the tables is called out in the changeset, because people have to migrate. ## Normal release @@ -81,8 +81,8 @@ preview version. ## Verification and recovery `bun run check:package` builds and packs both packages, looks inside the tarballs, makes a new Spool -from them in a folder of its own, checks its types, builds it, checks that a production server -without keys refuses to start, seeds it, and asks it for pages. It never publishes. +from them in a folder of its own, checks its types, checks that a production server +without keys refuses to start, seeds it, and asks its API for answers. It never publishes. If a release fails before npm accepts it, fix the cause and rerun the workflow. If npm accepted the version but tag or GitHub release creation failed, do not reuse or republish that version; create diff --git a/ROADMAP.md b/ROADMAP.md index 377e82e..1f11fbf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -24,7 +24,7 @@ What's planned, roughly in order. Open an issue to discuss any of it. search and a few casts. - **More email adapters**: SMTP, Postmark, SES. - **Field-level encryption with CipherStash.** Fields can already be marked - `encrypted` in `crm.config.json`; they're stored as plaintext until + `encrypted` in `spool.config.json`; they're stored as plaintext until `@cipherstash/stack-prisma` supports Prisma 8. When it does, the generator will emit encrypted column types and existing configs will work unchanged. Existing plaintext data will need a one-time migration, which we'll document. diff --git a/SECURITY.md b/SECURITY.md index 8f44c76..d78488b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -34,7 +34,7 @@ A Spool runs your own code. Hooks, handlers, pages, adapters, and installed depe Your application is responsible for: -- Choosing who may use the CRM, in `access` in `crm.config.json` and at your sign-in provider +- Choosing who may use the CRM, in `access` in `spool.config.json` and at your sign-in provider - Keeping secrets on the server, and rotating them when someone who had them leaves - Keeping the bucket, disk, or drive behind the Files pages private, and the database reachable only by the server - Configuring the number of proxies in front of the server, request limits, and backups diff --git a/apps/docs/public/prompt.md b/apps/docs/public/prompt.md index 1285152..0792cdd 100644 --- a/apps/docs/public/prompt.md +++ b/apps/docs/public/prompt.md @@ -1,8 +1,11 @@ -# Build a CRM with Spools +# Build business software with Spools -You are a coding agent, and the person you work for wants a CRM of their own. Spools is an open -source CRM framework: it brings the sign-in, data layer, security, search, email and tests, and you -write what is specific to their business. Follow these steps in order. +You are a coding agent, and the person you work for wants software of their own to run their +business on, such as a CRM, a job tracker, a policy book or an order desk. Spools is the open +source backend for it. It already has the sign-in, access rules, data layer, search, email and +tests behind one typed HTTP API, and you write what is specific to their business. It draws +nothing, so the front end is theirs, on any framework. A new Spool starts as a working CRM, which +you change to fit. Follow these steps in order. Everything here happens in one new folder on this machine. It needs no accounts, and nothing is deployed. Do not ask for a password, an API key or a token, and do not read one from another @@ -13,11 +16,12 @@ project. If the person has not told you already, ask these in one message and wait for the answers: - What does the business sell, and to whom? -- What should the CRM track? For example companies, people, deals, policies, projects or orders. +- What should it track? For example companies, people, deals, policies, projects or orders. - What stages does a deal, or whatever they track, move through? - What should happen on its own? For example a task when a deal is won, or an email before a renewal. - What is the business called, and what email domain does the team sign in with? +- Do they want a front end now, and on which framework? The back end works without one. Short answers are enough. Where they have no preference, choose something sensible and say what you chose. @@ -38,11 +42,11 @@ Run this in the folder where the person keeps their projects. Pass `--yes`, or t ask questions you cannot answer from here. ```bash -bun create @swirls/spools my-crm --name "Acme" --domain acme.com --yes +bun create @swirls/spools my-app --name "Acme" --domain acme.com --yes ``` -- `my-crm` is the new folder. It must not exist yet, or it must be empty. -- `--name` is the business, as the CRM shows it. +- `my-app` is the new folder. It must not exist yet, or it must be empty. +- `--name` is the business, as the app names it. - `--domain` lets in everyone with an email address at that domain. Use `--email` for one person. The command installs the packages and writes `.env` with fresh secrets. Leave `.env` alone. @@ -50,7 +54,7 @@ The command installs the packages and writes `.env` with fresh secrets. Leave `. ## 4. Read the guide in the new folder ```bash -cd my-crm +cd my-app ``` Read `AGENTS.md`. It says where each kind of change goes and which files are generated. It is the @@ -58,16 +62,16 @@ guide for this Spool from now on, and it wins over this page where they differ. ## 5. Describe the business -Most of the CRM is `crm.config.json`: objects, fields, pipelines, views, actions, automations and +Most of the app is `spool.config.json`: objects, fields, pipelines, views, actions, automations and email sequences. Change it to fit what you learned in step 1, then regenerate what is made from it: ```bash -bun run crm:gen +bun run gen ``` Reach for the config first. If the config cannot say it, write a hook or a handler in -`src/app/extensions.ts`, and after that a page in `src/routes`. Never edit anything in -`node_modules`, and never query the database directly. +`src/app/extensions.ts`, and after that an endpoint of their own under `routes` in `src/server.ts`. +Never edit anything in `node_modules`, and never query the database directly. The config also keeps records right and says who reaches what. Use these before you write a hook that guards a field: @@ -79,7 +83,7 @@ hook that guards a field: reads. The server enforces it. - [Configuration](https://spools.codes/docs/configuration) lists every key. -- [Extending](https://spools.codes/docs/extending) covers hooks, handlers and pages. +- [Extending](https://spools.codes/docs/extending) covers hooks, handlers and endpoints. - [Modules](https://spools.codes/docs/modules) covers a feature set that plugs into a Spool. - [Build with coding agents](https://spools.codes/docs/coding-agents) shows requests and where each one goes. @@ -104,14 +108,20 @@ bun run dev ``` `bun run dev` keeps running. Start it in the background, or give the person the command. -The CRM is at http://localhost:3000, and they are signed straight in. Records are kept in a Postgres -inside the server, in `.data/pglite`. +The API is at http://localhost:3000/api/v1, and on this machine every request is signed in as the +development user. `GET /api/v1` lists every operation. Records are kept in a Postgres inside the +server, in `.data/pglite`. + +If they asked for a front end, build it as an app of its own that calls the API through the typed +client. [Front ends](https://spools.codes/docs/front-ends) covers the client, the query options, the +state hooks and TanStack Start, and `examples/client.ts` in the new folder is a script that reads +and writes records. ## 8. Report Tell the person: -- where the folder is and how to start the CRM, +- where the folder is, how to start the server and where the API is, - what you put in the config: the objects, the pipelines and the automations, - anything you chose for them, and anything they asked for that you left out, - that `bun run check` passes. diff --git a/apps/docs/src/components/copy-prompt.tsx b/apps/docs/src/components/copy-prompt.tsx index 2f85490..d20d352 100644 --- a/apps/docs/src/components/copy-prompt.tsx +++ b/apps/docs/src/components/copy-prompt.tsx @@ -21,7 +21,7 @@ export function CopyPrompt({ className = '' }: { className?: string }) {