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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ S3_ENDPOINT=http://localhost:${PT_S3_PORT}
# Enabled plugins. Defaults to core,site, which are the only plugins that exist so far.
# core is always required.
PT_PLUGINS=core,site
# The languages in use, chosen from those registered in apps/cms/src/locales.ts: en, fr, pt, ar,
# sw. English is always on. Start-up stops on a code that is not registered. Defaults to en.
# PT_LOCALES=en,fr
# Chooses the verification adapter when more than one enabled plugin provides one. With only
# core enabled, the built-in `native` adapter is used and this can stay unset.
# PT_VERIFICATION=native
Expand Down
45 changes: 45 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

PromiseTracker v3. The system specification in `docs/spec/promisetracker-v3-system-specification.md`
is the source of truth for behaviour. Work is tracked as issues in the "v3: version 1" milestone.
Issue #672 gives the build order and the owner of each issue.

## Layout

Expand Down Expand Up @@ -43,6 +44,50 @@ is the source of truth for behaviour. Work is tracked as issues in the "v3: vers
- Next.js 16 ships its own docs in `apps/site/node_modules/next/dist/docs/`. Read them before
relying on remembered APIs.

## Working on an issue

1. Find the issue. Issue #672 lists every issue in build order, with its owner. Work only on
issues assigned to the person you are working for, and only on ones labelled `status: ready`.
2. Read the issue's "Start here" section. It names the specification sections to read, where the
code goes, what already exists, and any v2 code to reuse. Read v2 code with
`git show v2-final:<path>`. v2 is not in the working tree.
3. Read those specification sections before writing code. If the issue and the specification
disagree, the specification wins. Say so in the pull request.
4. Branch from `main`: `feat/v3-<short-name>`, or `docs/...`, `fix/...`, `chore/...`.
5. Build only what the acceptance criteria ask for. Each criterion needs a test, or a line in the
pull request saying how it was checked.
6. After changing collections or fields: `pnpm generate`, then `pnpm payload migrate:create <name>`,
then `pnpm migrate:check`.
7. Before opening the pull request: `pnpm lint`, `pnpm typecheck` and `pnpm test`. The last needs
`pnpm services` running.
8. The pull request says `Closes #<issue>` and follows the format of #663 and #664: what it does,
decisions made while building, environment and config changes, migrations, how to test.
9. A decision that changes behaviour also goes in the specification's decision register, section
20.1, with the PDFs rebuilt.
10. After the merge, look at the issue's "Unblocks" section. Move each issue listed there to
`status: ready` if nothing else open blocks it.

Where things are:

| What | Where |
| ------------------------------------------------ | ----------------------------- |
| Ports, the plugin helper, start-up checks | `packages/kernel/src` |
| Record types and default adapters | `plugins/core/src` |
| Settings for the default public site | `plugins/site/src` |
| Payload config, migrations, generated types | `apps/cms/src` |
| `/api/v1` handlers | `apps/cms/src/api/v1.ts` |
| Public API response schemas | `packages/contract/src` |
| The typed client the site uses | `packages/sdk/src` |
| Components, props only | `packages/ui/src` |
| Public pages | `apps/site/src/app/(site)` |
| Admin, REST, `/api/v1`, health and plugin routes | `apps/site/src/app/(payload)` |
| Registered languages | `apps/cms/src/locales.ts` |
| Every environment key | `.env.example` |

A new plugin is a package in `plugins/`. It is also added to `firstPartyPlugins` in
`apps/cms/src/kernel.ts`, to `transpilePackages` in `apps/site/next.config.ts`, and to the `COPY`
lines for `package.json` files in `docker/Dockerfile`.

## Style

- Biome formats and lints: two spaces, single quotes, no semicolons, 100 columns.
Expand Down
8 changes: 7 additions & 1 deletion apps/cms/src/kernel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,17 @@ import { createKernel } from '@promisetracker/kernel'
import { corePlugin } from '@promisetracker/plugin-core'
import { sitePlugin } from '@promisetracker/plugin-site'

import { defaultLocale, registeredLocales } from './locales'

