diff --git a/.changeset/34770-platform-skill-router.md b/.changeset/34770-platform-skill-router.md new file mode 100644 index 00000000000..69350448939 --- /dev/null +++ b/.changeset/34770-platform-skill-router.md @@ -0,0 +1,20 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): the objectstack-platform entry file becomes a router + +Clause-②: no +Metadata-protocol: none + +`skills/objectstack-platform/SKILL.md` goes from 24.7 KB to 9.0 KB (421 lines to 105). It now holds three things: four first checks (the installed `@objectstack/spec` version, what the project already has, the contract, `os validate`), the traps that pass `os validate` and then fail at run time, and a table that says which file to open for the task at hand. No rule's teaching changes. Text moved, and this entry says where it went. The skill's files are 2.1 KB smaller together (107.5 KB to 105.5 KB). + +**What the entry keeps.** Five traps: no driver in `plugins:`, an installed package is customized from its paired `.custom` package, who owns the HTTP server (`createHonoApp` or `HonoServerPlugin`), `manifest.engines.protocol`, and `manifest.namespace`. Then the full list of `defineStack()` top-level keys with the rule that an undeclared key is refused, the `requires:` provider table with the three rules that bite most often, and `Seed Data` (the three import modes; a seed cannot create a person, `demoStaff` does). + +**What left, and where it is now.** + +- `references/bootstrap.md` now also holds `Strict Validation` (`#strict-validation`), the manifest notes the entry's two traps do not repeat (`#manifest`), `Project Structure Conventions`, what the `blank` template scaffolds (under `#scaffolding-command`), `Runtime Boot Sequence` (`#runtime-boot-sequence`), the `requires:` tokens that have no provider row and the remaining rules (`#requires-in-detail`), `onEnable`, `Customizing an installed package` in full (`#customizing-an-installed-package`), and `demoStaff` with its example (`#demo-accounts--demostaff-vs-devlogins`). +- `references/operations.md` now also holds `Driver Selection Guide` (`#driver-selection-guide`), when to construct `DriverPlugin` yourself (`#wiring-a-driver-yourself`), `HTTP Layer (Hono)` (`#http-layer-hono`), and the note that `os compile` writes `dist/objectstack.json`. +- Anchors that no longer exist in `SKILL.md`: `#definestack--the-core-configuration` (now `#definestack-keys`), `#full-configuration-reference`, `#strict-validation`, `#compile-artifact-and-runtime-metadata-boundary`, `#manifest-reference`, `#the-app--platform-boundary`, `#the-template`, `#project-structure-conventions`, `#naming-conventions`, `#driver-selection-guide`, `#wiring-a-driver--you-usually-do-not`, `#http-layer-hono`, `#usage-pattern-hono`, `#architecture`, `#runtime-boot-sequence`, `#onenable--where-an-app-binds-runtime-code`, `#demo-accounts--demostaff-vs-devlogins`, `#references`. `#requires--which-service-plugins-boot` and `#seed-data` still do. + +**Not carried over, because another file already says it.** The `App / Platform Boundary` section (objectstack-project owns that decision; `references/bootstrap.md#app-or-platform` keeps the two sentences it does not have), the naming-convention table (objectstack-data's naming rules), the annotated manifest example (every key is in `kernel/manifest.zod.ts`, which the entry's third check points at; the barrel example in `references/bootstrap.md` now shows `engines`), the Hono usage snippet, and the closing list of the other files (the routing table replaces it). In `references/plugin-development.md`, the `Plugin` interface block and the hook example are now one pointer each to `rules/plugin-lifecycle.md` and `references/plugin-hooks.md`, which carry the same text. diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 5f9bb5b3cda..ee78bc56557 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -1117,7 +1117,38 @@ export const CEILINGS = new Map([ // row adds 20 bytes, so the LANDED priced text is 24632 bytes -> 6158 // tokens: the ceiling moves 6153 -> 6158 (+5). Pinned AT the measurement. // ceil(($(wc -c < skills/objectstack-platform/SKILL.md) - 27) / 4) == ceil(24632 / 4) - ['skills/objectstack-platform/SKILL.md', 6158], + // 6158 -> 2241 (#34770, the entry file becomes a router; authority as the + // `skills/objectstack-data/SKILL.md` row): LOWERED. The entry keeps four first checks, five + // traps that pass `os validate` and fail at run time (a driver in `plugins:`, customizing an + // installed package from its pair, who owns the HTTP server, `manifest.engines.protocol`, + // `manifest.namespace`), the routing table, and the three sections a gate binds to this file: + // the `defineStack()` key enumeration (`check-skill-top-level-keys`), the `requires:` provider + // table and `## Seed Data` (both Leg 2 of `check-skill-identifier-liveness`), each cut to the + // enumeration and what fails silently. What left, and its home: Strict Validation, the + // manifest notes, Project Structure Conventions, the template paragraph, Runtime Boot + // Sequence, the `requires:` detail, `onEnable`, Customizing an installed package and Demo + // accounts -> `references/bootstrap.md`; Driver Selection Guide, HTTP Layer (Hono) and the + // compile / alias paragraph -> `references/operations.md`. Gone, each restating a file the + // entry now names: the App / Platform Boundary section (objectstack-project), the naming + // table (objectstack-data), the annotated manifest example (`manifest.zod.ts`), the Hono + // usage block, the References list. 24659 bytes (24632 priced) -> 8991 (8964 priced) -> 2241 + // tokens; the ceiling follows the file down to the measurement, which also pins the 9 KB + // budget from here on. + // ceil(($(wc -c < skills/objectstack-platform/SKILL.md) - 27) / 4) == ceil(8964 / 4) + // 2241 -> 2250 (#34770, the parity round): trap 1 names again the package the CLI resolves + // for a SQL database URL (`@objectstack/driver-sql`), the literal the entry's driver table + // carried before the split; without it a deployment plan described the driver and did not + // name it. Nothing else in the entry is cut to pay for it, on the owning seat's choice: the + // file is 8991 -> 9027 bytes (8964 -> 9000 priced), +36, 27 bytes over the 9 KB target the + // row above pinned, -> 2250 tokens, pinned AT the measurement. The row still falls 3908 from + // the 6158 before this change, so no raise path is spent. + // ceil(($(wc -c < skills/objectstack-platform/SKILL.md) - 27) / 4) == ceil(9000 / 4) + // 2250 stays (#34770, the review round): the AI-door rule names the gated call again (an + // action declaring `ai.requiresConfirmation: true`) and `pinyin-search` its `zh-*` locale + // condition, both paid inside the entry: 9027 -> 9025 bytes (9000 -> 8998 priced), 25 over + // the 9 KB target, the same 2250 tokens, still AT the measurement. + // ceil(($(wc -c < skills/objectstack-platform/SKILL.md) - 27) / 4) == ceil(8998 / 4) + ['skills/objectstack-platform/SKILL.md', 2250], // `skills/objectstack-pm-dispatch/SKILL.md` (9708) and its // `rules/dev-template.md` (1838) left this table on 2026-09-10 with the files: // the maintainer deleted the published PM skill whole (verbatim: @@ -2403,7 +2434,25 @@ export const CEILINGS = new Map([ ['skills/objectstack-data/references/seeds.md', 1895], // -3 to the measurement (was 1898) // 1351 -> 1343: the body-pin values left the count (#31115, ruling B; see // BODY_PIN_REPIN); the file's count fell by the same 8, headroom unchanged. - ['skills/objectstack-platform/references/bootstrap.md', 1340], // -3 to the measurement (was 1343) + // 1340 -> 4389 (#34770): RECEIVES from SKILL.md, no new teaching: `### Strict Validation`, + // `### Manifest`, `### Project Structure Conventions`, the template paragraph under + // Scaffolding Command, `## Runtime Boot Sequence`, `### requires: in detail`, `### onEnable`, + // `## Customizing an installed package`, `## Demo accounts` and `## App or platform`. PAID + // DOWN FIRST: the manifest, `requires:` and demo-account sections arrive as the complement of + // what the entry still states, and the template paragraph without its three counts. The file + // is 5425 -> 17621 bytes (+12196; 5360 -> 17556 priced, the five body pins excluded) -> 4389 + // tokens, zero headroom before, ceiling +3049, pinned AT the measurement. + // Authority: the decision record that orders the entry file down to router size (as the + // `skills/objectstack-data/SKILL.md` row) and the maintainer's ruling of 2026-11-24 (ruling + // record 7128031203, fork 4 = A), which names "later moves of the same kind": a ceiling + // raised because text MOVED between files is accepted when each raised row equals the + // measured bytes moved in, with zero headroom, and the sum of ceilings does not rise. Both + // hold: the four objectstack-platform rows this change moves are each pinned AT their + // measurement and sum to 13498, under the 14014 before it (-3908 entry, +3049 here, +630 + // `references/operations.md`, -287 `references/plugin-development.md`); the sum of all + // ceilings goes 200510 -> 199994. + // ceil(($(wc -c < skills/objectstack-platform/references/bootstrap.md) - 65) / 4) == ceil(17556 / 4) + ['skills/objectstack-platform/references/bootstrap.md', 4389], // 3108 -> 3287: `os deploy`, the managed-package dev loop — when to deploy // rather than publish a release, its entry points, how it picks the // environment, its flags, and how to read its exit 1 (refusal before any @@ -2460,8 +2509,21 @@ export const CEILINGS = new Map([ // pinned at the measurement. Same maintainer ruling, verbatim and // untranslated: 「A:先削重复,余额按实测提高」 (ruling record 6513306068 on // #27847). - ['skills/objectstack-platform/references/operations.md', 3389], // -5 to the measurement (was 3394) - ['skills/objectstack-platform/references/plugin-development.md', 3127], // -10 to the measurement (was 3137) + // 3389 -> 4019 (#34770): RECEIVES from SKILL.md, no new teaching: `## Driver Selection + // Guide` (the table whole; of the wiring section only what the entry's trap no longer says), + // `## HTTP Layer (Hono)` (the two-package table whole, the remainder in three sentences, the + // usage block cut) and the compile / alias paragraph above Verify your work. The file is + // 13556 -> 16075 bytes (+2519) -> 4019 tokens, zero headroom before, ceiling +630, pinned AT + // the measurement. Authority and the sum as the `references/bootstrap.md` row. + // ceil($(wc -c < skills/objectstack-platform/references/operations.md) / 4) == ceil(16075 / 4) + ['skills/objectstack-platform/references/operations.md', 4019], + // 3127 -> 2840 (#34770): LOWERED, the deletion that pays part of the two rows above. Two + // blocks restated a sibling file and are now one pointer each: the `Plugin` interface + // (`rules/plugin-lifecycle.md` § Plugin Interface carries the same block) and the hook + // example with its event list (`references/plugin-hooks.md`); the `data:*` warning keeps the + // silent failure and links the rest. 12505 -> 11360 bytes (-1145) -> 2840 tokens. + // ceil($(wc -c < skills/objectstack-platform/references/plugin-development.md) / 4) == ceil(11360 / 4) + ['skills/objectstack-platform/references/plugin-development.md', 2840], ['skills/objectstack-upgrade/references/examples-upgrade.md', 1193], // -4 to the measurement (was 1197) // NEW FILE, pinned AT the measurement: the context pack (`ai_context`, ADR-0160) // is a metadata kind no published skill taught beyond its key name. Card #37177 diff --git a/skills/objectstack-platform/SKILL.md b/skills/objectstack-platform/SKILL.md index e11ab25d700..b118a5db648 100644 --- a/skills/objectstack-platform/SKILL.md +++ b/skills/objectstack-platform/SKILL.md @@ -24,11 +24,22 @@ metadata: # Platform — ObjectStack Bootstrap & Plugin System -## `defineStack()` — The Core Configuration +## First checks -→ See [references/bootstrap.md](./references/bootstrap.md) § Minimal Example. +1. **Version.** Where the installed `@objectstack/spec` version differs from this skill's `compatibility` line, the installed contract is right. +2. **Read what exists.** `objectstack.config.ts` and the `src/*/index.ts` barrels it imports. +3. **Read the contract.** [references/_index.md](./references/_index.md) points at each Zod source in `node_modules/@objectstack/spec/src/`. `Read` it for exact keys, never from memory. +4. **Verify before reporting done.** `os validate` must pass ([Verify your work](./references/operations.md#verify-your-work)). Most traps below pass it. -### Full Configuration Reference +## Traps + +1. **No driver in `plugins:`.** `os dev` / `os serve` / `os start` resolve the driver from the database URL (`@objectstack/driver-sql` for SQL) and register `DriverPlugin` themselves. Construct one only when you own the runtime ([Driver Selection Guide](./references/operations.md#driver-selection-guide)). +2. **An installed package is customized from its pair, never edited.** In `hotcrm`'s paired writable `hotcrm.custom`, a same-named item with `overrides: { package: 'hotcrm', basedOn: '3.2.0' }` replaces the base's document whole (a view, flow, action, page, dataset, …); `DELETE …?package=hotcrm.custom` serves the base's again. Only the pair declares: a dependent's same-named item is refused, and its one fix is a new name. A permission set, position or capability is never overridden: copy it under a new name ("new similar"). An action override never widens who runs it: dropping a `requiredPermissions` entry is refused `declared_action_widens_access` ([the rest](./references/bootstrap.md#customizing-an-installed-package)). +3. **You own the server: `createHonoApp({ kernel })` from `@objectstack/hono`** (`prefix` defaults to `/api`). `HonoServerPlugin` is for when ObjectStack owns the socket; there are no `@objectstack/adapter-*` packages. `prefix` does not move auth: `/auth/*` follows the auth service's `basePath`, and a `prefix` that `basePath` is not inside refuses at boot ([HTTP Layer](./references/operations.md#http-layer-hono)). +4. **`manifest.engines.protocol`** (`engines: { protocol: '^19' }`) is checked before the runtime loads anything, and an out-of-range app is refused: change it when you move to a new protocol major, never to silence a mismatch. +5. **`manifest.namespace` is enforced once set**: with `namespace: 'crm'` every `object.name` must start with `crm_` or `defineStack` errors. Object and doc names, capabilities (`crm.export_data`) and positions carry it; every other name stays short (`send_email`). The object `name` is the table name: never set `tableName` or the retired object-level `namespace` field (refused at load), and never add a `sys_metadata` object ([Manifest](./references/bootstrap.md#manifest)). + +## `defineStack()` keys `defineStack()` accepts an `ObjectStackDefinitionInput` whose top-level keys are `manifest`, `packages`, `objects`, `objectExtensions`, `picklists`, @@ -46,376 +57,49 @@ an approval is a flow with Approval nodes, and record state machines are a `state_machine` validation rule on each object. A phantom key (`roles:`, `policies:`) is no silent no-op: the top level refuses it and the stack fails to load. +Each `objects[]` entry and field refuses an undeclared key too (`TS2353`). A surface not +closed yet (`connectors` is one) only warns that the key's +`value is dropped at load`. -`queues` declares ownership queues (`defineQueue`, `@objectstack/spec/security`; -objectstack-data): named sets of people a new record of an `ownership: 'user'` -object sits in until a member claims it. `assignmentRules` (`defineAssignmentRule`, -`@objectstack/spec/automation`; objectstack-automation) routes each inserted -ownerless row into a queue — parked, `round_robin` or `least_loaded` — or to one -user. Both need the ownership-queue service `@objectstack/plugin-sharing` registers: -a stack declaring either without it is refused at boot. - -Undeclared keys are handled per surface, in two postures: - -- **Refused** — `defineStack()`'s top level, each `objects[]` entry - (`ObjectSchema`), and each field (`FieldSchema`). The parse throws, naming - the surface and the offending key. TypeScript rejects the literal earlier - still, with `TS2353: Object literal may only specify known properties`. -- **Warned, then dropped** — the authoring surfaces whose shapes have not - been closed yet (`connectors` is one). `defineStack()` warns before the parse: - `defineStack: connectors.stripe.bogusKey: 'bogusKey' is not a declared connector key, so its value is dropped at load.` - Treat these as errors-in-waiting: a key that only warns today is expected - to be refused later. - -→ See [references/bootstrap.md](./references/bootstrap.md) § Map Format (Key → Name) · § Barrel Import Pattern. - -### Strict Validation - -`defineStack()` validates by default (`strict: true`): - -1. **Zod schemas** — field names, types, enums -2. **Cross-references** — views/actions/flows reference defined objects -3. **Seed data** — dataset objects exist in the definition - -Disable it with `defineStack(config, { strict: false })` (objects another plugin provides). - -### Compile Artifact and Runtime Metadata Boundary - -ObjectStack runtime metadata must come from source files during local development or -from a compiled artifact. Do not configure an environment runtime to read or write -metadata through its business database. - -```bash -# the CLI ships an `os` binary; `objectstack` is an alias for it -objectstack compile -# -> dist/objectstack.json - -OS_ARTIFACT_PATH=./dist/objectstack.json objectstack dev -``` - ---- - -## Manifest Reference - -Every stack needs a `manifest`: - - -```typescript -import { defineStack } from '@objectstack/spec'; -export default defineStack({ manifest: { - id: 'com.example.crm', // Reverse domain unique ID - version: '1.0.0', // Semver - type: 'app', // app | plugin | driver | module | ... - name: 'Acme CRM', // Human-readable display name - description: 'CRM system', // Optional - engines: { protocol: '^19' }, -} }); -``` - -**`manifest.engines.protocol`:** the metadata-protocol major the app is authored -against (stamped by `create-objectstack`). The runtime -checks it **before it loads anything** and refuses an out-of-range app at the -boundary with the exact migration command. Change it when you deliberately move -to a new protocol major — never to silence a mismatch. - -**Object naming:** The object `name` is the canonical identifier and equals the physical table name. The object-level `namespace` *field* is retired (ADR-0129 D3) and refused at load. Never set `tableName`, and never add a `sys_metadata` object to a runtime manifest. - -**`manifest.namespace` (ADR-0048):** Optional, but **enforced once set**. When a package declares `manifest.namespace: 'crm'`, every `object.name` must start with `crm_` or `defineStack` errors (`validateNamespacePrefix` in `@objectstack/spec`); the legacy `__` double-underscore form is rejected, and `sys_`-prefixed names are platform-reserved and exempt. The namespace is also a package-ownership key — installing two packages that both claim `crm` fails with `NamespaceConflictError` (downgrade to a warning with `OS_METADATA_COLLISION=warn`). Never `actions`, `connectors`, `global`, `hooks`, `oauth`, `runs`, `trigger` (route literals; `os validate` and build refuse). - -**Which names carry the namespace (ADR-0150):** object and doc names, capabilities (`crm.export_data`) and positions (one slot per environment). Every other name stays short (`send_email`): flows, actions, hooks, apps, pages, dashboards, reports, datasets, permission sets, tools, skills, agents, context packs are identified by package and name. A prefixed name stays valid; no name starts with `_`, which the router reserves. `os lint`'s `naming/namespace-prefix` warns on a bare capability or position name, and when one package declares an app, page, dashboard, flow, report or dataset name twice, or an action name twice on one object. - -**Customizing an installed package (ADR-0146):** Customize an installed base `hotcrm` in its paired writable `hotcrm.custom`, which depends on it: a same-named item there with `overrides: { package: 'hotcrm', basedOn: '3.2.0' }` (its `manifest.id`/`manifest.version`) replaces the base's document whole. Reads honour it only from the pair (the row's `package_id`), for a view, dashboard, report, email_template, translation, flow, action, page, app, dataset, doc, book or mapping, never judging `basedOn`. An email template is one item per (name, locale): an override names a locale the base ships; one it does not ship is added without `overrides`. Then no `?package`, `?package=hotcrm`, the layered read and both lists serve it, and removing the pair's item (`DELETE …?package=hotcrm.custom`) serves the base's again; the env-wide list holds one item per name one code package ships (a dependent's stays under its own `?package=`); a pre-D11 unbound Setup row wins over the base's until `os migrate packageless-overlays` moves it, and once movable as a declared override, its package-less save, publish, reset and rollback are refused (D11); an email-template row at a locale the base does not ship moves as the pair's own member and keeps that write. The base's address serves the pair's added locale too (both lists, the layered read with `code` null and `effective` the pair's, the execution list, a send in that locale); one a dependent adds under the base's name is served only under its own `?package=`. An undeclared pair row or a dependent's row at a base-shipped locale is an orphan in the layered read's `overlay`, `effective` = the base's. An override may narrow a public form's anonymous intake, never re-open one any honoured body withdrew. `GET /packages/hotcrm.custom/export` carries it with `overrides`. - -The pair comes from `POST /api/v1/packages/hotcrm/ensure-customization`: `namespace` = the base's + `_custom`, `dependencies: { hotcrm: '^' }`; `GET /packages/hotcrm/customizations` lists its overrides, extensions, switched-off items and `arrangements` (`{ object, key }` per `fieldGroups`, `relatedLists` or `actionLayout` its object extension writes; no content, no diff), and uninstalling the base is refused (`409`) while the pair exists. Only the pair declares: the save, publish and install doors, `os validate` and `os build` refuse `overrides` from any other package, and a dependent's item under a base item's name — its one fix is a new name. A permission set, position or capability is never overridden: copy it under a new name ("new similar", landing in the pair). An object is extended (`__c` fields, **objectstack-data**); a flow is overridden or copied (**objectstack-automation**). An action override keeps the base's `objectName` (keyed `OBJECT:NAME`; another object is refused `declared_package_ships_no_such_item`) and replaces its behaviour (`type`, `body`, `label`, `visible`, …) whole, for whoever could already run the base: dropping a `requiredPermissions` entry, turning `ai.exposed` on or `ai.requiresConfirmation` off is refused `declared_action_widens_access`, both `403 NOT_OVERRIDABLE`. - -That read's `contributions` lists what other packages add to the base, one entry per item with its `packageId`: a `field` or `flow` names the base's `object` it is on, a `nav` item the base's `app`, its `group` if any, and its id as `name`; `counts.contributions` counts items, not packages. - ---- - -## The App / Platform Boundary - -An ObjectStack app is a **simplified implementation of business features**: -author metadata under the platform's spec and check it -with the `os` commands ([Verify your work](./references/operations.md#verify-your-work)). - -- **Business features belong in the app; capability belongs in the platform.** - A missing default, a wrong diagnostic, a shape the spec refuses — the fix is - upstream. -- **Could this be written by something that has only the metadata, and no - knowledge of this company?** *No* — it encodes this company's own judgement (a - discount ceiling, who a case is assigned to, how won/lost is booked) ⇒ the - app. *Yes* — it only asks whether the metadata is self-consistent (reference - integrity, translation coverage, view rosters, sharing-rule coverage, CRUD - round-trips, RLS probes per declared position) ⇒ the platform. -- **A platform defect means waiting for the platform fix.** No defensive coding, - no shape tolerance, no hand-written predicate re-implementing a platform rule, - and never "land the half we can" — that spends the contract-first option and - leaves a decision half-executed. Record the block against the platform issue - so it is machine-visible; before resuming, confirm the version you **pin** - carries the fix (merged upstream ≠ present on your pin) and re-run the - defect's own reproduction. - ---- - -## The Template - -`blank` is the only template `create-objectstack` offers: - -- Bundled — no network fetch -- One example object; `requires: ['automation', 'triggers']` plus the three - generic connector executors in `plugins:`; and the eight generator barrels - (`objects`, `views`, `actions`, `flows`, `dashboards`, `apps`, `skills`, `picklists`), - each `src/*/index.ts` handed to the stack key of its name through - `exportsOf` — the scaffolded `AGENTS.md` says how to add to them. - -The five retired remote templates (`todo`, `compliance`, `content`, -`contracts`, `procurement`) are refused by name. - -→ See [references/bootstrap.md](./references/bootstrap.md) § Scaffolding Command. - ---- - -## Project Structure Conventions - -`objectstack.config.ts` at the root is THE entry point (`defineStack()`), beside -`package.json` and `tsconfig.json`. Metadata lives under `src//` — -`objects/`, then the optional `views/`, `apps/`, -`flows/`, `actions/`, `dashboards/`, `reports/`, `datasets/`, `i18n/` and -`handlers/` (runtime hook handlers) — each with a barrel `index.ts` -(`export * from './task.object'`). - -### Naming Conventions - -| Concept | Convention | Example | -|:--------|:-----------|:--------| -| File names | `{name}.{type}.ts` | `task.object.ts`, `main.app.ts` | -| Machine names | `snake_case` | `project_task`, `first_name` | -| Config keys | `camelCase` | `maxLength`, `defaultValue` | - ---- - -## Driver Selection Guide - -Memory and MongoDB may loudly refuse a query capability SQL serves. - -| Driver | Package | Best For | Notes | -|:-------|:--------|:---------|:------| -| **Memory** | `@objectstack/driver-memory` | Dev, testing, prototyping | `InMemoryDriver` — data lost on restart | -| **SQL** | `@objectstack/driver-sql` | Production (PostgreSQL, MySQL, SQLite) | `SqlDriver` (`pg` / `mysql` / `better-sqlite3` clients) | -| **MongoDB** | `@objectstack/driver-mongodb` | Production (document store) | `MongoDBDriver` | -| **SQLite WASM** | `@objectstack/driver-sqlite-wasm` | Browser / WebContainer | `SqliteWasmDriver` — in-process, no server | -| **Turso** | `@objectstack/driver-turso` | Edge, serverless, multi-tenant | **Cloud / EE only**. The open-core CLI recognizes `libsql://` URLs but **fails loudly** (`UnsupportedDriverError`) | - -### Wiring a driver — you usually do not - -Under `os dev` / `os serve` / `os start` the CLI **resolves the driver itself** -from the database URL and registers `DriverPlugin` for you. Do **not** put a -driver in your config's `plugins:` array: the -`plugins:` key is for plugins the CLI cannot infer (connector executors, your -own plugins). - -Construct `DriverPlugin` yourself only when **you** own the runtime — embedding -via `Runtime` / `ObjectKernel`, or a test that boots a kernel directly: -`new DriverPlugin(new SqlDriver({ client: 'pg', connection: process.env.DATABASE_URL }))` -(`@objectstack/runtime` / `@objectstack/driver-sql`; a full boot: -[Programmatic Bootstrap](./references/bootstrap.md#programmatic-bootstrap-without-cli)). - ---- - -## HTTP Layer (Hono) - -Two packages exist: - -| Package | Export | Use When | -|:--------|:-------|:---------| -| `@objectstack/hono` | `createHonoApp({ kernel, prefix })` | You own the server: embed ObjectStack routes in your own Hono app / deploy target. | -| `@objectstack/plugin-hono-server` | `HonoServerPlugin` | ObjectStack owns the server: a kernel plugin that hosts the Hono app and opens the listening socket. | - -There are **no** `@objectstack/adapter-*` packages. To integrate another -framework, mount the Hono app (a web-standard `fetch` handler) or call the -dispatcher yourself. - -### Usage Pattern (Hono) - -```typescript -import { createHonoApp } from '@objectstack/hono'; - -// prefix defaults to '/api'. -export default createHonoApp({ kernel }); -``` - -⚠️ **`prefix` does not move auth.** The `/auth/*` mount follows the auth -service's `basePath` (`AuthPlugin` default `/api/v1/auth`), not `prefix`. A `prefix` -that `basePath` is not inside **refuses at boot**, naming both values. - -### Architecture - -`createHonoApp` creates an `HttpDispatcher`, mounts explicit -routes for auth and discovery, and delegates everything else to it. - ---- - -## Runtime Boot Sequence - -``` -objectstack.config.ts - └── defineStack({ manifest, objects, views, ... }) - │ - ▼ -CLI: `os serve` / `os dev` - 1. Load .env files (NODE_ENV-based) - 2. Dynamic import of config file - 3. Create Runtime + ObjectKernel - 4. Auto-detect and register plugins (in this order): - ├── ObjectQLPlugin (if objects defined) - ├── DriverPlugin (memory in dev, SQL in prod) - ├── AppPlugin (loads the defineStack bundle) - ├── I18nServicePlugin (if translations/i18n defined) - ├── HonoServerPlugin (registered BEFORE AuthPlugin — the server must - │ exist for plugins that mount routes during init/start) - ├── AuthPlugin - ├── Split platform-app plugins (ADR-0048, optional/best-effort): - │ @objectstack/setup → createSetupAppPlugin (first-run wizard) - │ @objectstack/account → createAccountAppPlugin - │ (@objectstack/studio is intentionally NOT default-loaded — the - │ Console, mounted at /_console/ by `--ui`, ships its own Studio - │ surface at /_console/studio/…) - ├── RESTPlugin (auto-generated API) - ├── DispatcherPlugin - └── AIServicePlugin (cloud / EE only — reverse-mounted by a cloud host) - 5. Runtime.start() → init + start all plugins - 6. Server listens on the resolved port -``` - -**Port resolution** and conflict behaviour: [Ports & networking](./references/operations.md#ports--networking). +`queues` (`defineQueue`, `@objectstack/spec/security`; objectstack-data) and +`assignmentRules` (`defineAssignmentRule`, `@objectstack/spec/automation`; +objectstack-automation) need the ownership-queue service +`@objectstack/plugin-sharing` registers: a stack declaring either without it is +refused at boot. ### `requires:` — which service plugins boot -Step 4's list is the fixed core. Tokens marked ° are always-on: every boot -mounts them, listed or not, and `--preset minimal` drops them; `email`, `approvals` or `auth` keeps `job` and `queue`. Every -other service plugin is opt-in (`requires: [...]` on the stack root turns it on) but the host defaults, mounted under every preset: `mcp` unless `OS_MCP_SERVER_ENABLED=false`, and `pinyin-search` when `i18n` names a `zh-*` locale (`OS_SEARCH_PINYIN_ENABLED` overrides). The CLI expands each -token through the `CAPABILITY_PROVIDERS` registry in -`@objectstack/core`: +Tokens marked ° are always-on: every boot mounts them, and only `--preset minimal` drops them. Every other service plugin is opt-in (`requires: [...]`), except the host defaults `mcp` and, for a `zh-*` locale in `i18n`, `pinyin-search`. Providers (`CAPABILITY_PROVIDERS`): | Token | Provider package | |:--|:--| | `automation` | `@objectstack/service-automation` — flows, and any declarative `connectors:` entry | -| `analytics`° `cache`° `storage`° `queue`° `job`° `messaging`° `realtime` `settings`° `sms`° `push` `record-context` `knowledge` | `@objectstack/service-` + the token ([the `push` block](./references/operations.md#mobile-push)); `record-context` serves `get_record_context`, **objectstack-ai** [context packs](../objectstack-ai/references/context-packs.md) | +| `analytics`° `cache`° `storage`° `queue`° `job`° `messaging`° `realtime` `settings`° `sms`° `push` `record-context` `knowledge` | `@objectstack/service-` + the token ([the `push` block](./references/operations.md#mobile-push)) | | `mailbox` | `@objectstack/service-mailbox` — inbound mail | | `marketplace` `package-registry`° | `@objectstack/service-package` | -| `audit` `email`° `sharing`° `approvals` `webhooks` | `@objectstack/plugin-` + the token | -| `pinyin-search` | `@objectstack/plugin-pinyin-search` | +| `audit` `email`° `sharing`° `approvals` `webhooks` `pinyin-search` | `@objectstack/plugin-` + the token | | `mcp` | `@objectstack/mcp` | | `triggers` | `@objectstack/trigger-record-change`, plus `trigger-schedule` and `trigger-api` | -The tokens in `PLATFORM_CAPABILITY_TOKENS` not in that map do not resolve -through it: - -- **Tier-gated** — `ai`, `ai-studio`, `i18n`, `ui`, `auth`: dedicated blocks - in `serve.ts` `run()` open their tier instead - (`ai`/`ai-studio` through the intent-driven AI block). -- **Enterprise / cloud** — `hierarchy-security` ships in - `@objectstack/security-enterprise`, loaded through `plugins[]`; `ai-seat`, - `governance`, `audit-compliance` and `access-policy-console` are resolved - only by cloud's objectos-runtime. +- **Declaring is a demand.** A table token or `ai`/`ai-studio` YOU declared whose provider package is absent is a hard boot error; `hierarchy-security` only warns, and its scopes fall back to owner-only. +- **Under `--preset minimal`, pair `triggers` with `job`:** `triggers` alone arms record-change triggers; schedule and time-relative ones run on the job service, so scheduled flows stay silent. +- **AI-door confirmation is a service you register**: an `IActionConfirmationService` under `'ai.actionConfirmation'` gives the person the hand-off (`status: 'pending_confirmation'`, a `pendingId`); with none, `mcp`'s `run_action` on an action declaring `ai.requiresConfirmation: true` is refused 428 `no_confirmation_service`. -The authoritative list is `PLATFORM_CAPABILITY_TOKENS` -(`@objectstack/spec`, `kernel/platform-capabilities.ts`) — an unknown token is -**rejected by `defineStack` at authoring time**. - -Six rules that change what you write: - -- **Precedence:** `requires` › `tiers` › `--preset` › built-in default. An - explicit instance in `plugins:` always shadows capability resolution. -- **Declaring is a demand.** A table token or `ai`/`ai-studio` YOU declared - whose provider package is absent is a hard boot error; one the platform - auto-injects for you stays best-effort (warn and continue). An enterprise / - cloud token with no provider only warns at boot; `hierarchy-security`'s - scopes then fall back to owner-only. -- **`auth` implies `email`**, even under `--preset minimal`: auth callbacks - need the mail service. -- **Keep `automation` whenever `plugins:` lists a connector** — connector - executors register their provider factories with it, and without it boot - fails. -- **Under `--preset minimal`, pair `triggers` with `job`:** `triggers` alone - arms record-change triggers; schedule and time-relative ones run on the job - service, so scheduled flows stay silent. -- **AI-door confirmation is a service you register.** `mcp`'s `run_action` and - `resume_run` never run an action declaring `ai.requiresConfirmation: true` on - the call, and refuse any call that sends `confirm`. Register an - `IActionConfirmationService` under `'ai.actionConfirmation'` and the person gets - the hand-off (`status: 'pending_confirmation'`, a `pendingId`); with none (the - open build) the call is refused 428, `details.reason: 'no_confirmation_service'`. - An AI service account is refused `service_account`; a stdio client asked through - `elicitation`, `declined` / `cancelled` / `timed_out`: objectstack-ai → **MCP**. - -### `onEnable` — where an app binds runtime code - -`objectstack.config.ts` may export `onEnable` beside its default stack. -`AppPlugin` invokes it during boot and hands the app live runtime handles: this -is the one seam where declarative metadata reaches imperative code (registering -action handlers, giving a job its data handle, provisioning a fixture -datasource). - -```typescript -export const onEnable = async (ctx: { ql: { registerAction: (...a: unknown[]) => void } }) => { - registerTaskActionHandlers(ctx.ql); -}; -``` - -→ See [references/bootstrap.md](./references/bootstrap.md) § Plugin Loading Order Matters · § Programmatic Bootstrap (Without CLI) · § Multi-App Composition · § Complete Working Example. - ---- +The rest: [`requires:` in detail](./references/bootstrap.md#requires-in-detail). ## Seed Data -The stack's `data:` collection is authored with `defineSeed()`, which -**objectstack-data** owns — go there for `externalId` matching, `env:` scoping, -and which keys are derived. - -`mode` (`ignore` default · `upsert` · `update`) decides what a replay does -to existing rows: -[Import modes](../objectstack-data/references/seeds.md#import-modes). - -### Demo accounts — `demoStaff` vs `devLogins` - -A seed deals records to people (`owner_id: 'Legal Counsel 1'`) but cannot -create one: a `sys_user` row written through `data` lands as a directory row -with no account, so nobody can sign in as it. Declare the people in -`demoStaff`; `os dev` creates each account after the development admin, -signing in with the seed password (`--admin-password`, default `admin123`) — -an entry carries no `password`: +`data:` is authored with `defineSeed()`, which **objectstack-data** owns; `mode` (`ignore` default · `upsert` · `update`) decides what a replay does to existing rows: [Import modes](../objectstack-data/references/seeds.md#import-modes). -```typescript -demoStaff: [ - { name: 'Legal Lead', email: 'lead@example.com' }, - { name: 'Legal Counsel 1', email: 'counsel1@example.com', manager: 'lead@example.com', - position: 'crm_legal_counsel', permissionSets: ['crm_contracts_editor'] }], -``` +**A seed cannot create a person.** A `sys_user` row written through `data` is a directory row with no account. Declare the people in `demoStaff` (`name`, `email`, `manager` = another entry's `email`, a `position` / `permissionSets` this stack declares); `os dev`, and no other boot, creates each account and writes `manager_id` itself. `devLogins` creates and grants nothing ([Demo accounts](./references/bootstrap.md#demo-accounts--demostaff-vs-devlogins)). -`name` is what a seed reference resolves by; `position` / `permissionSets` -name only what this stack declares (a platform set such as -`admin_full_access` is refused); `manager` is another entry's `email` — the -boot writes `manager_id` itself once every account exists and keeps one set -by hand, so no seed hook writes it; a display name, an address no entry -has, the entry itself or a loop is refused at load; `os build` drops the -key and a non-dev boot creates nothing. `devLogins` creates and grants nothing — it only prints an -existing account on the boot banner. - ---- - -→ Part 2 — Plugin Development & Kernel Extension: [references/plugin-development.md](./references/plugin-development.md); its detailed rules stay at [rules/plugin-lifecycle.md](./rules/plugin-lifecycle.md) · [rules/service-registry.md](./rules/service-registry.md) · [references/plugin-hooks.md](./references/plugin-hooks.md). - ---- - -→ Part 3 — Operations: CLI, Testing, Deployment (`os deploy` to see an edit on your Cloud environment): [references/operations.md](./references/operations.md). - ---- - -## References - -See [references/_index.md](./references/_index.md) for the full list of Zod -schemas (with one-line descriptions) — pointers into -`node_modules/@objectstack/spec/src/`. Always `Read` the source for exact field -shapes; do not rely on memory of property names. +## Where to go +| Task | Open first | +|:--|:--| +| A minimal stack, map format, barrels, project layout, the template, `strict: false`, `onEnable`, boot order, composing stacks | [bootstrap.md](./references/bootstrap.md) | +| A plugin: kernels, `PluginContext`, an example, its tests | [plugin-development.md](./references/plugin-development.md) | +| `init` / `start` / `destroy`, dependencies; services | [Plugin Lifecycle](./rules/plugin-lifecycle.md) · [Service Registry](./rules/service-registry.md) | +| Kernel events (a `data:*` hook registers and never fires) | [plugin-hooks.md](./references/plugin-hooks.md) | +| The `os` CLI, ports, `os migrate`, `os deploy` to Cloud, `os mcp connect`, push, Docker, health, pitfalls | [operations.md](./references/operations.md) | +| App or platform? | **objectstack-project** | diff --git a/skills/objectstack-platform/references/bootstrap.md b/skills/objectstack-platform/references/bootstrap.md index 204e80cea95..719e82c00f6 100644 --- a/skills/objectstack-platform/references/bootstrap.md +++ b/skills/objectstack-platform/references/bootstrap.md @@ -31,6 +31,16 @@ export default defineStack({ }); ``` +### Strict Validation + +`defineStack()` validates by default (`strict: true`): + +1. **Zod schemas** — field names, types, enums +2. **Cross-references** — views/actions/flows reference defined objects +3. **Seed data** — dataset objects exist in the definition + +Disable it with `defineStack(config, { strict: false })` (objects another plugin provides). + ### Map Format (Key → Name) All named collections support **map format** where the key becomes the `name` field: @@ -50,6 +60,41 @@ export default defineStack({ }); ``` +### Manifest + +The entry file holds the rules (`engines.protocol`, the namespace prefix, which +names carry it); this is the rest. + +- `engines.protocol` is stamped by `create-objectstack`; an out-of-range app is + refused at the boundary with the exact migration command. +- The prefix check is `validateNamespacePrefix` in `@objectstack/spec` (ADR-0048); + the legacy `__` double-underscore form is rejected, and + `sys_`-prefixed names are platform-reserved and exempt. +- The namespace is also a package-ownership key — installing two packages that + both claim `crm` fails with `NamespaceConflictError` (downgrade to a warning + with `OS_METADATA_COLLISION=warn`). Never `actions`, `connectors`, `global`, + `hooks`, `oauth`, `runs`, `trigger` (route literals; `os validate` and build + refuse). +- A position holds one slot per environment (ADR-0150). The names that stay + short (flows, actions, hooks, apps, pages, dashboards, reports, datasets, + permission sets, tools, skills, agents, context packs) are identified by + package and name. A prefixed name stays valid; no name starts with `_`, which + the router reserves. `os lint`'s `naming/namespace-prefix` warns on a bare + capability or position name, and when one package declares an app, page, + dashboard, flow, report or dataset name twice, or an action name twice on one + object. + +### Project Structure Conventions + +`objectstack.config.ts` at the root is THE entry point (`defineStack()`), beside +`package.json` and `tsconfig.json`. Metadata lives under `src//` — +`objects/`, then the optional `views/`, `apps/`, +`flows/`, `actions/`, `dashboards/`, `reports/`, `datasets/`, `i18n/` and +`handlers/` (runtime hook handlers) — each with a barrel `index.ts` +(`export * from './task.object'`). +Files are named `{name}.{type}.ts` (`task.object.ts`, `main.app.ts`); machine +names and config keys follow **objectstack-data** → Naming. + ### Barrel Import Pattern ```typescript @@ -64,7 +109,8 @@ import * as views from './src/views'; import * as flows from './src/flows'; export default defineStack({ - manifest: { id: 'com.example.pm', namespace: 'pm', version: '1.0.0', type: 'app', name: 'PM' }, + manifest: { id: 'com.example.pm', namespace: 'pm', version: '1.0.0', type: 'app', name: 'PM', + engines: { protocol: '^19' } }, objects: Object.values(objects), apps: Object.values(apps), views: Object.values(views), @@ -82,6 +128,49 @@ npx create-objectstack npx create-objectstack my-app ``` +`blank` is bundled (no network fetch) and scaffolds one example object; +`requires: ['automation', 'triggers']` plus the generic connector executors in +`plugins:`; and the generator barrels +(`objects`, `views`, `actions`, `flows`, `dashboards`, `apps`, `skills`, `picklists`), +each `src/*/index.ts` handed to the stack key of its name through +`exportsOf` — the scaffolded `AGENTS.md` says how to add to them. The retired +remote templates (`todo`, `compliance`, `content`, `contracts`, `procurement`) +are refused by name. + +## Runtime Boot Sequence + +``` +objectstack.config.ts + └── defineStack({ manifest, objects, views, ... }) + │ + ▼ +CLI: `os serve` / `os dev` + 1. Load .env files (NODE_ENV-based) + 2. Dynamic import of config file + 3. Create Runtime + ObjectKernel + 4. Auto-detect and register plugins (in this order): + ├── ObjectQLPlugin (if objects defined) + ├── DriverPlugin (memory in dev, SQL in prod) + ├── AppPlugin (loads the defineStack bundle) + ├── I18nServicePlugin (if translations/i18n defined) + ├── HonoServerPlugin (registered BEFORE AuthPlugin — the server must + │ exist for plugins that mount routes during init/start) + ├── AuthPlugin + ├── Split platform-app plugins (ADR-0048, optional/best-effort): + │ @objectstack/setup → createSetupAppPlugin (first-run wizard) + │ @objectstack/account → createAccountAppPlugin + │ (@objectstack/studio is intentionally NOT default-loaded — the + │ Console, mounted at /_console/ by `--ui`, ships its own Studio + │ surface at /_console/studio/…) + ├── RESTPlugin (auto-generated API) + ├── DispatcherPlugin + └── AIServicePlugin (cloud / EE only — reverse-mounted by a cloud host) + 5. Runtime.start() → init + start all plugins + 6. Server listens on the resolved port +``` + +**Port resolution** and conflict behaviour: [Ports & networking](./operations.md#ports--networking). + ### Plugin Loading Order Matters Plugins initialize in registration order. Key dependencies: @@ -95,6 +184,65 @@ Plugins initialize in registration order. Key dependencies: | RESTPlugin | ObjectQLPlugin, AppPlugin | Generates routes from registered objects | | AIServicePlugin | ObjectQLPlugin, AppPlugin | Needs metadata for tool generation. **Cloud / EE only** — `@objectstack/service-ai` moved to cloud (cloud ADR-0025); the open edition has no in-UI AI plugin and uses `@objectstack/mcp` (BYO-AI) | +### `requires:` in detail + +The entry file's `requires:` section holds the provider table and the rules +that bite most often; this is the rest. + +- Under `--preset minimal`, `email`, `approvals` or `auth` keeps `job` and `queue`. +- The host defaults are mounted under every preset: `mcp` unless + `OS_MCP_SERVER_ENABLED=false`, and `pinyin-search` when `i18n` names a `zh-*` + locale (`OS_SEARCH_PINYIN_ENABLED` overrides). +- `record-context` serves `get_record_context`, **objectstack-ai** + [context packs](../../objectstack-ai/references/context-packs.md). + +The tokens in `PLATFORM_CAPABILITY_TOKENS` not in the provider table do not +resolve through it: + +- **Tier-gated** — `ai`, `ai-studio`, `i18n`, `ui`, `auth`: dedicated blocks + in `serve.ts` `run()` open their tier instead + (`ai`/`ai-studio` through the intent-driven AI block). +- **Enterprise / cloud** — `hierarchy-security` ships in + `@objectstack/security-enterprise`, loaded through `plugins[]`; `ai-seat`, + `governance`, `audit-compliance` and `access-policy-console` are resolved + only by cloud's objectos-runtime. + +The authoritative list is `PLATFORM_CAPABILITY_TOKENS` +(`@objectstack/spec`, `kernel/platform-capabilities.ts`) — an unknown token is +**rejected by `defineStack` at authoring time**. + +- **Precedence:** `requires` › `tiers` › `--preset` › built-in default. An + explicit instance in `plugins:` always shadows capability resolution. +- **Declaring is a demand** covers a provider-table token or `ai`/`ai-studio` + YOU declared; one the platform auto-injects for you stays best-effort (warn + and continue). An enterprise / cloud token with no provider only warns at + boot. +- **`auth` implies `email`**, even under `--preset minimal`: auth callbacks + need the mail service. +- **Keep `automation` whenever `plugins:` lists a connector** — connector + executors register their provider factories with it, and without it boot + fails. +- **AI-door confirmation:** `mcp`'s `run_action` and `resume_run` never run an + action declaring `ai.requiresConfirmation: true` on the call, and refuse any + call that sends `confirm`; with no registered service (the open build) the + 428 carries `details.reason: 'no_confirmation_service'`. An AI service + account is refused `service_account`; a stdio client asked through + `elicitation`, `declined` / `cancelled` / `timed_out`: objectstack-ai → **MCP**. + +### `onEnable` — where an app binds runtime code + +`objectstack.config.ts` may export `onEnable` beside its default stack. +`AppPlugin` invokes it during boot and hands the app live runtime handles: this +is the one seam where declarative metadata reaches imperative code (registering +action handlers, giving a job its data handle, provisioning a fixture +datasource). + +```typescript +export const onEnable = async (ctx: { ql: { registerAction: (...a: unknown[]) => void } }) => { + registerTaskActionHandlers(ctx.ql); +}; +``` + ### Programmatic Bootstrap (Without CLI) ```typescript @@ -128,6 +276,45 @@ own id (`examples/app-multi-package`). A flat `manifest` (`'last'`, the default, `'first'` or an index) keeps one, so two or more apps under one `app` or `module` package id are refused (`STACK_SINGLE_APP_VIOLATION`, 422). +## Customizing an installed package + +ADR-0146: customize an installed base `hotcrm` in its paired writable `hotcrm.custom`, which depends on it: a same-named item there with `overrides: { package: 'hotcrm', basedOn: '3.2.0' }` (its `manifest.id`/`manifest.version`) replaces the base's document whole. Reads honour it only from the pair (the row's `package_id`), for a view, dashboard, report, email_template, translation, flow, action, page, app, dataset, doc, book or mapping, never judging `basedOn`. An email template is one item per (name, locale): an override names a locale the base ships; one it does not ship is added without `overrides`. Then no `?package`, `?package=hotcrm`, the layered read and both lists serve it, and removing the pair's item (`DELETE …?package=hotcrm.custom`) serves the base's again; the env-wide list holds one item per name one code package ships (a dependent's stays under its own `?package=`); a pre-D11 unbound Setup row wins over the base's until `os migrate packageless-overlays` moves it, and once movable as a declared override, its package-less save, publish, reset and rollback are refused (D11); an email-template row at a locale the base does not ship moves as the pair's own member and keeps that write. The base's address serves the pair's added locale too (both lists, the layered read with `code` null and `effective` the pair's, the execution list, a send in that locale); one a dependent adds under the base's name is served only under its own `?package=`. An undeclared pair row or a dependent's row at a base-shipped locale is an orphan in the layered read's `overlay`, `effective` = the base's. An override may narrow a public form's anonymous intake, never re-open one any honoured body withdrew. `GET /packages/hotcrm.custom/export` carries it with `overrides`. + +The pair comes from `POST /api/v1/packages/hotcrm/ensure-customization`: `namespace` = the base's + `_custom`, `dependencies: { hotcrm: '^' }`; `GET /packages/hotcrm/customizations` lists its overrides, extensions, switched-off items and `arrangements` (`{ object, key }` per `fieldGroups`, `relatedLists` or `actionLayout` its object extension writes; no content, no diff), and uninstalling the base is refused (`409`) while the pair exists. Only the pair declares: the save, publish and install doors, `os validate` and `os build` refuse `overrides` from any other package, and a dependent's item under a base item's name — its one fix is a new name. A permission set, position or capability is never overridden: copy it under a new name ("new similar", landing in the pair). An object is extended (`__c` fields, **objectstack-data**); a flow is overridden or copied (**objectstack-automation**). An action override keeps the base's `objectName` (keyed `OBJECT:NAME`; another object is refused `declared_package_ships_no_such_item`) and replaces its behaviour (`type`, `body`, `label`, `visible`, …) whole, for whoever could already run the base: dropping a `requiredPermissions` entry, turning `ai.exposed` on or `ai.requiresConfirmation` off is refused `declared_action_widens_access`, both `403 NOT_OVERRIDABLE`. + +That read's `contributions` lists what other packages add to the base, one entry per item with its `packageId`: a `field` or `flow` names the base's `object` it is on, a `nav` item the base's `app`, its `group` if any, and its id as `name`; `counts.contributions` counts items, not packages. + +## Demo accounts — `demoStaff` vs `devLogins` + +A seed deals records to people (`owner_id: 'Legal Counsel 1'`) declared in +`demoStaff`; `os dev` creates each account after the development admin, +signing in with the seed password (`--admin-password`, default `admin123`) — +an entry carries no `password`: + +```typescript +demoStaff: [ + { name: 'Legal Lead', email: 'lead@example.com' }, + { name: 'Legal Counsel 1', email: 'counsel1@example.com', manager: 'lead@example.com', + position: 'crm_legal_counsel', permissionSets: ['crm_contracts_editor'] }], +``` + +`name` is what a seed reference resolves by; `position` / `permissionSets` +name only what this stack declares (a platform set such as +`admin_full_access` is refused); `manager` is another entry's `email` — the +boot writes `manager_id` itself once every account exists and keeps one set +by hand, so no seed hook writes it; a display name, an address no entry +has, the entry itself or a loop is refused at load; `os build` drops the +key and a non-dev boot creates nothing. `devLogins` only prints an existing account on the boot +banner. + +## App or platform + +Business features belong in the app; capability belongs in the platform. The +test, and what to do with a platform gap, are **objectstack-project**'s. Two +things it does not say: never "land the half we can" (that spends the +contract-first option and leaves a decision half-executed), and before +resuming, re-run the defect's own reproduction on the version you pin. + ## Complete Working Example **`package.json`**: diff --git a/skills/objectstack-platform/references/operations.md b/skills/objectstack-platform/references/operations.md index e5ebfaa4b2f..d706e80f9df 100644 --- a/skills/objectstack-platform/references/operations.md +++ b/skills/objectstack-platform/references/operations.md @@ -22,6 +22,12 @@ | `os start` | Quick-start a server: auto-compiles `objectstack.config.ts` when no artifact is present, and falls back to an empty kernel with the Console + marketplace when there is no config at all. It does **not** validate env or apply migrations — run `os validate` / `os migrate apply` yourself | | `os generate ` | Scaffold `object` `view` `action` `flow` `dashboard` `app` `skill` `picklist` `permission` `dataset` | +The CLI ships an `os` binary; `objectstack` is an alias for it. Runtime +metadata comes from source files during local development or from a compiled +artifact, never through the environment's business database: `os compile` +writes `dist/objectstack.json`, and +`OS_ARTIFACT_PATH=./dist/objectstack.json os dev` boots from it. + ## Verify your work Metadata mistakes surface at runtime, not at edit time: a bare field ref in a @@ -146,6 +152,44 @@ the other imports: [Using Plugins](./plugin-development.md#using-plugins). - **HTTP-level tests:** mount `createHonoApp({ kernel })` from `@objectstack/hono` and drive it with `app.request(...)` / `fetch`. +## Driver Selection Guide + +Memory and MongoDB may loudly refuse a query capability SQL serves. + +| Driver | Package | Best For | Notes | +|:-------|:--------|:---------|:------| +| **Memory** | `@objectstack/driver-memory` | Dev, testing, prototyping | `InMemoryDriver` — data lost on restart | +| **SQL** | `@objectstack/driver-sql` | Production (PostgreSQL, MySQL, SQLite) | `SqlDriver` (`pg` / `mysql` / `better-sqlite3` clients) | +| **MongoDB** | `@objectstack/driver-mongodb` | Production (document store) | `MongoDBDriver` | +| **SQLite WASM** | `@objectstack/driver-sqlite-wasm` | Browser / WebContainer | `SqliteWasmDriver` — in-process, no server | +| **Turso** | `@objectstack/driver-turso` | Edge, serverless, multi-tenant | **Cloud / EE only**. The open-core CLI recognizes `libsql://` URLs but **fails loudly** (`UnsupportedDriverError`) | + +### Wiring a driver yourself + +`plugins:` is for plugins the CLI cannot infer (connector executors, your +own plugins), never a driver. Construct `DriverPlugin` yourself only when +**you** own the runtime — embedding via `Runtime` / `ObjectKernel`, or a test +that boots a kernel directly: +`new DriverPlugin(new SqlDriver({ client: 'pg', connection: process.env.DATABASE_URL }))` +(`@objectstack/runtime` / `@objectstack/driver-sql`; a full boot: +[Programmatic Bootstrap](./bootstrap.md#programmatic-bootstrap-without-cli)). + +## HTTP Layer (Hono) + +Two packages exist: + +| Package | Export | Use When | +|:--------|:-------|:---------| +| `@objectstack/hono` | `createHonoApp({ kernel, prefix })` | You own the server: embed ObjectStack routes in your own Hono app / deploy target. | +| `@objectstack/plugin-hono-server` | `HonoServerPlugin` | ObjectStack owns the server: a kernel plugin that hosts the Hono app and opens the listening socket. | + +To integrate another framework, mount the Hono app (a web-standard `fetch` +handler) or call the dispatcher yourself. `createHonoApp` creates an +`HttpDispatcher`, mounts explicit routes for auth and discovery, and delegates +everything else to it. The auth service's `basePath` defaults to +`/api/v1/auth` (`AuthPlugin`); when a `prefix` it is not inside refuses the +boot, the refusal names both values. + ## Deployment targets | Target | Driver | HTTP layer | Notes | diff --git a/skills/objectstack-platform/references/plugin-development.md b/skills/objectstack-platform/references/plugin-development.md index 43a9b4a07a2..9e81db2739d 100644 --- a/skills/objectstack-platform/references/plugin-development.md +++ b/skills/objectstack-platform/references/plugin-development.md @@ -65,29 +65,11 @@ const kernel = new LiteKernel({ --- -## Plugin Interface — Quick Overview +## Plugin Interface -```typescript -import type { PluginContext, PluginType } from '@objectstack/core'; - -export interface Plugin { - name: string; // Unique identifier (reverse domain recommended) - version?: string; // Semantic version - type?: PluginType; // closed set exported by @objectstack/core - dependencies?: string[]; // Plugins that must init before this one - - // Phase 1: Register services - init(ctx: PluginContext): Promise | void; - - // Phase 2: Execute business logic (optional) - start?(ctx: PluginContext): Promise | void; - - // Phase 3: Cleanup (optional) - destroy?(): Promise | void; -} -``` - -See [rules/plugin-lifecycle.md](../rules/plugin-lifecycle.md) for complete examples. +`name`, optional `version` / `type` / `dependencies`, then `init(ctx)` +(required), `start(ctx)` and `destroy()`: the typed interface, and what belongs +in each phase, are in [rules/plugin-lifecycle.md](../rules/plugin-lifecycle.md#plugin-interface). --- @@ -113,34 +95,14 @@ See [rules/service-registry.md](../rules/service-registry.md) for factories and ### Hook / Event System -```typescript -// Register a kernel hook handler -ctx.hook('kernel:ready', async () => { - ctx.logger.info('System is ready!'); -}); - -// React to a metadata hot-reload / publish -ctx.hook('metadata:reloaded', async (payload?: { changed?: string[] }) => { - ctx.logger.info('Metadata reloaded', { changed: payload?.changed }); -}); - -// Trigger a custom hook -await ctx.trigger('my-plugin:initialized', { version: '1.0.0' }); -``` - -Built-in kernel events: `kernel:ready`, `kernel:bootstrapped`, -`kernel:listening`, `kernel:shutdown`, `app:seeded`, `metadata:reloaded`, -`external.schema.drift`. - -> **⚠️ There are no `data:*` kernel hooks.** Record-level lifecycle logic -> (beforeInsert / afterUpdate / …) runs on the **ObjectQL engine**, not the -> kernel event bus — author it via the `hooks:` collection or -> `ql.on('beforeInsert', 'task', async (ctx) => { … })` (see -> **objectstack-data**). Because `ctx.hook()` accepts any string, a handler -> registered for `'data:beforeInsert'` will register successfully and then -> **silently never fire**. Kernel hooks are for platform lifecycle only. +`ctx.hook(event, handler)` subscribes to a kernel event and +`ctx.trigger(event, payload)` fires one. The built-in events, their payloads +and the handler patterns: [references/plugin-hooks.md](./plugin-hooks.md). -See [references/plugin-hooks.md](./plugin-hooks.md) for the kernel event list, payloads, and patterns. +> **⚠️ There are no `data:*` kernel hooks.** `ctx.hook()` accepts any string, +> so a handler registered for `'data:beforeInsert'` registers successfully and +> then **silently never fires**. Record-level lifecycle logic runs on the +> ObjectQL engine: [why, and where to author it](./plugin-hooks.md#data-lifecycle-hooks-live-elsewhere). ### Logger