/**
* Every first-party plugin, enabled or not. Their record types and fields are
* always in the schema (D29). PT_PLUGINS decides which ones act.
*/
export const firstPartyPlugins = [corePlugin, sitePlugin] as const

/** Built once per process. A configuration problem stops start-up here. */
export const kernel = createKernel({ plugins: firstPartyPlugins })
export const kernel = createKernel({
plugins: firstPartyPlugins,
locales: registeredLocales,
defaultLocale,
})
16 changes: 16 additions & 0 deletions apps/cms/src/locales.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { LocaleSpec } from '@promisetracker/kernel'

/**
* Every language PromiseTracker can run in (section 7.1, D45). The database
* stores this list, so adding one here needs a migration. PT_LOCALES chooses
* which of them a deployment uses, and never changes the schema.
*/
export const registeredLocales = [
{ code: 'en', label: 'English' },
{ code: 'fr', label: 'Français' },
{ code: 'pt', label: 'Português' },
{ code: 'ar', label: 'العربية', rtl: true },
{ code: 'sw', label: 'Kiswahili' },
] as const satisfies readonly LocaleSpec[]

export const defaultLocale = 'en'
1 change: 1 addition & 0 deletions docker/compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ x-app: &app
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-promisetracker}
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-promisetracker}
PT_PLUGINS: ${PT_PLUGINS:-core,site}
PT_LOCALES: ${PT_LOCALES:-}
PT_VERIFICATION: ${PT_VERIFICATION:-}
PT_LLM_MODEL: ${PT_LLM_MODEL:-}
PT_STARTUP_LOCK_TIMEOUT_SECONDS: ${PT_STARTUP_LOCK_TIMEOUT_SECONDS:-}
Expand Down
3 changes: 3 additions & 0 deletions docs/spec/promisetracker-v3-system-specification.md
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,9 @@ so the same file is stored once.
default), and each plugin's credentials. Only super-admins can read it, and every credential is
encrypted. Environment variables choose which plugins run. The database holds what they need.

The kernel reads the settings once and reuses them, so an adapter call costs no database read. A
change takes effect at once in the process that saved it, and within 30 seconds in the others.

### 7.11 Indexes and search

| Record type | Indexes |
Expand Down
Binary file modified docs/spec/promisetracker-v3-system-specification.pdf
Binary file not shown.
26 changes: 19 additions & 7 deletions packages/kernel/src/env.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,39 @@
/** Environment variables, as process.env or a plain object in tests. */
export type Env = Readonly<Record<string, string | undefined>>

/** The three variables that select the set-up (section 4.3). */
/** The four variables that select the set-up (section 4.3). */
export interface KernelEnv {
/** Enabled plugin slugs. `core` and `site` when PT_PLUGINS is unset. */
readonly plugins: readonly string[]
/** The verification adapter to use, when more than one is available. */
readonly verification: string | undefined
/** `provider:model`, for example `google:gemini-2.5-pro`. */
readonly llmModel: string | undefined
/** Locale codes from PT_LOCALES, as written. The kernel checks them (section 7.1). */
readonly locales: readonly string[]
}

export const DEFAULT_PLUGINS = ['core', 'site'] as const

const clean = (value: string | undefined): string | undefined => value?.trim() || undefined

export function readEnabledPlugins(env: Env = process.env): string[] {
const raw = clean(env.PT_PLUGINS)
if (!raw) return [...DEFAULT_PLUGINS]
const plugins = raw
const readList = (raw: string | undefined): string[] | undefined => {
const value = clean(raw)
if (!value) return undefined
const items = value
.split(',')
.map((p) => p.trim())
.map((item) => item.trim())
.filter(Boolean)
return [...new Set(plugins)]
return [...new Set(items)]
}

export function readEnabledPlugins(env: Env = process.env): string[] {
return readList(env.PT_PLUGINS) ?? [...DEFAULT_PLUGINS]
}

/** The locale codes in PT_LOCALES, in lower case. Empty when it is unset. */
export function readLocales(env: Env = process.env): string[] {
return [...new Set((readList(env.PT_LOCALES) ?? []).map((code) => code.toLowerCase()))]
}

/** Reads the set-up once. The kernel keeps the result for the life of the process. */
Expand All @@ -31,5 +42,6 @@ export function readKernelEnv(env: Env = process.env): KernelEnv {
plugins: Object.freeze(readEnabledPlugins(env)),
verification: clean(env.PT_VERIFICATION),
llmModel: clean(env.PT_LLM_MODEL),
locales: Object.freeze(readLocales(env)),
})
}
7 changes: 4 additions & 3 deletions packages/kernel/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
* the system specification).
*/
export type { Env, KernelEnv } from './env'
export { DEFAULT_PLUGINS, readEnabledPlugins, readKernelEnv } from './env'
export { DEFAULT_PLUGINS, readEnabledPlugins, readKernelEnv, readLocales } from './env'
export { KernelError } from './errors'
export type { Kernel, KernelOptions, ResolvedAdapters } from './kernel'
export type { Kernel, KernelOptions, LocaleSpec, ResolvedAdapters } from './kernel'
export { createKernel } from './kernel'
export type { HttpMethod, PluginManifest, PluginRoute, PromiseTrackerPlugin } from './plugin'
export { applyManifest, definePromiseTrackerPlugin, isSuperAdmin, SETTINGS_GLOBAL } from './plugin'
export { applyManifest, definePromiseTrackerPlugin, isSuperAdmin } from './plugin'
export * from './ports'
export { pluginRoute } from './routes'
export { forgetSettings, readSettings, SETTINGS_GLOBAL, SETTINGS_TTL_MS } from './settings'
103 changes: 89 additions & 14 deletions packages/kernel/src/kernel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import type { Env, KernelEnv } from './env'
import { readKernelEnv } from './env'
import { KernelError } from './errors'
import type { PluginManifest, PromiseTrackerPlugin } from './plugin'
import { SETTINGS_GLOBAL } from './plugin'
import type {
AdapterContext,
AnalyticsProvider,
Expand All @@ -20,6 +19,7 @@ import type {
VerificationProvider,
} from './ports'
import { PORTS } from './ports'
import { readSettings } from './settings'

/** The adapters that run, one entry per port (section 4.1). */
export interface ResolvedAdapters {
Expand All @@ -34,8 +34,20 @@ export interface ResolvedAdapters {
captcha: CaptchaProvider
}

/** A language the Payload config registers (section 7.1). */
export interface LocaleSpec {
/** Lower case, such as `en` or `fr`. */
code: string
label: string
/** Written right to left, as Arabic is. */
rtl?: boolean
}

export interface Kernel {
readonly env: KernelEnv
/** The locales in use: the default, then those PT_LOCALES names, in registered order. */
readonly locales: readonly LocaleSpec[]
readonly defaultLocale: string
/** Enabled plugin slugs, in load order. */
readonly enabled: readonly string[]
readonly adapters: ResolvedAdapters
Expand All @@ -60,10 +72,15 @@ export interface KernelOptions {
env?: Env
/** The plugin whose adapters are defaults. */
defaultsFrom?: string
/**
* Every locale the Payload config registers. The database stores this list,
* so PT_LOCALES can only choose from it (D45). Defaults to English alone.
*/
locales?: readonly LocaleSpec[]
/** Always in use, whatever PT_LOCALES says. Defaults to `en`. */
defaultLocale?: string
}

type GlobalSlugParam = Parameters<Payload['findGlobal']>[0]['slug']

type Candidate<P extends PortName> = { plugin: string; adapter: PortAdapters[P] }

const list = (values: readonly string[]): string => values.map((v) => `"${v}"`).join(', ')
Expand Down Expand Up @@ -115,6 +132,36 @@ function checkDependencies(
}
}

for (const m of manifests) {
for (const { collection } of m.takesOver ?? []) {
const owner = owners.get(collection)
if (owner && owner !== m.slug && !(m.dependsOn ?? []).includes(owner)) {
throw new KernelError(
`Plugin "${m.slug}" takes over fields on "${collection}", which plugin "${owner}" owns. ` +
`Add "${owner}" to its dependsOn.`,
)
}
}
}

// Two enabled plugins cannot both write one field.
const takenBy = new Map<string, string>()
for (const m of manifests) {
if (!enabled.has(m.slug)) continue
for (const { collection, fields } of m.takesOver ?? []) {
for (const path of fields) {
const key = `${collection}.${path}`
const other = takenBy.get(key)
if (other) {
throw new KernelError(
`Plugins "${other}" and "${m.slug}" both take over "${key}". Remove one from PT_PLUGINS.`,
)
}
takenBy.set(key, m.slug)
}
}
}

for (const m of manifests) {
for (const dep of m.dependsOn ?? []) {
const target = bySlug.get(dep)
Expand Down Expand Up @@ -210,6 +257,34 @@ function pickLlm(
return { adapter: match.adapter, model: modelName }
}

/** The locales in use: the default and those PT_LOCALES names, in registered order. */
function pickLocales(
registered: readonly LocaleSpec[],
defaultLocale: string,
chosen: readonly string[],
): { locales: readonly LocaleSpec[]; defaultLocale: string } {
const codes = registered.map((l) => l.code)
if (!codes.includes(defaultLocale)) {
throw new KernelError(
`The default locale "${defaultLocale}" is not registered. Registered locales: ${list(codes)}.`,
)
}
const unknown = chosen.filter((code) => !codes.includes(code))
if (unknown.length > 0) {
throw new KernelError(
`PT_LOCALES names locales that are not registered: ${list(unknown)}. ` +
`Registered locales: ${list(codes)}. Registering another needs a code change and a migration.`,
)
}
const inUse = registered.filter((l) => l.code === defaultLocale || chosen.includes(l.code))
// The default comes first, as the site and the admin expect.
const ordered = [
...inUse.filter((l) => l.code === defaultLocale),
...inUse.filter((l) => l.code !== defaultLocale),
]
return { locales: Object.freeze(ordered), defaultLocale }
}

export function createKernel(options: KernelOptions): Kernel {
const env = readKernelEnv(options.env)
const defaultsFrom = options.defaultsFrom ?? 'core'
Expand All @@ -230,6 +305,11 @@ export function createKernel(options: KernelOptions): Kernel {
}
const enabledSet = new Set(env.plugins)
checkDependencies(manifests, enabledSet)
const { locales, defaultLocale } = pickLocales(
options.locales ?? [{ code: 'en', label: 'English' }],
options.defaultLocale ?? 'en',
env.locales,
)

const adapters: ResolvedAdapters = Object.freeze({
verification: pickOne(
Expand Down Expand Up @@ -301,23 +381,16 @@ export function createKernel(options: KernelOptions): Kernel {
const portList = Object.entries(ports())
.map(([port, ids]) => `${port}=${ids.length ? ids.join('+') : 'none'}`)
.join(' ')
return `PromiseTracker plugins=${enabled.join(',')} ${portList}`
const localeList = locales.map((l) => l.code).join(',')
return `PromiseTracker plugins=${enabled.join(',')} locales=${localeList} ${portList}`
}

const settingsFor = async (
payload: Payload,
slug: string,
): Promise<Readonly<Record<string, unknown>>> => {
// The settings global exists only once a plugin declares settings.
const globalSlugs: readonly string[] = payload.config.globals.map((g) => g.slug)
if (!globalSlugs.includes(SETTINGS_GLOBAL)) return {}
// The kernel cannot see the app's generated global names, so it names this
// one through Payload's own parameter type. Settings hold credentials, and
// the kernel reads them as the system.
const settings = await payload.findGlobal({
slug: SETTINGS_GLOBAL as GlobalSlugParam,
overrideAccess: true,
})
// Read once and reused, so an adapter call does not cost a database read.
const settings = await readSettings(payload)
const own: unknown = Reflect.get(settings, slug)
return own && typeof own === 'object' ? (own as Record<string, unknown>) : {}
}
Expand Down Expand Up @@ -357,6 +430,8 @@ export function createKernel(options: KernelOptions): Kernel {

return Object.freeze({
env,
locales,
defaultLocale,
enabled: Object.freeze(enabled),
adapters,
payloadPlugins: Object.freeze(payloadPlugins),
Expand Down
Loading
Loading