diff --git a/.claude/skills/objectstack-ai/SKILL.md b/.claude/skills/objectstack-ai/SKILL.md index 4725c62..68c6a06 100644 --- a/.claude/skills/objectstack-ai/SKILL.md +++ b/.claude/skills/objectstack-ai/SKILL.md @@ -13,7 +13,7 @@ license: Apache-2.0 compatibility: Requires @objectstack/spec 19.x (Zod v4 schemas) metadata: author: objectstack-ai - version: "19.0.0-next.2" + version: "19.0.0-next.3" domain: ai tags: agent, tool, skill, knowledge, context-pack, llm, embedding, mcp --- @@ -239,10 +239,10 @@ in `@objectstack/spec/ai`). Ship it in a package (`knowledgeSources`, `KnowledgeServicePlugin({ sources })` and `registerSource` are a second door for the same schema. A source is identified by its package and `name`; the ☁️ `search_knowledge` tool lists a package's source to agents as `NAMESPACE-NAME` -(bare for one no package holds), and a code registration and an environment -item of one name are one slot, the second refused. A shipped item mounts the -knowledge service and its store; an app that ships none and authors sources at -run time needs `requires: ['knowledge']`, or its items are never indexed. +(bare for one no package holds). A shipped item mounts the +knowledge service and its store; where an app ships none, a run-time save is +refused (`503 SERVICE_UNAVAILABLE`, nothing written) until you add +`requires: ['knowledge']` to the stack and restart the server. **A source is an egress and cost decision.** Its first build sends every listed field of every matching record to the embedding provider and keeps the text (and @@ -252,15 +252,16 @@ object or field, when you may not search that object or query a field it reads. | Key | Purpose | |:----|:--------| -| `name` | Snake_case source name; with the package, its identity | +| `name` | Snake_case source name | | `label` / `description` | Display metadata | -| `adapter` | Optional store id (`pgvector`, `turso`, `memory`). Omitted: the deployment's store (`pgvector` on PostgreSQL, `turso` otherwise), else the only one registered; several and none the deployment's is refused, naming them | +| `adapter` | Store id (`pgvector`, `turso`, `memory`). Omitted: the deployment's store (`pgvector` on PostgreSQL, `turso` otherwise), else the only one registered; several and none the deployment's is refused, naming them. A run-time save naming a store not mounted is refused (`400`), naming the mounted ones | | `source.kind` | `'object'`, the one kind | | `source.object` | The object whose records are indexed | -| `source.content` | Non-empty list of the fields whose text is indexed, in order. `'*'` is refused: embedding is egress, and a wildcard also sent fields added later. Meaningful text only, never ids or system fields; credential-class and `internal` fields are never indexed | +| `source.content` | Non-empty list of the fields whose text is indexed, in order. `'*'` is refused: it would also send fields added later. Never ids or system fields | | `source.metadataFields` | Fields kept for search-time filtering (`status`, `owner_id`, `tags`) | | `source.where` | ObjectQL `where`: keeps drafts and archived rows out | | `source.split` | How documents are cut into passages (below) | +| `source.retrieval.mode` | `'vector'` (by meaning), `'keyword'` (by words: codes, clause numbers) or `'hybrid'`; omitted: the store's default (`hybrid` on `turso`, `pgvector`). A mode the store lacks fails a run-time save; shipped, every search (503). `memory` runs none | | `refresh.onRecordChange` | Sync from record events (default `true`); `false` leaves the index to an external indexer | | `aiExposed` | May `search_knowledge` expose it (default `true`) | @@ -269,9 +270,25 @@ Retired in 19, each refused with its fix: `id` (use `name`), `contentFields` deployment configures one embedder), `vectorStore` (the store is `adapter`), `adapterConfig` (an adapter takes plugin options), `refresh.cron` (call `reindexSource` from a flow or job), and `source.kind: 'file'` / `'http'` with -`prefix`, `mimeTypes`, `urls`, `userAgent` (no form in 19). `os migrate meta +`prefix`, `mimeTypes`, `urls`, `userAgent` (attachment text: below). `os migrate meta --from 18` lists a stack's edits; edit a registration in code by hand. +`os validate` and publish check each source; an error refuses the publish: + +- `knowledge-source-object-unknown`: `source.object` is no object of the stack + or its packages (on the CLI a warning while the manifest declares a + dependency `packages[]` lacks). Name one, or declare and install its package. +- `knowledge-source-field-unknown`: a `content` / `metadataFields` member is no + field of it (`id` and the injected system columns resolve). Fix the + spelling, or remove it. +- `knowledge-source-object-not-searchable`: the API does not serve the object + for `search`. Leave `enable.apiEnabled` on; an `enable.apiMethods` list + must grant `list`, with `enable.searchable` not false. +- `knowledge-source-system-object-not-ai-readable`: a `sys_` object without + `enable.aiReadable: true`. Index a business object. +- `knowledge-source-field-never-indexed` (warning): a credential-class or + `internal: true` member, which the index never carries. Remove it. + ```typescript import { KnowledgeSourceSchema, type KnowledgeSource } from '@objectstack/spec/ai'; @@ -279,7 +296,7 @@ import { KnowledgeSourceSchema, type KnowledgeSource } from '@objectstack/spec/a export const supportKb: KnowledgeSource = KnowledgeSourceSchema.parse({ name: 'support_kb', label: 'Support Knowledge Base', - source: { // no adapter: the deployment's store + source: { kind: 'object', object: 'kb_article', content: ['title', 'body'], @@ -289,31 +306,49 @@ export const supportKb: KnowledgeSource = KnowledgeSourceSchema.parse({ }); ``` +**Sources over business objects**, not only a document library: + +- **Long free text only.** `content` lists prose: an article body, a ticket's + `description`, a note, with its title or subject line. Numbers, dates, + statuses and the names of people or accounts stay out; counts and filters + go to the record tools. "Which customers reported login loops?" is + `search_knowledge`; "how many tickets are open per priority?" is + `aggregate_records` (in-app `ask`: `aggregate_data`). +- **One source per corpus**, and a skill's `instructions` say which to pass in + `sourceIds`: `search_knowledge({ query, sourceIds: ['ticket_bodies'] })` + searches the tickets and not `support_kb`. Omitted, every exposed source is + scanned. +- **Attachment text goes through a field.** A `file` field in `content` adds + no file text. Have the flow, hook or import that extracts the text write it + to a `textarea` field (`contract.attachment_text`), and list that field. + **Splitting (`split`).** The knowledge service cuts each document into passages for a store declaring `capabilities.chunks`; any other store receives whole -documents. `split: { strategy, maxChars?, minChars? }` — `strategy` is required -once `split` is written; an omitted `split` means `recursive`: +documents. `split: { strategy, maxChars?, minChars? }` — `strategy` is +required; an omitted `split` means `recursive`: - `recursive`: cuts at blank lines, then line breaks, then sentence ends. For prose. - `markdown`: one section per heading, each passage embedded with its heading - path. For documents with headings. + path. A section that fits `maxChars` with that path is one passage; one that + does not is cut as `recursive` cuts. - `whole`: one passage per document. For short records only: a document over - the embedder's input budget is removed from the index and reported, never - truncated. + the embedder's input budget is removed from the index and reported. `maxChars`, the longest passage in characters (`whole` ignores it), overrides -the **Target chunk size** setting (`knowledge.chunk_target`, else 800); the +the **Longest passage** setting (`knowledge.chunk_target`, else 800); the embedder's input limit can lower it. Adjacent pieces shorter than `minChars` -(default 200) are merged. Changing `split` re-splits a document only when it -next changes. +(default 200) are merged in `recursive` text and in a `markdown` section that +does not fit; a section that fits stays whole whatever `minChars` is. Changing +`split` rebuilds the source's whole index, and its searches are refused until +the rebuild finishes. -Retired and refused: the `knowledge.chunk_overlap` setting (`400 UNKNOWN_KEY`; +Retired: the `knowledge.chunk_overlap` setting (`400 UNKNOWN_KEY`; passages never overlap) and `KnowledgeChunk.metadata` (parse error; a passage takes its document's `metadata`). -`topK` is a `search_knowledge` argument. Rerank and hybrid weighting are no -source key, and no shipped store has a setting for either. +`topK` is a `search_knowledge` argument; rerank and leg weights are no source +key. --- @@ -346,15 +381,16 @@ live, but listing-only: carried onto the tool, never sent to the model). ## Model Configuration Sampling lives under an agent's `model` (`AIModelConfigSchema`), **never a -top-level `temperature` / `maxTokens`** (`packages/spec/src/ai/agent.zod.ts:87-95`). -The block names a model, never a provider: the deployment's AI settings choose -the provider and resolve the model name among the providers turned on. -`provider` is retired (protocol 19): writing it is a parse error. Delete it. +top-level `temperature` / `maxTokens`** (`packages/spec/src/ai/agent.zod.ts:89-97`). +The block names a model: the deployment's AI settings choose the provider and +resolve the model name among the ones turned on. `provider` is retired +(protocol 19) and refused, except the `'openai'` an 18.x toolchain wrote out, +which parses and is stripped. Delete it. | Key | Contract | |:--|:--| -| `model` | Optional free-string model name; absent = the host's default model for the environment | -| `temperature` | `min(0).max(2)`, default `0.7`. **Outside 0–2 is a parse error** | +| `model` | Optional free-string name; absent = the host's default model | +| `temperature` | Default `0.7`. **Outside 0–2 is a parse error** | | `maxTokens` / `topP` | Optional, schema-unbounded numbers | --- @@ -443,7 +479,7 @@ https://objectstack.ai/docs/protocol-upgrade: | Retired key | Removed in 17, tombstone gone in 18 — why, and what replaces it | |:--|:--| | `agent.tools` | The inline slot resolved names against the *full* registry with no surface check. Not a rename: the strict schema refuses the key as unknown; re-declare each tool in a `defineSkill` under the stack's `skills` (ADR-0064) | -| `agent.knowledge` | Declaring sources/indexes on an agent never scoped retrieval — `search_knowledge` takes `sourceIds` from the model's tool-call arguments. Restrict on the knowledge source (`aiExposed`, `source.where`); describe intended grounding in `instructions` | +| `agent.knowledge` | Declaring sources/indexes on an agent never scoped retrieval — `search_knowledge` takes `sourceIds` from the model's tool-call arguments. Restrict on the knowledge source (`aiExposed`, `source.where`); name the `sourceIds` to pass in `instructions` (§ Knowledge Sources) | --- diff --git a/.claude/skills/objectstack-ai/evals/skills-tools-knowledge.json b/.claude/skills/objectstack-ai/evals/skills-tools-knowledge.json index 37c5204..f5cb72b 100644 --- a/.claude/skills/objectstack-ai/evals/skills-tools-knowledge.json +++ b/.claude/skills/objectstack-ai/evals/skills-tools-knowledge.json @@ -14,11 +14,21 @@ { "id": 2, "prompt": "Our copilot should use Anthropic with a low temperature (0.3) and cap responses at 2000 tokens. Where do these settings go in the metadata?", - "expected_output": "Places sampling under the agent's `model` block (`AIModelConfigSchema`): `temperature: 0.3` (0–2, outside is a parse error) and `maxTokens: 2000`, and states that there is no top-level `temperature` / `maxTokens` on an agent. Writes no provider key: `provider` is retired in protocol 19 and a parse error, because the deployment's AI settings choose the provider, not the agent. To run on an Anthropic model, names that model in the free-string `model` (the deployment resolves the name among the providers turned on) or omits it to run on the host's default model; turning Anthropic on is done in the deployment's AI settings, not in metadata.", + "expected_output": "Places sampling under the agent's `model` block (`AIModelConfigSchema`): `temperature: 0.3` (0–2, outside is a parse error) and `maxTokens: 2000`, and states that there is no top-level `temperature` / `maxTokens` on an agent. Writes no provider key: `provider` is retired in protocol 19 and refused, because the deployment's AI settings choose the provider, not the agent. To run on an Anthropic model, names that model in the free-string `model` (the deployment resolves the name among the providers turned on) or omits it to run on the host's default model; turning Anthropic on is done in the deployment's AI settings, not in metadata.", "files": [], "assertions": { "must_contain": ["temperature", "maxTokens", "deployment"], - "must_not_contain": ["provider: 'anthropic',"] + "must_not_contain": [ + "provider: 'anthropic',", + "provider: \"anthropic\",", + "provider: 'anthropic'\n", + "provider: \"anthropic\"\n", + "provider: 'anthropic' }", + "provider: \"anthropic\" }", + "provider: 'anthropic'}", + "provider: \"anthropic\"}", + "\"provider\": \"anthropic\"" + ] } }, { @@ -58,7 +68,7 @@ "expected_output": "Does not decide on the token: the script may list the queue (`client.ai.pendingActions.list({ status: 'pending' })`), but approving or rejecting an item is the person's own act, done in the app on their signed-in session by the person the assistant call ran as. An API key or token is refused on the decide door, even the person's own, and so is an AI identity; another user's `ai:approve` does not decide the item, and the model's own confirmation does not count. The script reports or notifies the stale items instead; where a second person must approve the write, that is the approvals engine's `held` outcome.", "files": [], "assertions": { - "must_contain_any": [["ai:approve", "signed-in session", "refused", "never decides"]], + "must_contain_any": [["ai:approve", "signed-in session", "refused", "refuses", "never decides"]], "must_not_contain": ["pendingActions.approve("] } }, @@ -68,7 +78,8 @@ "expected_output": "Stop sending `confirm`: `run_action` and `resume_run` refuse any call that carries the member, on every action, because the agent cannot confirm for the person. Call `run_action({ actionName: 'crm_close_deal', recordId })` without it. Where the host registers a pending-confirmation service, the answer is `status: 'pending_confirmation'` with a `pendingId` and a message: that is a success, not an error, and nothing has run. Relay the message, tell the user to approve it in the app, and do not retry. On a host with no such service (the open-source build ships none) the call is refused 428 `ACTION_CONFIRMATION_REQUIRED` with `details.reason: 'no_confirmation_service'`, and the person performs the action in the app. The two delete tools still take the member.", "files": [], "assertions": { - "must_contain": ["pending_confirmation", "pendingId", "no_confirmation_service", "do not retry"], + "must_contain": ["pending_confirmation", "pendingId", "no_confirmation_service"], + "must_contain_any": [["do not retry", "Do not retry", "don't retry", "Don't retry"]], "must_not_contain": ["recordId, confirm: true", "then retry with"] } }, @@ -136,12 +147,23 @@ { "id": 14, "prompt": "Our app ships no knowledge source in its package: admins will create them at run time in Studio, and an agent of ours saves them over MCP. What does `objectstack.config.ts` need so those sources are indexed and searchable? Answer from what is stated here.", - "expected_output": "Adds `requires: ['knowledge']` to the stack: a source the app ships in `knowledgeSources` mounts the knowledge service and its store by itself, but an app that ships none and authors its sources at run time must list the token, or a saved source is never indexed and no search tool serves it. Names no `adapter` requirement (the deployment's store is used) and adds no `knowledgeSources` entry the prompt did not ask for. Says that creating or changing a source at run time needs `manage_knowledge_sources` beside `manage_metadata`.", + "expected_output": "Adds `requires: ['knowledge']` to the stack: a source the app ships in `knowledgeSources` mounts the knowledge service and its store by itself, but an app that ships none and authors its sources at run time must list the token, or a run-time save is refused (`503 SERVICE_UNAVAILABLE`, nothing written) until the stack declares it and the server restarts. Names no `adapter` requirement (the deployment's store is used) and adds no `knowledgeSources` entry the prompt did not ask for. Says that creating or changing a source at run time needs `manage_knowledge_sources` beside `manage_metadata`.", "files": [], "assertions": { "must_contain_any": [["requires: ['knowledge']", "requires: [\"knowledge\"]"]], "must_not_contain": ["contentFields:"] } + }, + { + "id": 15, + "prompt": "Our support app has `kb_article` (`title`, `body`) and `support_ticket` (`subject`, `description` as a textarea, `priority`, `status`, `amount`, and a `contract_pdf` file field holding a signed PDF). The assistant should answer from article bodies, from ticket descriptions and from what the PDFs say, and also tell us how many open tickets there are per priority. Design the knowledge sources and say how a skill should search them. None of the project's files are in this directory: write the files in your answer.", + "expected_output": "Writes two `knowledge_source` items, one per corpus (articles, tickets), each `source: { kind: 'object', … }` with an explicit `content` list of long free-text fields only: `title` / `body` for articles, `subject` / `description` for tickets. `priority`, `status` and `amount` are not in `content` (at most `metadataFields`), and the count of open tickets per priority is answered by a record tool (`aggregate_records` / `query_records`), not by `search_knowledge`. The PDF is not indexed from the `contract_pdf` file field and no `kind: 'file'` or `'http'` source is written (both retired): the extracted text is first written to a text field on the record (a `textarea`, filled by a flow, hook or import) and that field is listed in `content`. The skill's `instructions` tell the model which source to search by passing `sourceIds` to `search_knowledge`, so a question does not scan every source; no second argument shape and no `knowledge` key on the skill is invented.", + "files": [], + "assertions": { + "must_contain": ["sourceIds", "content:", "textarea"], + "must_contain_any": [["aggregate_records", "query_records", "aggregate_data"]], + "must_not_contain": ["kind: 'file',", "kind: \"file\",", "kind: 'http',", "kind: \"http\",", "contentFields:", "content: ['priority'", "content: ['status'", "content: ['amount'", "content: ['contract_pdf'", "'description', 'priority'", "'description', 'status'", "'description', 'amount'", "'description', 'contract_pdf'"] + } } ] } diff --git a/.claude/skills/objectstack-api/SKILL.md b/.claude/skills/objectstack-api/SKILL.md index c8bfc64..f8c56d9 100644 --- a/.claude/skills/objectstack-api/SKILL.md +++ b/.claude/skills/objectstack-api/SKILL.md @@ -14,425 +14,138 @@ license: Apache-2.0 compatibility: Requires @objectstack/spec 19.x (Zod v4 schemas) metadata: author: objectstack-ai - version: "19.0.0-next.2" + version: "19.0.0-next.3" domain: api tags: rest, endpoint, auth, realtime, server --- # API Design — ObjectStack API Protocol -## Skill Boundaries +A custom endpoint is **metadata** (`defineStack({ apis })`), never a route an app mounts. -| Need | Use instead | -|:-----|:------------| -| Model objects, fields, permissions, or datasources (`rules/datasources.md`) | **objectstack-data** | -| Pick a driver package | **objectstack-platform** → Driver Selection Guide | -| Filter, sort, paginate, or aggregate a request | **objectstack-query** | -| Register a kernel service, or read one from a plugin | **objectstack-platform** | -| CEL in a route guard or auth predicate | **objectstack-formula** | +## First checks ---- - -## Auto-Generated vs Custom APIs +1. **Version.** Where the installed `@objectstack/spec` version differs from this skill's + `compatibility` line, the installed contract is right. Declared endpoints are live from + protocol 17: an older `apis:` block turns from inert text into an execution entry point + (the protocol upgrade guide's `declarative-apis-endpoints-live` entry). +2. **Read what exists**: the stack's `apis` and `manifest.namespace`, the object's + `apiMethods`. Prefer a generated route. +3. **Read the contract** ([references/_index.md](./references/_index.md)); an endpoint is + `node_modules/@objectstack/spec/src/api/endpoint.zod.ts`. Never recall a key or a code. +4. **Verify**: `os validate` or `os build`. A declaration this runtime cannot serve is + rejected one publish gate at a time: read the rejection, it carries the fix. -### Auto-Generated APIs +## Generated routes -Every ObjectStack object with `apiEnabled: true` (the default) automatically -gets a full REST API: +Served with nothing authored (`data`: an object with `apiEnabled: true`, the default): ``` -GET /api/v1/data/{object} # List records (with filter, sort, pagination) -GET /api/v1/data/{object}/:id # Get single record -POST /api/v1/data/{object} # Create record -PATCH /api/v1/data/{object}/:id # Update record -DELETE /api/v1/data/{object}/:id # Delete record (business-object rows → recycle bin) -POST /api/v1/data/{object}/query # Complex queries + aggregation (QueryAST in body) -POST /api/v1/data/{object}/batch # Per-object batch operations -POST /api/v1/batch # Cross-object atomic batch +GET|POST /api/v1/data/{object} # list | create +GET|PATCH|DELETE /api/v1/data/{object}/:id # get | update | delete (→ recycle bin) +POST /api/v1/data/{object}/query # QueryAST body, aggregation +POST /api/v1/data/{object}/batch # per-object batch +POST /api/v1/batch # cross-object atomic batch +POST /api/v1/data/{object}/import, GET …/export +GET /api/v1/meta/:type[/:name] # metadata read (object, view, flow, …) ``` -There is no `/bulk` route and no `GET .../aggregate` route — batch writes go -through the `batch` endpoints. - -> **Key rule:** If your object defines `apiMethods`, only those operations (and -> what derives from them) are exposed; `[]` means deny-all. - -### Metadata API (`/meta`) +There is no `/bulk` route and no `GET …/aggregate`. -The metadata read surface lives under `/api/v1/meta` (separate from the data -CRUD routes above): - -``` -GET /api/v1/meta/:type # List metadata items of a type (object, view, flow, doc, …) -GET /api/v1/meta/:type/:name # Read a single metadata item -``` - -The list reads a closed query set — `package`, `preview` (`draft`), `object`, -`include` (`content`, `grants`), `id`, `names`, `locale` — and refuses any other key with -`400 VALIDATION_ERROR` instead of ignoring it. `?names=a,b,c` (one -comma-separated value) narrows the list to the named items the caller may see: -an unknown name is simply absent, an empty value is refused `400`, and the -`package` list (keyed by id) refuses the key. These are **client** contracts — -nothing in a stack declares them. - -### Public (anonymous) Form Endpoints - -A `FormView` is served by the anonymous form endpoints only when its -`sharing` declares all three: `enabled: true` (the schema default is -`false`), `allowAnonymous: true` and a `publicLink` slug. Miss any one and -both endpoints answer `404 FORM_NOT_FOUND`. The form is then mounted at: - -``` -GET /api/v1/forms/:slug # returns form spec + restricted objectSchema -POST /api/v1/forms/:slug/submit # whitelist-filtered INSERT, no auth header -``` +- **`GET /api/v1/meta/:type` reads a closed query set** (`package`, `preview`, `object`, + `include`, `id`, `names`, `locale`) and refuses any other key with `400 VALIDATION_ERROR`. + `?names=a,b,c` (one comma-separated value) narrows the list to the named items the caller + may see: an unknown name is absent, an empty value is refused `400`. +- **An import** takes `mapping` as `{ Column: field }` or as `FieldMappingEntry[]` + (`api/export.zod.ts`). Only an entry, `{ sourceField, targetField, applyOn }`, carries + `applyOn` (default `'always'`): `'create'` writes the column only when the row is + created, so a re-run `upsert` keeps a value an admin set since. -These bypass `enforceAuth` (Web-to-Lead / Web-to-Case flows). The form's own -declaration authorizes the submit: a `publicFormGrant` on its target object -(create and read-back of its new row, nothing else), decided before any permission -set resolves. The submit context's `guest_portal` name admits nothing and needs -no set; a set so named only feeds the grant's result masker. The framework -strips fields outside the form's `sections[].fields[]` list; a -`beforeInsert` hook on the target object should stamp safe defaults -(`status='new'`, `lead_source='web'`, …) and `delete` privileged keys -(`owner`, `internal_notes`, …). On a walled posture (`group`/`isolated`), a -form on an object walled by an organization column is withheld too — both -endpoints `404`, and save / publish warn `public-form-intake-unavailable`; -declare `tenancy: { enabled: false }` on an object whose rows belong to no -organization to offer it again. For the full contract, read -`node_modules/@objectstack/spec/src/ui/view.zod.ts` (`FormViewSchema`) and -`node_modules/@objectstack/spec/src/ui/sharing.zod.ts` (`SharingConfigSchema` -with `enabled` / `allowAnonymous` / `publicLink`). - -A form open to anonymous intake declares no file field. A section field whose -object type is in `FILE_REFERENCE_TYPES` (`image`, `file`, `avatar`, `video`, -`audio`) is refused by the gating lint rule `public-form-file-field` — at -`os validate` / `os build` / `os lint`, and at the view's publish — because a -visitor has no upload door to mint a `sys_file` id. A form published before that -rule meets the same refusal at submit: a file value answers the flat `400 -VALIDATION_FAILED` with `fields[].code: 'invalid_value'`. Collect the file on a -signed-in form instead. - ---- - -## Declarative Endpoints (`apis:`) — no handler code - -`defineStack({ apis })` declares an HTTP endpoint as **metadata**. Declared -endpoints are **live from protocol 17**: the runtime matches -`METHOD` + `path`, runs the endpoint's policy keys, and delegates to the *same* -pipelines the built-in routes use — `object_operation` to the data pipeline -behind `/api/v1/data/{object}`, `flow` to the automation pipeline behind -`POST /api/v1/automation/{name}/trigger`. An endpoint is a stable URL plus a -policy layer over an existing pipeline, never a second execution dialect. +## API Methods (Operations) -### Choosing between `apis:` and a code handler +`apiMethods` whitelists the six authorable primitives (`ApiMethod`): `get`, `list`, +`create`, `update`, `delete`, `bulk` (the `/batch` route); unset is all, `[]` none. Every +other operation derives and is never declared (a declared one is stripped at parse, with a +warning): `aggregate`, `export` and, where `searchable`, `search` (the global +`GET /api/v1/search`) from `list`; `import` from `create` ∨ `update`; `history` from `get` +∧ `trackHistory`; `restore` and `purge` (trap 3) from `delete`; `upsert` from `create` ∧ +`update`, with no route: query by the external ID, then create or update through `/batch`. -| Use | When | -|:---|:---| -| **`defineStack({ apis })`** | The endpoint is a *projection* of something the platform already executes: query/return records, or trigger a flow. No code, no deploy artifact, publish-gated. **Prefer this.** | -| **A flow that runs your code** | The endpoint needs real handler CODE: point a `type: 'flow'` endpoint at a flow whose `script` node names a stack function (`defineStack({ functions })`; which one runs: [objectstack-automation](../objectstack-automation/SKILL.md#valid-but-silently-wrong-passes-build-fails-at-runtime) item 3), or whose `connector_action` node calls a declared connector (outbound). The URL stays declarative; the code runs where the automation surface already runs it. | +## A declared endpoint -An inbound webhook is a `type: 'api'` flow (objectstack-automation → -**Inbound webhook (`api`) triggers**): it verifies ObjectStack's own -`x-objectstack-signature`, or a vendor's own HMAC-SHA256 header its start node -declares as `config.signature` (DocuSign Connect, Stripe-style), enqueues, and -answers `202`. -**An app never mounts on `http.server`** — that service is the platform -plugins' own door-building primitive, and a code-mounted route gets no caller -identity, auth gate, rate limit, namespace carve-out or OpenAPI entry. Three -cases have no app surface today; say so rather than invent one: a third-party -callback signed in a form `config.signature` cannot declare (not HMAC-SHA256), -a streaming response (a declared endpoint answers one JSON envelope), and a -protocol the platform does not speak. +`type` is `object_operation` or `flow`, the pipelines of `/api/v1/data/{object}` and +`POST /api/v1/automation/{name}/trigger`; `script` and `proxy` are rejected at publish. ```typescript import type { ApiEndpoint } from '@objectstack/spec/api'; -// The stack declares `manifest: { namespace: 'acme', … }` — required, see below. +// `manifest: { namespace: 'acme', … }` is required, never derived from `id`. export const leadFeed: ApiEndpoint = { name: 'acme_lead_feed', path: '/api/v1/apps/acme/leads', // /api/v1/apps// method: 'GET', - summary: 'Lead feed', type: 'object_operation', objectParams: { object: 'acme_lead', operation: 'find' }, - cacheTtlSeconds: 30, // GET-only; rides success answers only + cacheTtlSeconds: 30, // GET-only }; ``` -### The path carve-out (ADR-0121 D1/D2) - -A declared path must be `/api/v1/apps//`. Only the -subpath is yours to name, and the ordinary naming rules below apply inside it. -`manifest.namespace` must be declared **explicitly** — it is never derived from -`manifest.id`. A path outside the carve-out is rejected at publish. - -### Five publish gates, each with a prescription - -A declaration this runtime cannot serve is **rejected at publish**, one gate at -a time. Do not memorise the gate texts; **read the rejection**, it carries the -fix. The five: **namespace** (the carve-out above), **supported target** -(`script` / `proxy` do not execute in 17.x; an `object_operation` needs both -`objectParams.object` and `.operation`; a `flow` needs a `target`), -**mapping** (below), **policy** (below), and **uniqueness** (one `METHOD` + -path claim per stack). - -### `authRequired` and the D6 pairing - -`authRequired` defaults to `true`, so **omitting it is safe**. An explicit -`false` is the only thing that opens an anonymous, unauthenticated execution -entry point — and ADR-0121 **D6** pairs it with an *armed* budget: - -```typescript -authRequired: false, -rateLimit: { enabled: true, windowMs: 60_000, maxRequests: 100 }, -``` - -The gate's predicate is `rateLimit.enabled === true`, **not** the key's presence: -`RateLimitConfigSchema.enabled` (`@objectstack/spec/shared`) itself defaults to `false`, so writing only -`windowMs` / `maxRequests` declares a budget that meters nothing. Endpoint -budgets are metered independently of the server-level `server.security.rateLimit`. - -### Mapping keys: projection only - -`inputMapping` / `outputMapping` **move and rename fields by dot path, and -nothing more**. `inputMapping` maps the REQUEST BODY, applied after the policy -chain and before delegation (so a mapping can never buy a caller past -`authRequired` or the rate limiter); `outputMapping` is applied to a **successful** -response body only. Three consequences worth knowing before you author one: - -- `transform` is rejected — there is no transformation-function registry. - Compute the value where it is produced (a flow, or a formula field). -- `inputMapping` is rejected on a `find` / `get` / `delete` `object_operation`, - which never reads a request body. -- Two entries cannot write the same target path, nor one inside the other - (`x` and `x.y`). - -### Upgrading a pre-17 stack - -An `apis:` block written against an older major **changes meaning without -changing a byte** — inert documentation becomes an execution entry point. Work -through the `declarative-apis-endpoints-live` entry of the protocol upgrade -guide before upgrading; it is a security review, not a rename. Its two -load-bearing steps: move every `path` into the carve-out, and grep every entry -for `authRequired: false`. - ---- - -## Endpoint Naming Conventions - -| Pattern | Use Case | Example | -|:--------|:---------|:--------| -| `/api/v1/{object}/:id/{action}` | Custom action on record | `/api/v1/cases/:id/close` | -| `/api/v1/{domain}/{action}` | Domain-level action | `/api/v1/ai/chat` | - -**Rules:** - -- Always use **plural nouns** for collection paths (`accounts`, not `account`). -- Use **snake_case** for multi-word paths (`project_tasks`, not `projectTasks`). -- Use **verbs** only for actions, not for CRUD (`/close`, `/approve`). - ---- - -## API Methods (Operations) - -The authorable `ApiMethod` enum is the SIX PRIMITIVES. The wider EFFECTIVE -vocabulary (`ApiOperation`, 14 values) is what gates and responses speak; its -eight extra verbs are never declared in `apiMethods`: - -**Authorable primitives:** - -| Method | HTTP surface today | Purpose | -|:-------|:-------------------|:--------| -| `get` | `GET /data/{object}/:id` | Retrieve a single record | -| `list` | `GET /data/{object}` | List records with filter/sort/pagination | -| `create` | `POST /data/{object}` | Create a new record | -| `update` | `PATCH /data/{object}/:id` | Update an existing record | -| `delete` | `DELETE /data/{object}/:id` | Delete a record | -| `bulk` | `POST /data/{object}/batch` | Batch create/update/delete (bulk ∧ child op) | - -**Derived operations (granted automatically, never authored):** - -| Operation | Derives from | HTTP surface today | -|:----------|:-------------|:-------------------| -| `upsert` | `create` ∧ `update` | none generated | -| `aggregate` | `list` | `POST /data/{object}/query` with `groupBy`/`aggregations` | -| `search` | `list` ∧ `searchable` | global `GET /api/v1/search`, not per-object | -| `import` | `create` ∨ `update` (writeMode-precise) | `POST /data/{object}/import` | -| `export` | `list` | `GET /data/{object}/export` | - -`history` (from `get` ∧ `trackHistory`) gates only. `restore` / `purge` derive -from `delete` and open the recycle-bin doors (pitfall 2). Declaring any -derived verb in `apiMethods` is stripped at parse with a FROM → TO warning. - -`POST /data/{object}/import` takes `mapping` as `{ Column: field }` or as -`FieldMappingEntry[]` (`api/export.zod.ts`); only the entry form carries -`applyOn`. `'always'` (default) writes the column on every row the import -creates or updates; `'create'` writes it only when the row is created, so a -re-run `upsert` refreshes the `always` columns and leaves a value an admin set -since (an owner, a stage) as it is. A create-only column is still read for -matching. Any other value is `400 INVALID_REQUEST`. - ---- - -## Discovery & Health - -`GET /api/v1/health`, `GET /ready` (200 running / 503 booting) and -`GET /api/v1/discovery` (per-service status) exist on **every** deployment. -All three are **response** surfaces — nothing to author. - ---- - -## Dispatcher Error Codes - -The **HttpDispatcher** is the central request router; it answers: - -| HTTP Status | Error Code | When | -|:------------|:-----------|:-----| -| 404 | `ROUTE_NOT_FOUND` | No route matches the path | -| 405 | `METHOD_NOT_ALLOWED` | Route exists but method not supported | -| 501 | `NOT_IMPLEMENTED` | Route declared but handler is a stub | -| 503 | `SERVICE_UNAVAILABLE` | Service is registered but not ready | - ---- - -## Realtime Subscriptions - -- `node_modules/@objectstack/spec/src/api/realtime.zod.ts` — `TransportProtocol` - (`websocket` | `sse` | `polling`), `SubscriptionSchema` (`id`, `events[]`, - `transport`, optional `channel`), `RealtimeEventSchema`, and - `RealtimeConfigSchema`. -- `node_modules/@objectstack/spec/src/api/websocket.zod.ts` — the WebSocket - message protocol: subscribe/unsubscribe messages, event delivery, presence, - cursor and collaborative-edit messages, and ack/error/ping/pong frames. - ---- - -## Authentication & Authorization - -### Auth Configuration - -There is no nested `auth` block on an endpoint, and no `name` / `request` / -`response` field: auth is the flat `public` + `permissions` pair on -`RestApiEndpointSchema`, and declarative `ApiEndpointSchema` endpoints (and the -dispatcher) use `authRequired: boolean` (D6 above). - -### Auth Providers - -Provider and login contracts live in -`node_modules/@objectstack/spec/src/api/auth.zod.ts`: `AuthProvider` is -`'local' | 'google' | 'github' | 'microsoft' | 'ldap' | 'saml'`, and -`LoginRequestSchema` carries `type` (login method), plus optional `email`, -`username`, `password`, `provider`, and `redirectTo`. Read that file for the -session and token response shapes before wiring an auth flow. - ---- - -## Error Envelopes & the Code Ledger (ADR-0112) - -`error.code` is **two-tier**: the closed `StandardErrorCode` catalog plus the -codes registered per owning package in `api/error-code-ledger.zod.ts`. -`ApiErrorSchema.code` validates the union, so an **unregistered code fails -parse → fails the envelope conformance suites → fails CI**. - -That ledger takes **framework packages only**. A downstream repo keeps its OWN -ledger and composes the two checks itself — `envelopeViolations(body)` for the -SHAPE, `makeApiErrorSchema(yourCodes)` for the VOCABULARY (both in -`api/contract.zod.ts`). What no repo may do is emit a code in no ledger at all. - -`userMessage` is producer-marked user-facing text in the REQUEST's locale; render it as -received and keep no per-code translation table. Platform-composed text follows one ladder -over the platform locale table (`PLATFORM_LOCALES`, `@objectstack/spec/system`): the locale -the request names (its `Accept-Language`, or `?locale` on the REST door), else the workspace -default, else `en`, each code read whole and then one subtag shorter at a time (`fr-FR` → -`fr`, `zh-Hant-US` → `zh-Hant`). App-authored text, such as a hook's catalogued refusal, is -not on this ladder: it is served in the caller's locale from the app's own translations, -otherwise as declared, with no `en` floor. The save / publish doors' `advisories[]` and the -422 `issues[]` share one element, `RuntimeAuthoringIssueSchema` (`api/protocol.zod.ts`): it -carries an optional `userMessage` beside the stable `rule`, while `message` / `hint` stay -developer-facing English; absent, render `message`. -A batch publish (`POST /api/v1/packages/:id/publish-drafts`) may answer `probes`, its runtime -findings (`BuildProbeReportSchema`, same file; ADR-0038). Each `issues[]` element -(`RuntimeBuildIssueSchema`) has two readers: `message` / `fix` are English for the agent that -built the app, the optional `userMessage` is the sentence for the person who published. Show -a person `userMessage`, never `message`; absent, show your own generic sentence. This door -reads the request's locale from `Accept-Language` alone. - -A flow door — `POST /api/v1/automation/{name}/trigger`, resume, `/actions`, a -declared `type: 'flow'` endpoint — answers a failed run with `400 FLOW_FAILED`; -its `error.details` is `FlowFailureDetailsSchema` (`api/automation-api.zod.ts`): -`errorMessage?` (the flow author's text), `summary?` (which node failed) and -`innerRefusal?`, the `{ code, message }` refusal a node met (a data node's read -or write, a `script` node's function name), `code` an `ErrorCode` member in wire -spelling (e.g. `UNIQUE_VIOLATION`, `PERMISSION_DENIED`, `RESOURCE_CONFLICT`). -Render it as a record form renders a refused save: -top-level `userMessage`, then `details.innerRefusal`, then `message`. Absent -keys mean the run produced none — never invent an empty. - ---- - -## Best Practices - -1. **Use auto-generated APIs** whenever possible. Only create custom endpoints - for business logic that cannot be expressed through CRUD + triggers. -2. **Return consistent error shapes.** The dispatcher envelope is - `DispatcherErrorResponseSchema`: `{ success: false, error: { code, message, - httpStatus?, route?, service?, hint? } }`, where `code` is the **semantic** - string and `code`/`message` are required. General API errors use - `ErrorResponseSchema` (`errors.zod.ts`). Be aware the shipped data routes - return flat `{ error, code }` bodies instead (e.g. `CONCURRENT_UPDATE` → - 409, `VALIDATION_FAILED` → 400). -3. **Design idempotent writes deliberately.** No upsert route is generated, so - an external integration queries by its unique external ID and branches to - create or update — group those writes through - `POST /api/v1/data/{object}/batch`. - ---- - -## Common Pitfalls - -1. **Not handling 409 Conflict.** The generated `PATCH /api/v1/data/{object}/:id` - route does optimistic concurrency with two spellings: the `If-Match` header - **or** an `expectedVersion` field in the JSON body — **the body wins** when - both are sent, and the token is typically the `updated_at` value the client - read. Sending neither skips the check; a mismatch answers **409 - `CONCURRENT_UPDATE`**; the quoted-empty entity-tag (`""`) is refused **400 - `VALIDATION_FAILED`**, not treated as omitted. -2. **Treating `DELETE` as final.** A by-id delete keeps a business object's - rows in the recycle bin (`sys_recycle_bin`, 30 days by default; not - `multi: true` deletes, platform rows or rows deleted before the bin existed) - and answers `recycleBinEntryId`. Under `/api/v1/data/{object}/recycle-bin`: - `POST /:entryId/restore` (`allowRestoreOwnDeleted` for your own deletes, - `manageRecycleBin` for others'); `GET` lists, `DELETE /:entryId` purges, - `DELETE` empties (`manageRecycleBin`). A refused restore answers `409` - `RESTORE_UNIQUE_VALUE_TAKEN`, `RESTORE_PARENT_PURGED`, - `RESTORE_PARENT_IN_RECYCLE_BIN` (restore that parent's entry first) or - `RESTORE_PACKAGE_UNINSTALLED`, and keeps the entry. No soft-delete. - ---- - -## Verify your work - -After adding a `*.endpoint.ts`, a custom route, or an auth provider, run the -author-time gate before reporting done: - -```bash -os validate # Zod schema + CEL predicate validation + bindings (no artifact) -# or: os build # the same gates, plus emits dist/ -``` - -Route-guard and auth predicates are CEL; the gate parses them and fails -non-zero with a located message instead of letting a malformed guard fall -through at runtime. In a scaffolded project the gate is `npm run validate`. See -objectstack-platform → **Verify your work** for the full gate list. - ---- - -## 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. - +`inputMapping` / `outputMapping` only move and rename fields by dot path; `transform` is +rejected: compute the value in a flow or a formula field. + +## Traps + +1. **`authRequired: false` needs an ARMED budget.** Omitting the key is safe (default + `true`); an explicit `false` opens an anonymous execution entry point and pairs with + `rateLimit: { enabled: true, windowMs: 60_000, maxRequests: 100 }`. The gate reads + `rateLimit.enabled === true`, not the key's presence: `enabled` defaults to `false`, so + `windowMs` / `maxRequests` alone meter nothing. Endpoint budgets are metered apart from + `server.security.rateLimit`. +2. **An app never mounts on `http.server`**, the platform plugins' own primitive: a + code-mounted route gets no caller identity, auth gate or rate limit. Handler code runs in + a flow: a `type: 'flow'` endpoint names it in `target`; its `script` node names a stack + function (`defineStack({ functions })`; which one runs: + [objectstack-automation](../objectstack-automation/SKILL.md)), or its `connector_action` + node calls a declared connector. An inbound webhook is a `type: 'api'` flow: it verifies + ObjectStack's own `x-objectstack-signature`, or a vendor's HMAC-SHA256 header its start + node declares as `config.signature` (DocuSign Connect, Stripe-style), enqueues, and + answers `202`. No app surface exists for a callback signed in a form `config.signature` + cannot declare, a streaming response or a protocol the platform does not speak: say so, + never invent one. +3. **`DELETE` is not final.** A by-id delete keeps a business object's rows in the recycle + bin (`sys_recycle_bin`, 30 days by default; not `multi: true` deletes or platform rows) + and answers `recycleBinEntryId`. `POST /api/v1/data/{object}/recycle-bin/:entryId/restore` + restores it (`allowRestoreOwnDeleted` for your own deletes, `manageRecycleBin` for + others'); listing, purging and emptying the bin need `manageRecycleBin`. No soft-delete. +4. **A `PATCH` with no version token skips the concurrency check.** Send `If-Match`, or + `expectedVersion` in the JSON body (the body wins; the token is typically the + `updated_at` the client read). A mismatch answers `409 CONCURRENT_UPDATE`. +5. **A public form answers `404 FORM_NOT_FOUND` unless its `sharing` declares all three**: + `enabled: true` (default `false`), `allowAnonymous: true` and a `publicLink` slug. Then + `GET /api/v1/forms/:slug` and `POST /api/v1/forms/:slug/submit` bypass auth; the + declaration grants only the create and read-back of its row. Fields outside + `sections[].fields[]` are stripped; write a `beforeInsert` hook that stamps safe defaults + and deletes privileged keys (`owner`, …). On a walled posture a form on an + organization-walled object is withheld too, and save and publish only warn + (`public-form-intake-unavailable`): declare `tenancy: { enabled: false }` where the rows + belong to no organization. +6. **`userMessage` is the sentence for a person**: render it as received and keep no + per-code translation table. It is in the REQUEST's locale (platform text: + `Accept-Language`, or `?locale` on the REST door, else the workspace default, else `en`). + On a batch publish's `probes.issues[]` (`POST /api/v1/packages/:id/publish-drafts`; + `RuntimeBuildIssueSchema`, `api/protocol.zod.ts`; `Accept-Language` alone) `message` / + `fix` are developer English: show `userMessage`, never `message`, and with none your own + generic sentence. A flow door's `400 FLOW_FAILED`: `userMessage`, then + `details.innerRefusal` (`api/automation-api.zod.ts`), then `message`. + +## Where to go + +| Need | Open | +|:-|:-| +| An endpoint key, a publish gate, a mapping refusal | `api/endpoint.zod.ts`; https://objectstack.ai/docs/api/declarative-endpoints | +| A generated route's request and answer; discovery | https://objectstack.ai/docs/protocol/kernel/http-protocol | +| An error code or envelope; a new `error.code` (one in no ledger fails CI) | `api/errors.zod.ts`, `api/dispatcher.zod.ts`, `api/error-code-ledger.zod.ts`; https://objectstack.ai/docs/api/error-catalog | +| Auth (an endpoint has no nested `auth` block: `authRequired`) | `api/auth.zod.ts`: `AuthProvider` (`local`, `google`, `github`, `microsoft`, `ldap`, `saml`), `LoginRequestSchema` | +| A public form | https://objectstack.ai/docs/ui/forms | +| Objects, permissions; filters; kernel services, drivers | **objectstack-data**; **objectstack-query**; **objectstack-platform** | diff --git a/.claude/skills/objectstack-ask/SKILL.md b/.claude/skills/objectstack-ask/SKILL.md index 3707a7a..7ad017d 100644 --- a/.claude/skills/objectstack-ask/SKILL.md +++ b/.claude/skills/objectstack-ask/SKILL.md @@ -17,7 +17,7 @@ license: Apache-2.0 compatibility: Requires an environment served by @objectstack/mcp 19.x metadata: author: objectstack-ai - version: "19.0.0-next.2" + version: "19.0.0-next.3" domain: process tags: ask, question, metric, dataset, mcp, list_datasets, query_dataset, 问数, 指标 --- diff --git a/.claude/skills/objectstack-automation/SKILL.md b/.claude/skills/objectstack-automation/SKILL.md index 97b3e32..53ab5ad 100644 --- a/.claude/skills/objectstack-automation/SKILL.md +++ b/.claude/skills/objectstack-automation/SKILL.md @@ -11,75 +11,67 @@ license: Apache-2.0 compatibility: Requires @objectstack/spec 19.x (Zod v4 schemas) metadata: author: objectstack-ai - version: "19.0.0-next.2" + version: "19.0.0-next.3" domain: automation tags: flow, workflow, trigger, approval, state-machine, scheduled, webhook --- # Automation Design — ObjectStack Automation Protocol -## When to Use This Skill +## First checks -Also vendor-integration callbacks and **assignment rules**. +1. **Version.** Read the installed `@objectstack/spec` + (`node_modules/@objectstack/spec/package.json`); where it differs from this + skill's `compatibility` line, the installed contract is right. +2. **Read what exists.** Read the object's fields and option `value`s, the + flows already bound to it, and the functions, queues and connectors the + stack declares. +3. **Read the type's contract.** [references/_index.md](./references/_index.md) + points at each type's Zod source in `node_modules/@objectstack/spec/src/`. + `Read` it for exact keys, never from memory. + A running environment serves the parsed shape (`GET /api/v1/meta/types`): + a defaulted key reads as required. +4. **Verify before reporting done.** `os validate`; CEL checks: + **objectstack-formula** § Verify your work. Most traps below pass it. -> **Predicates and conditions are CEL** — every `condition` / `guard` / -> `entryCondition` / filter `value` is an **Expression** envelope: a plain CEL -> string, or the `P\`...\`` / `cel\`...\`` tag (author-time validation); pick one -> per file. +**Nothing to read yet?** Say so in a line, then still give the whole +definition as code. ---- - -## Flows — Visual Logic Orchestration +## Where to go -### Flow Types +Open the file for what you are writing before you write it. -| Type | When to Use | +| Authoring | Open first | |:--|:--| -| `autolaunched` | No user interaction: started by events, APIs or other flows | -| `screen` | Shows UI screens | -| `schedule` | Runs on a cron/interval cadence declared on the **start node's `config.schedule`**, or a **per-record date sweep** via `config.timeRelative` | -| `record_change` | Fires on record create/update/delete. `autolaunched` + the same `record-*` binding behaves identically; `record_change` also opts into the trigger-readiness lint | -| `api` | Inbound **webhook** (*Inbound webhook triggers*); a flow only ever started explicitly is `autolaunched` | - -**A stepped form over one object that never branches** is no flow: an **objectstack-ui** named form view (`type: 'wizard'`) a `type: 'form'` action opens. - -**A flow an installed package ships** is read-only. To change what it does, save -a same-named flow in the base's paired `.custom` package declaring -`overrides: { package: '', basedOn: '' }` -(**objectstack-platform** § Customizing an installed package): it is armed in the -base's place, keeps the base's name and its one activation switch -(`POST /api/v1/automation/:name/toggle`, `{ enabled: false }` = off for this -deployment), and a run suspended on the old body finishes on that body. An -undeclared same-named flow in the pair or in a dependent is refused at publish. -A flow *beside* it is "new similar": `POST /api/v1/automation/:name/clone` -`{ name, label, package? }` lands the copy switched off in the pair, never -package-less; a flow holding a `secret` / `signingSecret` is refused (`409`): author -it anew. - -A package ships a flow **switched off** with `defaultActive: false` (beside -`status: 'active'`): unarmed (`_status` `enabled: false`) until an administrator -turns that switch on, which then outlives restart, upgrade and reinstall. -`status: 'obsolete'` disarms past the switch; a flow authored in the deployment -is refused the key (its switch is `status`). +| Each flow type's use, control-flow nodes, an installed package's flow, and the rest of each section below | [examples-flows.md](./references/examples-flows.md) | +| Triggers (record change, schedule, date sweep, inbound webhook), `requires` capabilities | [Triggers](./references/examples-flows.md#triggers--event-driven-automation) | +| Routing a new record to a queue or a person | [Assignment rules](./references/examples-flows.md#assignment-rules) | +| An approval, a send-back, an escalation, a state machine | [state-machines-and-approvals.md](./references/state-machines-and-approvals.md) — its state-introspection route is `GET /api/v1/meta/object/:name/state/:field?from=:state` | +| A vendor integration or callback | [integration-recipes.md](./references/integration-recipes.md) | -### Flow Node Types +## Flows + +**In a project a flow is `defineFlow({ … })` in a `*.flow.ts`**; a JSON block +is that literal. Its `type`: `autolaunched` (no user interaction: started by +events, APIs or other flows), `screen`, `record_change`, `api` (inbound +webhook), or `type: 'schedule'`: a cron / interval cadence on the **start +node's `config.schedule`**, or a per-record date sweep (`config.timeRelative`). -Built-in (plugins register more; a `type` none runs is refused at a server's publish, `flow-node-type-no-executor`): +`variables` is an **array**; a variable has no `label`: `variables: [{ name: 'case_id', +type: 'text', isInput: true }, { name: 'approval_result', type: 'boolean', isOutput: true }]`. -#### Control Flow +**A trigger is the start node's `config`**; there is no top-level `trigger`, +`event` or `schedule` key. A record change: +`{ objectName: 'support_case', triggerType: 'record-after-update', condition: "previous.status != 'escalated' && record.status == 'escalated'" }`. +Guard a flow that writes its own object, or +it re-triggers itself. `defineStack({ requires })` +lists `automation` and `triggers`. -| Node | Purpose | -|:--|:--| -| `start` | Entry point: exactly one per flow | -| `end` | Exit point: one or more | -| `decision` | Branch by **edge `condition` predicates**, not node config | -| `loop` | Iterate a **nested `config.body` region** once per item of `config.collection` — a CEL value envelope or an inline list, never a string; `iteratorVariable` (default `item`) and optional `indexVariable` bind inside it, `maxIterations` caps it | -| `parallel` | Fan out into `config.branches[]` (≥ 2 regions) run concurrently, **joined implicitly** at block end | -| `try_catch` | Run `config.try`; on failure run `config.catch` with the error in `errorVariable` (default `$error`); `config.retry` re-runs `try` with backoff first; in a `record-after-*` flow it (or `errorHandling.strategy: 'retry'`) may not reach an inline `http` / `connector_action`: the save would wait out every attempt. Inside a `subflow` / `map` child, retried by either flow, that is **silent**: the flow saves but never arms (`GET /api/v1/automation/_status`: `bound: false`, `unboundCause: retried_callout_in_subflow`) until the child's `http` is `durable: true` or nothing retries the call. **No `finally`** — the container's ordinary out-edges are the continuation | -| `map` | Sequential multi-instance — invoke the `config.flowName` flow (named as `subflow`'s) per item of `config.collection` (shaped as `loop`'s); each may pause (batch approvals); a refused name fails it at the first item | -| `wait` | Pause for a timer or a named signal | -| `subflow` | Invoke the flow bare `config.flowName` names: a package's flow gets its own, else the one holder in its `dependencies` closure plus `sys`; a package-less flow, the environment's, else the one package holder. Else the node fails at run time (`subflow 'X' failed: …` naming every candidate; no `code`): `outside-closure` — held only by an undeclared package (declare it) or the environment; `ambiguous-in-closure` / `ambiguous-in-environment` — two packages hold it (package / package-less caller). `os validate` warns `flow-subflow-unknown` on any name this stack lacks, a correct cross-package call included | -| `parallel_gateway` / `join_gateway` / `boundary_event` | BPMN-interop forms a `parallel` / `try_catch` container lowers into; author the container | +### Flow Node Types + +Control flow and every node's `config`: +[Flow Node Types](./references/examples-flows.md#flow-node-types). A human +sign-off is an `approval` node (`type: 'approval'`). #### Data Operations @@ -96,31 +88,21 @@ Built-in (plugins register more; a `type` none runs is refused at a server's pub | Node | Purpose | |:--|:--| -| `http` | Call an HTTP API — set `timeoutMs`, or it has no timeout and warns (`flow-http-timeout-missing`). `url` and `headers` are served as written with the definition to every member who can read flows — only `signingSecret` and a start node's `secret` are withheld — so never a credential there: use a declared connector via `connector_action`. Retried after a record change: `durable: true` (outbox-queued, else sent once in the background, unretried; no response) | +| `http` | Call an HTTP API. Set `timeoutMs`. `url` and `headers` are served to every member who can read flows: never a credential there, use a declared connector. Retried after a record change: `durable: true` | | `notify` | Send a notification (below) | -| `connector_action` | Dispatch an action of a declared connector (§ *Integrations are declared, not coded*) or a plugin's. `connectorConfig.input` is a value-slot map like `subflow` `input`. Evaluated, it is judged against the action's `inputSchema` (`required`, `type`, `items`, a key outside listed `properties`) before dispatch: a breach fails the step `VALIDATION_ERROR` (`fault`-routable); `os validate` does not judge that fit yet. Retried after a record change: drop the retry, or run the flow on demand / on a schedule | +| `connector_action` | Dispatch an action of a declared connector (§ *Integrations are declared, not coded*). `connectorConfig.input` is a value-slot map, judged against the action's `inputSchema` only at dispatch | | `script` | Call a **registered** function (*Valid-but-silently-wrong* #3) | -| `screen` | Display a UI form (screen flows only). `config.fields[]`: `{ name, label, type, required, options, defaultValue }`, `type` an open widget hint; `'file'` renders the upload widget and resumes with the `sys_file` id bound to `name` — a later `create_record` / `update_record` writes it into a `file` field, which claims the file: collect first, write after the last screen. `'record_link'` (never `'record'`, an object field type) takes no input — it shows the `reference` record whose id `defaultValue` evaluates to, by display name, as a link to its record page: the result screen of a flow that created records, `{ name: 'account_link', type: 'record_link', reference: 'crm_account', defaultValue: { dialect: 'cel', source: 'account.id' } }` over a `create_record` `outputVariable: 'account'`. Both keys required; `required` / `options` / `placeholder` / `min` / `max` refused; a resume value under its name refused (`400 INVALID_SCREEN_INPUT`). A completed `end` `message` is refused and a markdown link in a screen `description` renders literally. Next / Submit and "Step N of M" are not authored: the engine reads the graph when the screen pauses and serves `progress`, which alone labels the button and draws the counter. A `decision`, `fault` edge, loop back, non-screen pause (`approval`, `wait`) or `subflow` after a screen means "Next", no count. `progress` in a node `config` is refused | - -#### Human Decision - -| Node | Purpose | -|:--|:--| -| `approval` | Route a record for human sign-off | +| `screen` | Display a UI form (screen flows only): `config.fields[]`. An upload is `type: 'file'`, a link to a created record `type: 'record_link'`; Next / Submit is never authored | ### `notify` -An undeclared key is a named parse error. **RAW** keys are read as written: -a `{token}` in one is refused. As JSON (TypeScript: the same -literal, a `FlowNode`): +As JSON (TypeScript: the same literal, a `FlowNode`): ```json { "id": "tell_owner", "type": "notify", "label": "Notify Owner", "config": { "recipients": { "dialect": "cel", "source": "record.owner_id" }, "title": "Done: {{ record.title }}", "message": "Closed {{ record.closed_at | date:long }}", - "topic": "task", - "severity": "warning", "channels": ["inbox"], "sourceObject": "task", "sourceId": { "dialect": "cel", "source": "record.id" }, @@ -128,181 +110,72 @@ literal, a `FlowNode`): } } ``` -- `recipients` — REQUIRED: id, list, or envelope; a CSV is ONE id. 4th form - `{ "emailField": "applicant_email" }`: an `email` field of the trigger record, - for a non-user — then `channels: 'email'` alone. An envelope must yield USER - ids: an address no user holds fails the node. -- `title` — inline; XOR `template` (RAW, localizable). `message` — body; only - with inline `title`. -- RAW: `topic` (default `'notify'`), `severity` (CLOSED enum - `info` | `warning` | `critical`), `channels` (default inbox). -- `sourceObject` + `sourceId` — the link: a PAIR, else dropped; none of the 3 ⇒ - the trigger record (not on delete/before-create), if any. `actionUrl` - overrides the pair. - -A recipient string, written or evaluated, may be an audience selector: - -- `team:ID` — that team's members. -- `owner_of:OBJECT:ID` — that record's owner; a computed id: `source: "'owner_of:crm_case:' + record.case_id"`. -- `org:members` — every member of the run's organization, else that of the record the notification is about, else nobody (`single` posture: a `schedule` flow declaring no `organization`, no record). Any other `org:` value reaches nobody too. Each warns in the server log only; the node succeeds. +- `recipients` — REQUIRED: id, list, or envelope yielding USER ids. A non-user + is `{ "emailField": "applicant_email" }` with `channels: 'email'` alone; an + audience is a selector string (`team:ID`, `owner_of:OBJECT:ID`, + `org:members`). +- `title` is inline XOR `template`. `sourceObject` + `sourceId` are a PAIR; + with neither and no `actionUrl` the notice links to the trigger record. An option label in a notice: `{{ stage | option:opportunity.stage }}` in the mail `template` (each recipient's language; mail-only, refused in inline `title` / `message`) — never `label()` in `templateData`, evaluated once per run, before fan-out. -### Flow Variables - -`variables` is an **array**; a variable has no `label`: `variables: [{ name: 'case_id', -type: 'text', isInput: true }, { name: 'approval_result', type: 'boolean', isOutput: true }]`. - -→ [references/examples-flows.md](./references/examples-flows.md) § Flow Example — Auto-Escalate Overdue Cases. - ### Failure routing & `runAs` -> **Handling a failed node: a `fault` edge.** `{ source, target, type: 'fault' }` -> routes a failed node to a handler instead of ending the run. **A -> `label: 'error'` alone does nothing:** an ordinary edge -> traverses on SUCCESS (`objectstack validate` reports `flow-error-label-not-fault`). -> A handled failure does not consume the flow-level retry -> (`errorHandling.strategy: 'retry'`), which replays from the start — prefer a fault edge for a local failure. The handler -> reads `{{ .error }}` (run-wide `{{ $error.message }}`; in CEL, -> `vars["$error"]`); the run then reports success and the failed step stays in the trace. - -| ROUTES (runtime failure) | Does NOT route (fatal either way) | -|:--|:--| -| 404, rate-limit, rejected write, failed subflow | missing required config key (`objectName`, `url`, `flowName`, `connectorId`/`actionId`); filter operand that evaluated to `null` or a non-value; graph past the nesting ceiling; unscoped run | - -> **Writing a `readonly` field? Set `runAs: 'system'`** (approval stamps, SLA -> markers, rollups). Under the default -> `runAs: 'user'` the engine **strips** it from `create_record` / `update_record` -> — the step succeeds, the drop is named in the step's -> warnings; `os validate` / `os build` fail a `runAs:'user'` -> `update_record` writing one (`readonlyWhen`: a warning). -> A button, an action, an endpoint or the trigger route does not let a user -> start an `autolaunched`, `record_change` or `schedule` flow declared -> `runAs: 'system'` (403 `PERMISSION_DENIED`), so for a flow a user starts from a -> button the elevated routes are a `screen` or `api` flow declared -> `runAs: 'system'`, or a user-run flow whose `subflow` node calls the elevated flow. - -> **Elevate the write, not the flow.** Prefer the `subflow` route — raising a -> whole `screen` flow silently elevates every other write in it, and an `api` -> flow adds a webhook secret and an inbound endpoint a button never uses. -> -> **Elevation stops at identity assignment.** A `runAs: 'system'` write (insert -> through purge) of `sys_user_position`, `sys_user_permission_set`, -> `sys_invitation` or `sys_member` is refused `PERMISSION_DENIED`, a system -> subflow included. Grant positions and permission sets from a `runAs: 'user'` -> flow — the delegated-administration gate judges that user and records them as -> `granted_by`; invitations and memberships change through the organization -> endpoints (row 1b, https://objectstack.ai/docs/permissions/system-context#1-authorization-and-scoping). -> -> **A `runAs: 'system'` sweep must pin its organization.** System context has no -> trigger user, so a scan or rollup with no organization predicate reads and -> writes across every tenant; filter on the platform-injected tenant column, never -> re-declare it per object. - -> **Who may START a flow: `requiredPermissions: ['…']` on the flow** — the -> four entrances above refuse a non-system caller missing any named capability -> with `403 PERMISSION_DENIED`; an action starting it inherits the list, a -> `subflow` node is not an entrance. Gate an elevated `screen` / `api` flow -> here, never on `current_user.positions` inside it. - -> **A hook elevates itself with `runAs`, never with `sudo`.** An object hook -> (objectstack-data) declares its own `runAs: 'system' | 'user' | 'inherit'` — -> default `'inherit'`, the context of the write that fired it — scoping that -> hook's `ctx.api` data operations only, on the in-process `handler` and the -> sandboxed `body` alike. A `'user'` hook whose trigger resolved no user has -> nothing to scope to: its `ctx.api` data operations are refused -> (`HOOK_UNSCOPED_DATA_ACCESS`, 403) rather than run unscoped. +- **A failed node is routed by a `fault` edge**, `{ source, target, type: 'fault' }`. + A `label: 'error'` alone does nothing: an ordinary edge traverses on SUCCESS. +- **Writing a `readonly` field? Set `runAs: 'system'`.** Under the default + `runAs: 'user'` the engine **strips** it and the step succeeds. A button + cannot start a `runAs: 'system'` `autolaunched`, `record_change` or + `schedule` flow: elevate the write, not the flow, through a `subflow` + node. +- **Elevation stops at identity assignment**: a `runAs: 'system'` write of + `sys_user_position`, `sys_user_permission_set`, `sys_invitation` or + `sys_member` is refused `PERMISSION_DENIED`: grant from a `runAs: 'user'` + flow. +- **A `runAs: 'system'` sweep must pin its organization**, or it reads and + writes across every tenant. +- **Who may START a flow: `requiredPermissions: ['…']` on the flow.** Gate an + elevated `screen` / `api` flow here, never on `current_user.positions` + inside it. ### Filter operands (`config.filter`) -- **Each operand is a value slot**, evaluated - before the query. - A whole-string **query placeholder** (`{current_user_id}`, `{today}`, - `{current_year_start}`) passes through verbatim for the query engine; a flow - variable never shadows it, and only `filter` gets this hand-off. -- **An operand that evaluates to `null` refuses the node**: a dropped condition - does not narrow a query, it widens it, so a routed `delete_record` would empty - the object while the run reports success. Where the value may be absent, - route around the node with a `decision`; to match an empty field, write the - literal `null`. A relation hop (`record.owner.email`) needs the start node's - `config.expand` to list the field — else the fault names the missing hop, not - the remedy. -- **A computed operand is a value, never a query operator**: a string, number, - bigint, boolean or date, or at an `$in` / `$nin` / `$between` comparand a list - of them with no empty entry. Anything else fails the node as a guard. - Make the expression evaluate to the compared value (for a record, - its `id`), and write conditions in the filter itself. - ---- +Each operand is a value slot, evaluated before the query; a whole-string query +placeholder (`{today}`) passes through verbatim. **An +operand that evaluates to `null` refuses the node** (a dropped condition +widens a query). Route around the node with a `decision`; to match an empty +field, write the literal `null`. A computed operand is a value, never a query +operator. ## Valid-but-silently-wrong (passes build, fails at runtime) Most are caught by `objectstack build`: 1. **A value slot takes a literal or a CEL envelope — never a `{…}` token.** - In `assignments.*`, `fields.*`, `subflow` / `map` `input.*`, `script` - `inputs.*`, `loop` / `map` `collection`, notify `recipients` / - `templateData.*` / `sourceId`, `http` `body` and every CRUD `filter` - operand, a string is the literal text it spells, and a `{…}` token is - **refused** — at `objectstack validate` (`expression-invalid`), - `registerFlow` and the executor — naming its CEL spelling. Compute with - `{ dialect: 'cel', source: '…' }`: - - `'{record.owner}'` → `source: 'has(record.owner) ? record.owner : null'` — - CEL refuses an absent key where the template wrote nothing, so nothing / - `null` / a default is now YOUR call; `'{record.tags.0}'` → `'record.tags[0]'`; - a deep path guards each step: `has(vars.source) && has(vars.source.id) ? vars.source.id : null` - - run user: `{$User.Id}` → `current_user.id`; a flow that can run without a - user guards it, `current_user != null ? current_user.id : null`. - `current_user` holds `id`, `positions`, `organizationId`, `isPlatformAdmin` - only — an email or a name is a `sys_user` read by that id - - Text slots (notify `title` / `message` / `actionUrl`, screen `title` / - `description`, end `message`, `http` `url` / `headers`) render `{{ }}` - holes — a variable path, optional formatter (a `default:` argument is - literal text, never a path), no logic; a `{…}` token there - is refused with its `{{ }}` spelling. A date or the run user has no hole: - assign it first (`assignments: { v: { dialect: 'cel', source: - 'current_user.id' } }`), then write `{{ v }}`. - `create_record` / `update_record` `fields` also take a text slot, marked - `{ dialect: 'template', source }`, for a sentence people read. It is written - in the organization's language (Localization setting if set, else - `i18n.defaultLocale`; key: **objectstack-i18n**), never the run starter's; - untranslated, the authored text; an unreadable setting fails the node. A - bare string stays a literal, never translated. - + In `assignments.*`, `fields.*`, `input.*`, `inputs.*`, `collection`, notify + `recipients`, `http` `body` and every `filter` operand a string is the + literal text it spells, and a `{…}` token is **refused** — at + `objectstack validate` (`expression-invalid`), `registerFlow` and the + executor — naming its CEL spelling. Compute with + `{ dialect: 'cel', source: '…' }`: a field that may be empty is + `source: 'has(record.owner) ? record.owner : null'`, the run user + `current_user.id`. Text slots (notify `title` / `message`, `http` `url`) + render `{{ }}` holes. 2. **`create_record`'s `outputVariable` holds the created RECORD, not its id.** - ❌ `fields: { ref: { dialect: 'cel', source: 'newRec' } }` ✅ `source: 'newRec.id'` - -3. **`script` nodes call a registered function — nothing else.** `config.function` - (**required**: an empty node refuses at execute, an unregistered name fails - loudly) names one registered in `defineStack({ functions })`. - - **The name resolves from the flow's package, as `subflow`'s `flowName` - does**, the platform's ownerless function in every flow's reach; a - `.custom` override reads as a package-less flow. Packages of two - `namespace`s each run their own `normalize_phone`. One namespace (or - none): both held at boot warn `Bare-name conflict at boot`; a later one - installs but binds NONE of its functions or hooks (error `Failed to bind - declarative hooks`): rename, or another namespace. If the flow's package - holds none, two holders in reach or one only outside its `dependencies` - closure fail the step as a guard (no `fault` edge; `$error.code: - 'RESOURCE_CONFLICT'` in a `try_catch`); a flow door's `innerRefusal` names - each holder. Fix: declare the dependency, or rename. - - **A flow `function` is a PURE compute step — it does NOT read/write the - database.** It receives `ctx.input` and **returns** a value; a later - **declarative** node persists its `outputVariable`: +3. **`script` nodes call a registered function — nothing else.** + `config.function` names one registered in `defineStack({ functions })`: a + PURE compute step that receives `ctx.input` and **returns** a value. A + later **declarative** node persists its `outputVariable`: ```json [ { "id": "ai", "type": "script", "label": "AI Triage", "config": { - "function": "helpdesk.aiTriageStub", - "inputs": { "ticketId": { "dialect": "cel", "source": "record.id" } }, - "outputVariable": "ai" } }, + "function": "helpdesk.aiTriageStub", "outputVariable": "ai", + "inputs": { "ticketId": { "dialect": "cel", "source": "record.id" } } } }, { "id": "apply", "type": "update_record", "label": "Apply Category", "config": { "objectName": "helpdesk_ticket", "filter": { "id": { "dialect": "cel", "source": "record.id" } }, @@ -310,171 +183,33 @@ Most are caught by `objectstack build`: ] ``` - A function that writes where the platform cannot see **declares** it, so the - run reports "cannot say" rather than `acted: 0` (project code — a function - has no JSON form): + A function that writes where the platform cannot see declares it (project + code, no JSON form): ```ts - defineStack({ functions: { - 'billing.sync': { handler: syncBilling, effect: 'writes' }, - } }); + defineStack({ functions: { 'billing.sync': { handler: syncBilling, effect: 'writes' } } }); ``` -4. **A `select` is compared and written by its option `value`, never its label.** - The request says "Lost"; the row stores `lost`. - A start or edge `condition: "record.status == 'Lost'"`, or `filter` / - `fields: { status: 'Lost' }`, is refused at publish (inline options), else - matches no row or fails the run (`invalid_option`); a filter for rows still - holding the label takes a CEL envelope operand. Read the field's `options`. +4. **A `select` is compared and written by its option `value`, never its + label.** A label is refused at publish (inline options), else it matches + no row or fails the run. ---- +## Assignment rules -→ State Machines & Approvals: [references/state-machines-and-approvals.md](./references/state-machines-and-approvals.md) — its state-introspection route is `GET /api/v1/meta/object/:name/state/:field?from=:state`. +Routing a new record to a queue or a person is a stack `assignmentRules` +entry, ⛔ never a `beforeInsert` hook that picks an owner, nor a round-robin +counter field: ---- - -## Assignment rules — route a new record to a queue or a person - -`assignmentRules` on the stack routes each inserted -row of an `ownership: 'user'` object whose `owner_id` and `queue` are both still -empty — once, after every `beforeInsert` hook, never on update, never refusing the -insert. Entries are ordered; the first whose `criteria` (CEL over -`record.*`) match decides: - - -```typescript -import { defineAssignmentRule } from '@objectstack/spec/automation'; - -export const caseIntake = defineAssignmentRule({ - name: 'crm_case_intake', - object: 'crm_case', - entries: [ - { name: 'urgent', criteria: 'record.priority == "urgent"', - assignTo: { type: 'queue', value: 'crm_escalations' } }, // no strategy: parked for a claim - { name: 'rest', assignTo: { type: 'queue', value: 'crm_support_intake' }, - strategy: 'least_loaded', load: 'record.status != "closed"' }, // or 'round_robin'; `load` only with least_loaded - ], -}); -``` +`defineAssignmentRule({ name: 'crm_case_intake', object: 'crm_case', entries: [{ name: 'rest', assignTo: { type: 'queue', value: 'crm_support_intake' }, strategy: 'round_robin' }] })` -`strategy` is for a queue target only; `assignTo: { type: 'user', value: '' }` -names one owner, who holds the row only while an active member of its organization -(else ownerless). Queues are declared in `queues` (objectstack-data); an approval -for the same people is a `queue` approver ([Approver Types](./references/state-machines-and-approvals.md#approver-types)). -⛔ Never a `beforeInsert` hook that picks an owner, nor a round-robin counter field. - -**A packaged rule's queue** is its package's own, else the one holder -in its `dependencies` closure plus `sys`: `acme.helpdesk` naming `acme.crm`'s queue -declares `dependencies: { 'acme.crm': '^1.0.0' }`. Else refused — `outside-closure` -(an undeclared package's or environment-only queue), `ambiguous-in-closure` (two -in it) — the row is written ownerless, in no queue, and the server log warns once -(`… does not resolve … from the rule's package`). An organization's -`sys_assignment_rule` row and a rule no package ships read environment-wide (two -package holders: `ambiguous-in-environment`). A name no `queues` entry declares -reads the organization's `sys_queue` row. - ---- - -## Triggers — Event-Driven Automation - -There is **no standalone trigger -object and no top-level `trigger` / `event` key**. - -### Prerequisite — declare the capabilities your nodes need - -Metadata registers without its `defineStack({ requires })` token. Two pairs are -instead **refused** at `os validate` / `build` / `dev` / `serve` (422); neither -token implies the other: - -| `requires` token | Turns on | Absent ⇒ | -|:--|:--|:--| -| `automation` | the flow engine + node executors | flows never execute | -| `triggers` + `automation` | `record-*` / schedule / `api` start bindings | auto-launched flow refused: `STACK_TRIGGER_CAPABILITY_REQUIRED` | -| `job`° | cron cadence + the `timeRelative` sweep | scheduled flows never launch | -| `queue`° | the inbound-webhook consumer | inbound POST answers **503** | -| `approvals` | `approval` / `approval_revise` (`plugin-approvals`) | no executor for the node type | -| `messaging`° | `notify` delivery to inbox (`sys_inbox_message`) | **silent:** success with `skipped: true` | -| `webhooks` + `realtime` | `defineStack({ webhooks })` outbound dispatch | declared webhook refused: `STACK_WEBHOOK_CAPABILITY_REQUIRED` | - -° Always-on, so list it only under `--preset minimal` (**objectstack-platform** § `requires:`). - -### Inbound webhook (`api`) triggers (ADR-0041 Tier 1) - -`POST /api/v1/automation/hooks/:flowName/:hookId`, configured on the -**start node `config`**: - -| `config` key | Purpose | -|:--|:--| -| `hookId` | URL path token (default `'default'`). **Rotate it to revoke** a leaked endpoint | -| `secretRef` / `secret` | HMAC-SHA256 secret, **one required** (else refused at registration and `os validate`). Ship `secretRef: 'NAME'`: an env var the deployment fills, not `OS_*`; unfilled ⇒ `503`. Never a literal | - -- **Signature:** `x-objectstack-signature: t=,v1=` — HMAC of `.`; `t` within 300 s. Vendor-signed: `config.signature` replaces it (recipe 4). -- **Idempotency:** `x-idempotency-key` dedupes retries — delivery is at-least-once: author the flow idempotent. -- **Queue-backed:** it ACKs `202` and enqueues; the flow runs on the consumer. -- The JSON body is the flow's trigger record (`record.*` / bare fields) plus `params`. -- **A flow name two packages hold:** the bare hook answers `401 INVALID_SIGNATURE` whatever the signature (cause: server log only). Each package's flow answers only at `…/hooks/:namespace/:flowName/:hookId`, by its `manifest.namespace` (`_env`: a flow no package ships). -- **A disabled package's flow:** that `401` at both addresses, nothing enqueued; once enabled, a sender's retry gets `202`. - -### Trigger Types (start-node `config.triggerType`) - -| `triggerType` | ObjectQL hook | -|:--|:--| -| `record-before-create` (can modify/reject) | `beforeInsert` | -| `record-after-create` | `afterInsert` | -| `record-before-update` | `beforeUpdate` | -| `record-after-update` | `afterUpdate` | -| `record-before-delete` | `beforeDelete` | -| `record-after-delete` | `afterDelete` | -| `record-before-write` / `record-after-write` — one flow, both events | insert + update hooks | - -### Trigger Configuration — on the `start` node - -```typescript -{ - id: 'start', - type: 'start', - label: 'On Case Escalated', - config: { - objectName: 'support_case', - triggerType: 'record-after-update', - condition: "previous.status != 'escalated' && record.status == 'escalated'", - }, -} -``` - -> **Prefer `record-after-*`**; **guard** one that writes its own object, or it re-triggers itself. A -> `record-before-*` flow that throws silently blocks the write — give it a -> user-facing message. - -→ [references/examples-flows.md](./references/examples-flows.md) § Time-relative triggers. - ---- +It routes each inserted row whose `owner_id` and `queue` are both still empty, +once, never on update. An approval for the same people is an `approval` node +with `approvers: [{ type: 'queue', value: 'crm_support_leads' }]`. ## Integrations are declared, not coded -A vendor system reachable over HTTP is a -`connectors:` entry inside the app — `provider: 'openapi' | 'mcp' | 'rest'`, a -packaged spec, `auth.credentialRef` (the customer's administrator supplies the -value) — dispatched by `connector_action`. Never a plugin. Recipes, -credential hand-off, loader limits: [references/integration-recipes.md](./references/integration-recipes.md). -Platform code only when one holds — and then it is the platform's, filed as a -card, the app still writing none: the protocol is not HTTP; the work writes -identity objects (users, units, positions); it processes files locally; one fixed -action contract spans several vendors; the callback is signed in no form -`config.signature` declares. A document the loader cannot take yet (YAML, Swagger 2.0, -`$ref`) is a gap named against its platform card. - ---- - -## Verify your work - -`os validate` (`os build` also emits `dist/`); CEL checks: **objectstack-formula** -§ Verify your work. - ---- - -## References - -See [references/_index.md](./references/_index.md) for pointers to the Zod -schemas in `node_modules/@objectstack/spec/src/`. - +A vendor system reachable over HTTP is a `connectors:` entry inside the app +(`provider: 'openapi' | 'mcp' | 'rest'`, a packaged spec, +`auth.credentialRef`), dispatched by `connector_action`. Never a plugin. +Recipes, credential hand-off, loader limits and the few cases that are +platform code: [references/integration-recipes.md](./references/integration-recipes.md). diff --git a/.claude/skills/objectstack-automation/evals/flows-triggers-approvals.json b/.claude/skills/objectstack-automation/evals/flows-triggers-approvals.json index 242d43f..fa02662 100644 --- a/.claude/skills/objectstack-automation/evals/flows-triggers-approvals.json +++ b/.claude/skills/objectstack-automation/evals/flows-triggers-approvals.json @@ -16,7 +16,7 @@ ], "must_not_contain": [ "next:", - "values:", + "values: {", "cron`" ] } diff --git a/.claude/skills/objectstack-automation/references/examples-flows.md b/.claude/skills/objectstack-automation/references/examples-flows.md index 335d57b..fa54e1e 100644 --- a/.claude/skills/objectstack-automation/references/examples-flows.md +++ b/.claude/skills/objectstack-automation/references/examples-flows.md @@ -1,4 +1,291 @@ -# Automation — long flow examples +# Automation — flows, triggers and assignment rules + +> **Predicates and conditions are CEL** — every `condition` / `guard` / +> `entryCondition` / filter `value` is an **Expression** envelope: a plain CEL +> string, or the `P\`...\`` / `cel\`...\`` tag (author-time validation); pick one +> per file. + +## Flow Types + +| Type | When to Use | +|:--|:--| +| `autolaunched` | No user interaction: started by events, APIs or other flows | +| `screen` | Shows UI screens | +| `schedule` | Runs on a cron/interval cadence declared on the **start node's `config.schedule`**, or a **per-record date sweep** via `config.timeRelative` | +| `record_change` | Fires on record create/update/delete. `autolaunched` + the same `record-*` binding behaves identically; `record_change` also opts into the trigger-readiness lint | +| `api` | Inbound **webhook** (*Inbound webhook triggers*); a flow only ever started explicitly is `autolaunched` | + +**A stepped form over one object that never branches** is no flow: an **objectstack-ui** named form view (`type: 'wizard'`) a `type: 'form'` action opens. + +## A flow an installed package ships + +It is read-only. To change what it does, save +a same-named flow in the base's paired `.custom` package declaring +`overrides: { package: '', basedOn: '' }` +(**objectstack-platform** § Customizing an installed package): it is armed in the +base's place, keeps the base's name and its one activation switch +(`POST /api/v1/automation/:name/toggle`, `{ enabled: false }` = off for this +deployment), and a run suspended on the old body finishes on that body. An +undeclared same-named flow in the pair or in a dependent is refused at publish. +A flow *beside* it is "new similar": `POST /api/v1/automation/:name/clone` +`{ name, label, package? }` lands the copy switched off in the pair, never +package-less; a flow holding a `secret` / `signingSecret` is refused (`409`): author +it anew. + +A package ships a flow **switched off** with `defaultActive: false` (beside +`status: 'active'`): unarmed (`_status` `enabled: false`) until an administrator +turns that switch on, which then outlives restart, upgrade and reinstall. +`status: 'obsolete'` disarms past the switch; a flow authored in the deployment +is refused the key (its switch is `status`). + +## Flow Node Types + +Built-in (plugins register more; a `type` none runs is refused at a server's publish, `flow-node-type-no-executor`): + +### Control Flow + +| Node | Purpose | +|:--|:--| +| `start` | Entry point: exactly one per flow | +| `end` | Exit point: one or more | +| `decision` | Branch by **edge `condition` predicates**, not node config | +| `loop` | Iterate a **nested `config.body` region** once per item of `config.collection` — a CEL value envelope or an inline list, never a string; `iteratorVariable` (default `item`) and optional `indexVariable` bind inside it, `maxIterations` caps it | +| `parallel` | Fan out into `config.branches[]` (≥ 2 regions) run concurrently, **joined implicitly** at block end | +| `try_catch` | Run `config.try`; on failure run `config.catch` with the error in `errorVariable` (default `$error`); `config.retry` re-runs `try` with backoff first; in a `record-after-*` flow it (or `errorHandling.strategy: 'retry'`) may not reach an inline `http` / `connector_action`: the save would wait out every attempt. Inside a `subflow` / `map` child, retried by either flow, that is **silent**: the flow saves but never arms (`GET /api/v1/automation/_status`: `bound: false`, `unboundCause: retried_callout_in_subflow`) until the child's `http` is `durable: true` or nothing retries the call. **No `finally`** — the container's ordinary out-edges are the continuation | +| `map` | Sequential multi-instance — invoke the `config.flowName` flow (named as `subflow`'s) per item of `config.collection` (shaped as `loop`'s); each may pause (batch approvals); a refused name fails it at the first item | +| `wait` | Pause for a timer or a named signal | +| `subflow` | Invoke the flow bare `config.flowName` names: a package's flow gets its own, else the one holder in its `dependencies` closure plus `sys`; a package-less flow, the environment's, else the one package holder. Else the node fails at run time (`subflow 'X' failed: …` naming every candidate; no `code`): `outside-closure` — held only by an undeclared package (declare it) or the environment; `ambiguous-in-closure` / `ambiguous-in-environment` — two packages hold it (package / package-less caller). `os validate` warns `flow-subflow-unknown` on any name this stack lacks, a correct cross-package call included | +| `parallel_gateway` / `join_gateway` / `boundary_event` | BPMN-interop forms a `parallel` / `try_catch` container lowers into; author the container | + +### External Integration — the rest + +| Node | Beyond its `SKILL.md` row | +|:--|:--| +| `http` | Without `timeoutMs` it has no timeout and warns (`flow-http-timeout-missing`). `url` and `headers` are served as written with the definition — only `signingSecret` and a start node's `secret` are withheld. `durable: true` is outbox-queued, else sent once in the background, unretried; no response | +| `connector_action` | A declared connector's action or a plugin's. `connectorConfig.input` is a value-slot map like `subflow` `input`. Evaluated, it is judged against the action's `inputSchema` (`required`, `type`, `items`, a key outside listed `properties`) before dispatch: a breach fails the step `VALIDATION_ERROR` (`fault`-routable); `os validate` does not judge that fit yet. Retried after a record change: drop the retry, or run the flow on demand / on a schedule | +| `screen` | `config.fields[]`: `{ name, label, type, required, options, defaultValue }`, `type` an open widget hint; `'file'` renders the upload widget and resumes with the `sys_file` id bound to `name` — a later `create_record` / `update_record` writes it into a `file` field, which claims the file: collect first, write after the last screen. `'record_link'` (never `'record'`, an object field type) takes no input — it shows the `reference` record whose id `defaultValue` evaluates to, by display name, as a link to its record page: the result screen of a flow that created records, `{ name: 'account_link', type: 'record_link', reference: 'crm_account', defaultValue: { dialect: 'cel', source: 'account.id' } }` over a `create_record` `outputVariable: 'account'`. Both keys required; `required` / `options` / `placeholder` / `min` / `max` refused; a resume value under its name refused (`400 INVALID_SCREEN_INPUT`). A completed `end` `message` is refused and a markdown link in a screen `description` renders literally. Next / Submit and "Step N of M" are not authored: the engine reads the graph when the screen pauses and serves `progress`, which alone labels the button and draws the counter. A `decision`, `fault` edge, loop back, non-screen pause (`approval`, `wait`) or `subflow` after a screen means "Next", no count. `progress` in a node `config` is refused | + +`approval` routes a record for human sign-off: +[state-machines-and-approvals.md](./state-machines-and-approvals.md). + +## `notify` — the rest + +An undeclared key is a named parse error. **RAW** keys are read as written: +a `{token}` in one is refused. + +- `recipients` — a CSV is ONE id. `emailField` names an `email` field of the + trigger record. An envelope yielding an address no user holds fails the node. +- `template` is RAW and localizable. `message` — body; only with inline `title`. +- RAW: `topic` (default `'notify'`), `severity` (CLOSED enum + `info` | `warning` | `critical`), `channels` (default inbox). +- `sourceObject` + `sourceId` — one without the other is dropped. The trigger + record is the link only when there is one (not on delete/before-create). + `actionUrl` overrides the pair. + +A recipient string, written or evaluated, may be an audience selector: + +- `team:ID` — that team's members. +- `owner_of:OBJECT:ID` — that record's owner; a computed id: `source: "'owner_of:crm_case:' + record.case_id"`. +- `org:members` — every member of the run's organization, else that of the record the notification is about, else nobody (`single` posture: a `schedule` flow declaring no `organization`, no record). Any other `org:` value reaches nobody too. Each warns in the server log only; the node succeeds. + +## Failure routing & `runAs` — the rest + +> **A `fault` edge**: `objectstack validate` reports an `error`-labelled +> ordinary edge (`flow-error-label-not-fault`). A handled failure does not consume the +> flow-level retry (`errorHandling.strategy: 'retry'`), which replays from the +> start — prefer a fault edge for a local failure. The handler reads +> `{{ .error }}` (run-wide `{{ $error.message }}`; in CEL, +> `vars["$error"]`); the run then reports success and the failed step stays in +> the trace. + +| ROUTES (runtime failure) | Does NOT route (fatal either way) | +|:--|:--| +| 404, rate-limit, rejected write, failed subflow | missing required config key (`objectName`, `url`, `flowName`, `connectorId`/`actionId`); filter operand that evaluated to `null` or a non-value; graph past the nesting ceiling; unscoped run | + +> **A `readonly` field** (approval stamps, SLA markers, rollups): the strip from +> `create_record` / `update_record` is named in the step's warnings; +> `os validate` / `os build` fail a `runAs:'user'` `update_record` writing one +> (`readonlyWhen`: a warning). A button, an action, an endpoint or the trigger +> route does not let a user start an `autolaunched`, `record_change` or +> `schedule` flow declared `runAs: 'system'` (403 `PERMISSION_DENIED`), so for a +> flow a user starts from a button the elevated routes are a `screen` or `api` +> flow declared `runAs: 'system'`, or a user-run flow whose `subflow` node calls +> the elevated flow. + +> **Elevate the write, not the flow.** Prefer the `subflow` route — raising a +> whole `screen` flow silently elevates every other write in it, and an `api` +> flow adds a webhook secret and an inbound endpoint a button never uses. +> +> **A `runAs: 'system'` identity write** is refused on every operation, insert +> through purge, a system subflow included. Positions and permission sets granted from a +> `runAs: 'user'` flow are judged by the delegated-administration gate as that +> user, who is recorded as `granted_by`; invitations and memberships change +> through the organization endpoints (row 1b, https://objectstack.ai/docs/permissions/system-context#1-authorization-and-scoping). +> +> **A `runAs: 'system'` sweep**: system context has no trigger user; filter on +> the platform-injected tenant column, never re-declare it per object. + +> **`requiredPermissions`**: the four entrances above refuse a non-system caller +> missing any named capability with `403 PERMISSION_DENIED`; an action starting +> the flow inherits the list, a `subflow` node is not an entrance. Gate an +> elevated `screen` / `api` flow here. + +> **A hook elevates itself with `runAs`, never with `sudo`.** An object hook +> (objectstack-data) declares its own `runAs: 'system' | 'user' | 'inherit'` — +> default `'inherit'`, the context of the write that fired it — scoping that +> hook's `ctx.api` data operations only, on the in-process `handler` and the +> sandboxed `body` alike. A `'user'` hook whose trigger resolved no user has +> nothing to scope to: its `ctx.api` data operations are refused +> (`HOOK_UNSCOPED_DATA_ACCESS`, 403) rather than run unscoped. + +## Filter operands — the rest + +- **Query placeholders** (`{current_user_id}`, `{current_year_start}`, …) are handed to the + query engine; a flow variable never shadows one, and only `filter` gets this + hand-off. +- **A `null` operand**: the dropped condition would let a routed `delete_record` + empty the object while the run reports success. A relation hop + (`record.owner.email`) needs the start node's `config.expand` to list the + field — else the fault names the missing hop, not the remedy. +- **A computed operand** is a string, number, bigint, boolean or date, or at an + `$in` / `$nin` / `$between` comparand a list of them with no empty entry. + Anything else fails the node as a guard. Make the expression evaluate to the + compared value (for a record, its `id`), and write conditions in the filter + itself. + +## Value slots and the other silent traps — the rest + +1. **Value slots** also: notify `templateData.*` / `sourceId`; `input.*` is + `subflow` / `map`'s, `inputs.*` `script`'s, `collection` `loop` / `map`'s, + `filter` a CRUD node's. The spellings a refused `{…}` token is given: + - CEL refuses an absent key where the template wrote nothing, so nothing / + `null` / a default is now YOUR call; an indexed path is `'record.tags[0]'`; + a deep path guards each step: `has(vars.source) && has(vars.source.id) ? vars.source.id : null` + - run user: `{$User.Id}` → `current_user.id`; a flow that can run without a + user guards it, `current_user != null ? current_user.id : null`. + `current_user` holds `id`, `positions`, `organizationId`, `isPlatformAdmin` + only — an email or a name is a `sys_user` read by that id + + Text slots also: notify `actionUrl`, screen `title` / `description`, end + `message`, `http` `headers`. A hole is a variable path, optional formatter + (a `default:` argument is literal text, never a path), no logic; a `{…}` token there + is refused with its `{{ }}` spelling. A date or the run user has no hole: + assign it first (`assignments: { v: { dialect: 'cel', source: + 'current_user.id' } }`), then write `{{ v }}`. + `create_record` / `update_record` `fields` also take a text slot, marked + `{ dialect: 'template', source }`, for a sentence people read. It is written + in the organization's language (Localization setting if set, else + `i18n.defaultLocale`; key: **objectstack-i18n**), never the run starter's; + untranslated, the authored text; an unreadable setting fails the node. A + bare string stays a literal, never translated. + +2. **`script`** (item 3). `config.function` is **required**: an empty node refuses at + execute, an unregistered name fails loudly. + + **The name resolves from the flow's package, as `subflow`'s `flowName` + does**, the platform's ownerless function in every flow's reach; a + `.custom` override reads as a package-less flow. Packages of two + `namespace`s each run their own `normalize_phone`. One namespace (or + none): both held at boot warn `Bare-name conflict at boot`; a later one + installs but binds NONE of its functions or hooks (error `Failed to bind + declarative hooks`): rename, or another namespace. If the flow's package + holds none, two holders in reach or one only outside its `dependencies` + closure fail the step as a guard (no `fault` edge; `$error.code: + 'RESOURCE_CONFLICT'` in a `try_catch`); a flow door's `innerRefusal` names + each holder. Fix: declare the dependency, or rename. + + **A flow `function` does NOT read/write the database.** One that writes + where the platform cannot see declares `effect: 'writes'`, so the run + reports "cannot say" rather than `acted: 0`. + +3. **`select`** (item 4). The request says "Lost"; the row stores `lost`. + A start or edge `condition: "record.status == 'Lost'"`, or `filter` / + `fields: { status: 'Lost' }`, is refused at publish (inline options), else + matches no row or fails the run (`invalid_option`); a filter for rows still + holding the label takes a CEL envelope operand. Read the field's `options`. + +## Triggers — Event-Driven Automation + +There is **no standalone trigger +object and no top-level `trigger` / `event` key**. + +### Prerequisite — declare the capabilities your nodes need + +Metadata registers without its `defineStack({ requires })` token. Two pairs are +instead **refused** at `os validate` / `build` / `dev` / `serve` (422); neither +token implies the other: + +| `requires` token | Turns on | Absent ⇒ | +|:--|:--|:--| +| `automation` | the flow engine + node executors | flows never execute | +| `triggers` + `automation` | `record-*` / schedule / `api` start bindings | auto-launched flow refused: `STACK_TRIGGER_CAPABILITY_REQUIRED` | +| `job`° | cron cadence + the `timeRelative` sweep | scheduled flows never launch | +| `queue`° | the inbound-webhook consumer | inbound POST answers **503** | +| `approvals` | `approval` / `approval_revise` (`plugin-approvals`) | no executor for the node type | +| `messaging`° | `notify` delivery to inbox (`sys_inbox_message`) | **silent:** success with `skipped: true` | +| `webhooks` + `realtime` | `defineStack({ webhooks })` outbound dispatch | declared webhook refused: `STACK_WEBHOOK_CAPABILITY_REQUIRED` | + +° Always-on, so list it only under `--preset minimal` (**objectstack-platform** § `requires:`). + +### Trigger Types (start-node `config.triggerType`) + +`record-before-create` (can modify/reject) / `record-after-create` run on the +ObjectQL `beforeInsert` / `afterInsert` hooks, `record-before-update` / +`record-after-update` on `beforeUpdate` / `afterUpdate`, `record-before-delete` +/ `record-after-delete` on `beforeDelete` / `afterDelete`; +`record-before-write` / `record-after-write` are one flow on both the insert +and the update hooks. + +### Trigger Configuration — on the `start` node + +The `config` itself: `SKILL.md` § Flows. + +> **Prefer `record-after-*`.** A `record-before-*` flow that throws silently +> blocks the write — give it a user-facing message. + +An inbound webhook: [integration-recipes.md](./integration-recipes.md#inbound-webhook-api-triggers-adr-0041-tier-1). + +## Assignment rules + +`assignmentRules` on the stack routes each inserted +row of an `ownership: 'user'` object whose `owner_id` and `queue` are both still +empty — once, after every `beforeInsert` hook, never on update, never refusing the +insert. Entries are ordered; the first whose `criteria` (CEL over +`record.*`) match decides: + + +```typescript +import { defineAssignmentRule } from '@objectstack/spec/automation'; + +export const caseIntake = defineAssignmentRule({ + name: 'crm_case_intake', + object: 'crm_case', + entries: [ + { name: 'urgent', criteria: 'record.priority == "urgent"', + assignTo: { type: 'queue', value: 'crm_escalations' } }, // no strategy: parked for a claim + { name: 'rest', assignTo: { type: 'queue', value: 'crm_support_intake' }, + strategy: 'least_loaded', load: 'record.status != "closed"' }, // or 'round_robin'; `load` only with least_loaded + ], +}); +``` + +`strategy` is for a queue target only; `assignTo: { type: 'user', value: '' }` +names one owner, who holds the row only while an active member of its organization +(else ownerless). Queues are declared in `queues` (objectstack-data); an approval +for the same people is a `queue` approver ([Approver Types](./state-machines-and-approvals.md#approver-types)). +⛔ Never a `beforeInsert` hook that picks an owner, nor a round-robin counter field. + +**A packaged rule's queue** is its package's own, else the one holder +in its `dependencies` closure plus `sys`: `acme.helpdesk` naming `acme.crm`'s queue +declares `dependencies: { 'acme.crm': '^1.0.0' }`. Else refused — `outside-closure` +(an undeclared package's or environment-only queue), `ambiguous-in-closure` (two +in it) — the row is written ownerless, in no queue, and the server log warns once +(`… does not resolve … from the rule's package`). An organization's +`sys_assignment_rule` row and a rule no package ships read environment-wide (two +package holders: `ambiguous-in-environment`). A name no `queues` entry declares +reads the organization's `sys_queue` row. + +## Long examples ### Flow Example — Auto-Escalate Overdue Cases @@ -141,5 +428,5 @@ query placeholder such as `{today}` is refused there (`expression-invalid`). For "days remaining" in a message, use `daysBetween(today(), record.end_date)`. `timeRelative` ships in `@objectstack/trigger-schedule` (its `requires` tokens: -SKILL.md § Prerequisite). Full descriptor schema: +§ Prerequisite above). Full descriptor schema: `node_modules/@objectstack/spec/src/automation/time-relative-trigger.zod.ts`. diff --git a/.claude/skills/objectstack-automation/references/integration-recipes.md b/.claude/skills/objectstack-automation/references/integration-recipes.md index 03afc0e..b93ce19 100644 --- a/.claude/skills/objectstack-automation/references/integration-recipes.md +++ b/.claude/skills/objectstack-automation/references/integration-recipes.md @@ -129,7 +129,7 @@ export const CarrierCallback = defineFlow({ ``` `requires: ['automation', 'triggers']`. The sender signs each post -under `CARRIER_HOOK_SECRET` (SKILL.md *Signature* bullet). A vendor signing +under `CARRIER_HOOK_SECRET` (*Signature* bullet below). A vendor signing its own header adds, keyed by that ref, `signature: { signs: 'body', header: 'X-DocuSign-Signature-1', algorithm: 'hmac-sha256', encoding: 'base64' }`. @@ -184,3 +184,29 @@ against the `redirectUri` that `GET …/:name/connection` answers, then connects (no secret for a public client; a reconnect naming no client keeps it). The connection keeps it encrypted; a read shows `client: { source: 'installer', clientId, hasSecret }`. Still never park a short-lived token behind a `bearer` ref. + +## Inbound webhook (`api`) triggers (ADR-0041 Tier 1) + +`POST /api/v1/automation/hooks/:flowName/:hookId`, configured on the +**start node `config`**: + +| `config` key | Purpose | +|:--|:--| +| `hookId` | URL path token (default `'default'`). **Rotate it to revoke** a leaked endpoint | +| `secretRef` / `secret` | HMAC-SHA256 secret, **one required** (else refused at registration and `os validate`). Ship `secretRef: 'NAME'`: an env var the deployment fills, not `OS_*`; unfilled ⇒ `503`. Never a literal | + +- **Signature:** `x-objectstack-signature: t=,v1=` — HMAC of `.`; `t` within 300 s. Vendor-signed: `config.signature` replaces it (recipe 4). +- **Idempotency:** `x-idempotency-key` dedupes retries — delivery is at-least-once: author the flow idempotent. +- **Queue-backed:** it ACKs `202` and enqueues; the flow runs on the consumer. +- The JSON body is the flow's trigger record (`record.*` / bare fields) plus `params`. +- **A flow name two packages hold:** the bare hook answers `401 INVALID_SIGNATURE` whatever the signature (cause: server log only). Each package's flow answers only at `…/hooks/:namespace/:flowName/:hookId`, by its `manifest.namespace` (`_env`: a flow no package ships). +- **A disabled package's flow:** that `401` at both addresses, nothing enqueued; once enabled, a sender's retry gets `202`. + +## When the answer is platform code + +Platform code only when one holds — and then it is the platform's, filed as a +card, the app still writing none: the protocol is not HTTP; the work writes +identity objects (users, units, positions); it processes files locally; one fixed +action contract spans several vendors; the callback is signed in no form +`config.signature` declares. A document the loader cannot take yet (YAML, Swagger 2.0, +`$ref`) is a gap named against its platform card. diff --git a/.claude/skills/objectstack-automation/references/state-machines-and-approvals.md b/.claude/skills/objectstack-automation/references/state-machines-and-approvals.md index 9bd8ab2..a9d0ee5 100644 --- a/.claude/skills/objectstack-automation/references/state-machines-and-approvals.md +++ b/.claude/skills/objectstack-automation/references/state-machines-and-approvals.md @@ -222,11 +222,11 @@ an id that does not exist gets. | `department` | A department + all descendant departments | | `manager` | The submitter's manager (`sys_user.manager_id`) | | `field` | User id read from a record field (`value` = field name). Resolved against the record's **live** state at node entry, so a field written mid-flow routes correctly; a multi-select user field fans out into one approver per user | -| `queue` | Members of ownership queue `value` at node entry; an empty queue adds nobody. In a packaged flow, see below | +| `queue` | Members of ownership queue `value` at node entry; an empty queue adds nobody. A packaged flow: below | | `expression` | A **CEL expression** resolved at node entry (`value` = the expression string) — see **Dynamic approvers** below. The optional `resolveAs: 'user'(default) \| 'department' \| 'position' \| 'team'` re-expands each resolved id through the graph | **A packaged flow's `queue` approver** (ADR-0150 D3) resolves `value` as a -packaged assignment rule does (SKILL.md § Assignment rules), from the package +packaged assignment rule does (examples-flows.md § Assignment rules), from the package whose flow body runs; a disabled package holds none. `acme.deals` naming `acme.crm`'s `crm_finance` declares `dependencies: { 'acme.crm': '^1.0.0' }`. Refused (`outside-closure`, `ambiguous-in-closure`), the node opens no request: @@ -238,7 +238,7 @@ environment-wide (`ambiguous-in-environment`). ### Dynamic approvers (`type: 'expression'`) An `expression` approver computes WHO approves at the moment the node is -entered. Its CEL source sees exactly **three roots** — nothing else: +entered. Its CEL source sees exactly **three roots**: | Root | Meaning | |:-----|:--------| @@ -252,7 +252,7 @@ say which time you mean, `current.x` or `trigger.x`. Result contract: a user-id string, a CSV string, or an array of ids. An **empty** result (present-but-empty field/variable) triggers `onEmptyApprovers`. A **missing** key (`vars.never_written`) is a loud error, never a silent empty -slate — guard genuinely-optional inputs explicitly, e.g. +slate — guard optional inputs, e.g. `has(vars.picked) ? vars.picked : []`. ```typescript @@ -370,19 +370,19 @@ These are wired on the **graph**, not in node config: the record and its `master_detail` child rows only: a `lookup` child shown in the record's details (`relatedList: 'primary'`) stays editable (warning `approval-detail-editable-while-pending`). Deleting the pending record - still lands, cancelling the request and cascading its `master_detail` rows; - it is refused (`409 RECORD_LOCKED`) where the cascade lacks one transaction - or the child object declares a second cascading relation. + still lands, cancelling the request and its parked run — neither `approve` + nor `reject` runs, so a delete-time action goes in the record's delete + hook — and cascading its `master_detail` rows; it is refused + (`409 RECORD_LOCKED`) where the cascade lacks one transaction or the child + declares a second cascading relation. 3. **Notify the submitter from downstream nodes** wired to the `approve` / `reject` edges. Opening already tells each resolved approver - (`approval.requested`); ⛔ no `notify` node for the opening: it tells - them twice. + (`approval.requested`): ⛔ a `notify` node there tells them twice. 4. **A flow reacting to the mirrored status runs as the person who acted.** The `approvalStatusField` write is elevated but attributed — submit carries - the submitter, approve / reject / recall / send-back the person who decided — - so a `record_change` flow on that field stays `runAs: 'user'` and runs - with the decider's own grants. Only the - two machine-driven transitions carry no user — an SLA `escalation` - auto-decision and the release of a record whose run died — and a - `runAs: 'user'` flow fired by one has its data steps refused: a flow that - must react to those too declares `runAs: 'system'`. + the submitter, approve / reject / recall / send-back the decider — so a + `record_change` flow on that field stays `runAs: 'user'`, with that person's + grants. Only two machine-driven transitions carry no user — an SLA + `escalation` auto-decision and the release of a record whose run died — + and refuse a `runAs: 'user'` flow's data steps: to react to those too, + declare `runAs: 'system'`. diff --git a/.claude/skills/objectstack-data/SKILL.md b/.claude/skills/objectstack-data/SKILL.md index f2e7fd1..e3f1f1b 100644 --- a/.claude/skills/objectstack-data/SKILL.md +++ b/.claude/skills/objectstack-data/SKILL.md @@ -11,48 +11,91 @@ license: Apache-2.0 compatibility: Requires @objectstack/spec 19.x (Zod v4 schemas) metadata: author: objectstack-ai - version: "19.0.0-next.2" + version: "19.0.0-next.3" domain: data tags: object, field, validation, index, relationship, hook, schema, permission, rls, security, seed, fixture --- # Data Modeling — ObjectStack Data Protocol -## Skill Boundaries - -| Need | Use instead | -|:-----|:------------| -| Query, filter, or aggregate records | **objectstack-query** | -| Define REST API endpoints or auth | **objectstack-api** | -| Build views, dashboards, or apps | **objectstack-ui** | -| Create a plugin or register services | **objectstack-platform** | +## First checks + +1. **Version.** Read the installed `@objectstack/spec` + (`node_modules/@objectstack/spec/package.json`); where it differs from this + skill's `compatibility` line, the installed contract is right. +2. **Read what exists.** Read the object being changed, those it references, + and the hooks, seeds and permission sets naming it. Extend what is there: + no second status field, owner field or look-alike object. +3. **Read the type's contract.** [references/_index.md](./references/_index.md) + points at each type's Zod source in `node_modules/@objectstack/spec/src/`. + `Read` it for exact keys, defaults and enum members, never from memory. A running environment serves the parsed shape as JSON Schema + (`GET /api/v1/meta/types`, `entries[].schema`): a defaulted key reads as + required and a bare-string predicate as `{}`. +4. **Verify before reporting done.** `os validate` (`npm run validate` in a + scaffolded project), then `os lint` + ([its rules](./references/lint-rules.md)). Most traps below pass both. + +**Nothing to read yet?** Say so in a line, then still give the whole +definition as code. + +## Traps — each parses, then fails at run time + +1. **A changed field does not reach a database that already has rows.** The + sync only adds: a column is never altered or dropped, and the column wins + at write time. Rename with `renamedFrom: ['old_key']`; `required` is the + write contract, never `NOT NULL` + ([Field Types](./rules/field-types.md#changing-a-field-that-has-data)). +2. **Search reads only this object's own stored columns.** To search by a + related record's title, mirror it into a stored text field in + `searchableFields`, kept fresh by hooks on both objects; a dotted path or a + `formula` there is refused + ([Search Fields](./references/examples-objects.md#search-fields-searchablefields)). +3. **An object you do not own is extended, never redeclared**: + `defineObjectExtension`, relabelling the owner's fields through + `fieldPatches` (redeclared in `fields`, a field is taken over and cut off + from the owner's upgrades). An installed package's object is extended from + its paired `.custom` package, each added field ending in `__c` + ([Object Extension Model](./references/examples-objects.md#object-extension-model)). + +## Where to go + +Open the file for your task first. + +| Authoring | Open first | +|:--|:--| +| An object's other keys, a starter object, field groups, `protection`, an extension | [examples-objects.md](./references/examples-objects.md) | +| A field's type and config, a default, changing a field that has data | [Field Types](./rules/field-types.md) | +| Names; labels in the request's language | [Naming](./rules/naming.md) | +| `lookup` or `master_detail`, junctions, delete behaviour, roll-ups, line items | [Relationships](./rules/relationships.md) | +| Validation rules, state machines, uniqueness, conditional field rules | [Validation](./rules/validation.md) | +| `indexes`, unique scope | [Indexing](./rules/indexing.md) | +| Record hooks: the sandboxed `body`, `ctx.api`, refusals, transactions | [data-hooks.md](./references/data-hooks.md) | +| Permission sets, RLS, field permissions, `secret`, tenancy, ownership queues | [Security](./rules/security.md) | +| Retention, append-only and audit objects, the save notice | [Lifecycle](./rules/lifecycle.md) | +| Seed and demo data: `defineSeed()`, import modes, `externalId`, relationship references, CEL values | [seeds.md](./references/seeds.md) | +| External databases, federated objects | [Datasources](./rules/datasources.md) | ---- +## Conditional Field Rules -## Quick Reference — Detailed Rules +`visibleWhen`, `requiredWhen` and `readonlyWhen` go on the **field**, as CEL +over `record.*` (`P\`record.status == 'paid'\``), so every form and +API write honours them. -- **[Naming Conventions](./rules/naming.md)** -- **[Field Types](./rules/field-types.md)** -- **[Relationships](./rules/relationships.md)** — lookup vs master_detail, junction patterns, delete behaviors -- **[Validation Rules](./rules/validation.md)** — All validation types, script inversion, severity levels -- **[Index Strategy](./rules/indexing.md)** — btree/gin/gist/fulltext, composite indexes -- **[Data Lifecycle & Retention](./rules/lifecycle.md)** — `lifecycle` classes, retention/TTL/rotation/archive policies (not *hooks*); plus the **save notice** a hook hands the saver (`ctx.notice`) -- **[Lifecycle Hooks](./references/data-hooks.md)** — the lifecycle events, the sandboxed `body` (ctx + capability contract; the inline `handler` is deprecated), registration, canonical patterns -- **[Datasources & Federation](./rules/datasources.md)** — `defineDatasource`, external/federated objects (`remoteName`/`columnMap`), auto-connect gating, credentials; ❌ no `field.columnName` on external objects -- **[Security & Access Control](./rules/security.md)** — permission sets, assignment rows, RLS policies, `secret` / `requiredPermissions`, `tenancy`, platform-global posture -- **[Quick-Start Template](./references/examples-objects.md#quick-start-template)** — one complete object: fields, `sharingModel`, `enable`, validations -- **[Metadata Protection](./references/examples-objects.md#metadata-protection-protection)** — the `protection` block that locks shipped metadata against edits and deletes -- **[Seed Data & Fixtures](./references/seeds.md)** — `defineSeed()`, import modes, `externalId`, relationship references, CEL values -- **[Linting & Generation Quality](./references/lint-rules.md)** — the `os lint` data-model rules and severities +- **`readonlyWhen` and `readonly: true` drop the value; they do not refuse the + write**, a declarative action's included. A field that only actions, imports + and the API change is `uiReadonly` + ([Locking a Field](./rules/validation.md#locking-a-field)). +- **`requiredWhen` is a transition gate, not an invariant**: it judges the + write, not the stored row. A fact true of every stored record is a + `validations[]` `script` rule. ---- +Example and syntax: [Validation](./rules/validation.md#conditional-field-rules). ## Core Concepts ### Object Definition -An **Object** maps to a database table and exposes automatic CRUD APIs. As JSON (in TypeScript the -same literal goes inside `ObjectSchema.create({...})`): +As JSON (in TypeScript the same literal goes inside `ObjectSchema.create({...})`): ```json { "name": "crm_account", "label": "Account", "pluralLabel": "Accounts", "icon": "building", @@ -60,413 +103,65 @@ same literal goes inside `ObjectSchema.create({...})`): "fields": { "name": { "type": "text", "label": "Name", "required": true } } } ``` -**Required properties:** - -| Property | Type | Convention | Description | -|:---------|:-------|:-----------|:------------| -| `name` | string | `snake_case` | Immutable machine identifier (`/^[a-z_][a-z0-9_]*$/`) | -| `fields` | map | keys in `snake_case` | Field definitions | -| `sharingModel` | enum | one of the four below | Org-wide default record visibility (OWD). Zod marks it optional, but **a publish with no authored `sharingModel` is refused** with the 422 lint envelope `security-owd-unset`. Author it on every object | - -**`sharingModel` — the four canonical values:** - -| Value | Who can read / write | -|:--|:--| -| `private` | owner only (widen with sharing rules, RLS, or `readScope`/`writeScope`) | -| `public_read` | everyone reads; the owner writes | -| `public_read_write` | everyone reads and writes | -| `controlled_by_parent` | inherited from the master record (`master_detail` children); a row with no (optional) master is its owner's | - -Choose the posture from the request: a business object a team -shares is `public_read_write` (`private` would hide every colleague's records -from everyone else); `private` fits personal or sensitive data only its owner -should see (HR reviews, pay, personal notes); `public_read` fits reference data -everyone reads and the owner maintains (price lists, policies, notices). -`ownership` is a separate axis: whether `owner_id` exists at -all (Relationship Patterns below). - -**Important optional properties:** - -| Property | Default | Description | -|:---------|:--------|:------------| -| `label` | Auto from `name` | Singular label | -| `pluralLabel` | — | Plural form; author it alongside `label` | -| `icon` | — | Icon for nav, list headers and lookup pickers; give every object one | -| `color` | `gray` | Tile colour behind the white `icon`: `gray` `blue` `teal` `green` `amber` `orange` `red` `pink` `purple` (no hex). Group the app's objects into a few business families, one name each, as the platform's own objects do: people `blue`, security `purple`, approvals and work `orange`, messaging `pink`, integrations `teal`, reference data and finance `green`, audit and settings `amber`. `red` only for an alert object; one nobody opens gets none | -| `highlightFields` | derived | Ordered field keys used as a record's compact face: the columns a **related list** renders on the parent's detail page, and what a lookup picker shows. Declare it on the CHILD object (see [Relationships](./rules/relationships.md)) | -| `namespace` | — | **Not a schema key**: refused as unknown. Embed the prefix in `name` | -| `datasource` | `'default'` | Target datasource ID | -| `nameField` | derived (e.g. `'name'`/`'title'`) | Record-title field: the stored field used as the record's display name. Use a single text/email field; a composite title to import, sort or search by is a stored computed field (a non-`formula` field with an `expression`); a text formula is display-only | -| `displayNameField` | — | **Deprecated** alias for `nameField`, still read | -| `titleFormat` | — | **Refused** by a save and `os validate` (`title-format-retired`): use `nameField` | -| `enable` | — | Capability flags (next section) | -| `fieldGroups` | — | Ordered field groups for forms/detail pages (see [Field Groups](./references/examples-objects.md#field-groups-mvp)) | -| `lifecycle` | `record` (permanent) | Data retention/rotation/archival contract. **Required for append-only, high-write-rate objects** (see [Data Lifecycle & Retention](./rules/lifecycle.md)) | - -### Object Capabilities (`enable`) - -| Flag | Default | Purpose | -|:-----|:--------|:--------| -| `fieldHistory` | on | A changed field's old → new values on the activity timeline, served per the reader's field read rule. `false`: off for the object. A field opts out with its own `fieldHistory: false`; a media or structured field (`json`, `address`, `code`…) shows values only with `true`, a credential never. `sys_audit_log` keeps its own grant | -| `trackHistory` | `false` | Ledger view on the record page and the `history` API verb; not the values switch | -| `searchable` | `true` | Index records for global search | -| `apiEnabled` | `true` | Expose via automatic REST + MCP APIs | -| `apiMethods` | all | Whitelist over the six primitives (`get`, `list`, `create`, `update`, `delete`, `bulk`); derived verbs (search/export/upsert/…) follow automatically | -| `files` | `false` | Attachments | -| `feeds` | `true` | Feed, comments, mentions; `false` hides the feed UI and rejects new comments | -| `activities` | `true` | Activity timeline (`sys_activity` mirror of CRUD); `false` stops mirroring and hides the timeline | -| `clone` | `true` | Record deep cloning | -| `aiReadable` | — | Platform `sys_*` objects only; on an app object, `false` included, refused at parse | - ---- - -## Search Fields (`searchableFields`) - -`searchableFields` on the object is the canonical set `$search` scans. -Leave it unset and search auto-defaults to the `nameField` plus the object's -short-text and enum columns (`text` / `email` / `phone` / `url` / `autonumber` / -`textarea` / `markdown` / `select`) plus every field marked `searchable: true`, -of any type except `secret` / `password` / `vector` or a virtual `formula`. `searchable: false`, the -default, never removes a field the type default scans; declare -`searchableFields` to choose the set. Views may narrow it, never widen it. - -### ⛔ Searching by a related record's title — mirror the value, always - -`$search` scans **the queried object's own columns**. A dotted path is never a -search target: unlike `fields` / `sort` / `filters`, the search axis does not -resolve traversal, and `project_id.name` in `searchableFields` (or in a -`$searchFields` override) is **refused** (`os validate` -`searchable-field-unknown`; a request, `400 INVALID_FIELD`). - -**This is the one prescription — emit it every time.** To search by a related -record's title, copy that title into a **stored field on this object** and -declare *that* field searchable. A task list searched by project name: - -```typescript -{ - name: 'task', - enable: { searchable: true }, - fields: { - name: { type: 'text', required: true }, - project_id: { type: 'lookup', reference: 'project' }, - project_name: { type: 'text', label: 'Project Name' }, - }, - searchableFields: ['name', 'project_name'], -} -``` - -`?search=apollo` expands to `name $contains 'apollo' OR project_name $contains -'apollo'` — one single-table scan, every driver. - -❌ **Never mirror onto a `formula` field.** It is *virtual* (no column to scan) -and CEL reads only this record's own fields, so it cannot hold the related title; -a `formula` entry in any `searchableFields` is refused — `os validate` -`searchable-field-unsearchable`, a request `400 INVALID_FIELD`. - -**Mirror maintenance is the trade-off.** Cover both paths: a `beforeInsert` / `beforeUpdate` hook on `task` -stamps `project_name` from the incoming `project_id`'s parent; an `afterUpdate` -hook on `project` re-stamps its tasks when it is renamed. Rows written past the hooks (bulk import, direct SQL) need a -one-off backfill. See [Lifecycle Hooks](./references/data-hooks.md). - ---- - -## Conditional Field Rules - -Put conditional UI/data-entry rules on the **field definition** when the rule -belongs to the data model and should apply everywhere the field is edited: -New and Edit, named and public forms, inline master-detail grids, API writes. - - -```typescript -import { P } from '@objectstack/spec'; -import { ObjectSchema, Field } from '@objectstack/spec/data'; - -export const Invoice = ObjectSchema.create({ - name: 'invoice', - sharingModel: 'public_read_write', - fields: { - status: Field.select({ - options: [ - { label: 'Draft', value: 'draft' }, - { label: 'Sent', value: 'sent' }, - { label: 'Paid', value: 'paid' }, - { label: 'Void', value: 'void' }, - ], - }), - paid_at: Field.datetime({ - visibleWhen: P`record.status == 'paid'`, - requiredWhen: P`record.status == 'paid'`, - }), - locked_total: Field.currency({ - readonlyWhen: P`record.status == 'paid'`, - }), - }, -}); -``` - -- Use `visibleWhen` to hide irrelevant fields in ObjectUI forms. -- `showOnCreate: false` keeps a field off every create surface; edit, the - record page and lists keep it. Refused beside `required: true`. -- Use `readonlyWhen` for state-locked fields; the ObjectQL write path ignores - incoming changes when the predicate is `TRUE` (for everyone; per permission - set → field permission `when`, rules/security.md). -- **`readonly: true` governs the end-user surface, not trusted system writers.** - A non-system write (REST/UI, and any `runAs:'user'` flow) has - the field **stripped**; the write reports - success but the value never lands. System-context writes — - `runAs:'system'` flows, system hooks, seeds, imports, migrations — are exempt - and DO write it. Keep the field `readonly` when automation maintains it; the - flow side: [objectstack-automation → Failure routing & `runAs`](../objectstack-automation/SKILL.md#failure-routing--runas). -- Use `requiredWhen` for conditional requiredness; the ObjectQL validator - enforces it on submit. The removed `conditionalRequired` alias is a parse - error. -- **Choose by intent — invariant or transition gate.** A fact true of *every - stored record* is an invariant: a `validations[]` `script` rule. A row that - violates it is refused on any edit until repaired. A *transition* condition - ("required once the record reaches `paid`") is `requiredWhen` / field bounds, - which judge the write, not the stored row. "Required when X" reads like an - invariant and is not one; an invariant written as a gate never enforces - itself. -- For inline `master_detail` grids, predicates are evaluated row-by-row against - the child row's `record`, so line-item rules should live on child fields. -- For complex predicates, load **objectstack-formula** and emit CEL via - `P\`...\``; do not use Salesforce-style `AND`, `IN (...)`, or `{field}` - syntax. - ---- - -## Schema evolution on an existing database - -The metadata→DB sync is **additive-only**: new tables/columns are created on -boot, but existing columns are **never** altered or dropped. A non-additive -change to an object that already has data silently diverges from the physical -schema, and the **database column wins at write time**: - -| Change | Existing DB on restart | -|--------|------------------------| -| add object / field / index | ✅ applied automatically | -| `storage: { notNull: true }` removed (relax `NOT NULL`) | ⚠️ **never auto-applied** — the drift is `category: 'needs_confirm'` (`relax_not_null`), so `os migrate apply` confirms it | -| `unique` re-scoped global → per-tenant | dev auto-heals; otherwise `os migrate apply` (`replace_unique_index`) | -| type / length change, drop field | `os migrate apply` (`--allow-destructive` for drops / tightenings) | -| rename a field | `renamedFrom: ['old_key']` on the new key: the sync carries the column's values | -| declared index removed, or its columns changed | `os migrate apply` (`--allow-destructive` when it drops, or rebuilds as `UNIQUE`) | - -**`required` is not the `NOT NULL` dial.** `required` is the -**write contract** — the engine refuses an insert that omits the value — and it -implies nothing about the column. The physical constraint is a separate explicit -opt-in, `storage: { notNull: true }`, and it is what drift detection compares -against. So tightening `required` on a deployed object is safe (existing null -rows stay readable), while declaring `storage.notNull` over null rows is a -destructive migration. The two cannot be combined with `requiredWhen`. - -Tell-tale: `/meta` reports a field optional (no `required`, no `storage.notNull`) -but writes that omit it fail with a **raw driver error** rather than a clean -validation 400 — that is a stale `NOT NULL` column, not a validator bug. Run -`os migrate plan` to preview and `os migrate apply` to reconcile, or ratify the -column by declaring `storage: { notNull: true }`. CLI details: see -**objectstack-platform**. - ---- - -## Common Patterns - -### Naming Rules Summary - -`snake_case` object names and field keys, `camelCase` schema properties, -lowercase option values — examples: [rules/naming.md](./rules/naming.md). +- `name` and field keys are immutable `snake_case`; a module prefix goes in + `name` (`namespace` is not a key). +- **Author `sharingModel` on every object**: Zod marks it optional, but a + publish without it is refused (`security-owd-unset`). Choose it from the + request. `public_read_write`: a business object a team shares + (`private` would hide every colleague's records). `private`: personal or + sensitive data only its owner should see (HR reviews, pay), widened by + sharing rules, RLS or `readScope`/`writeScope`. `public_read`: reference + data everyone reads and the owner maintains (price lists, policies). + `controlled_by_parent`: a `master_detail` child, inherited from its master. +- Author `pluralLabel` and `icon` beside `label`. The record title is + `nameField`: one stored text or email field, never a text formula. + +Every other key: [examples-objects.md](./references/examples-objects.md#object-keys). ### Field Type Selection -Two to get right here (the rest: [rules/field-types.md](./rules/field-types.md)): credentials are `secret` (**encrypted-at-rest**, ADR-0100) — -never `password`, which on a generic object is **plaintext at rest**; `formula` takes CEL in `expression` (a `{ dialect: 'cel', source }` envelope — -`F\`...\`` in TypeScript; see **objectstack-formula**). +Credentials are `secret` (encrypted at rest), never `password`, which on a +generic object is plaintext at rest. A person is `type: 'user'` with no +`reference`, optional unless the request says otherwise. `formula` takes CEL +in `expression`, a `{ dialect: 'cel', source }` envelope (`F\`...\`` in +TypeScript; **objectstack-formula**). + +- A yes/no flag is `{ type: 'boolean', defaultValue: false }`. `required` on + it refuses only `null`, so it never means "must be checked": that is a + `validations[]` rule. +- A dynamic default (`defaultValue: 'current_user'`) resolves when + the record is SAVED with the field empty. Describe it as save-time, not as + a pre-filled form. -- A yes/no flag (`is_*`, `has_*`, "done?", "active?") is `{ type: 'boolean', defaultValue: false }`. - `required` on it refuses only `null`: an unchecked box is a value, so it - never means "must be checked". A box that must be checked (terms, consent) - is a `validations[]` rule: `{ name: 'terms', type: 'script', - condition: { dialect: 'cel', source: 'record.accepted != true' }, message: 'Accept the terms.' }`. - The default also lands seeded or imported rows that omit the column on - `false`, not a null that only looks unchecked. -- A person on the record (approver, reviewer) is `type: 'user'` with - no `reference`, and optional unless the request says otherwise — the platform - already stamps the owner and `created_by`. -- A dynamic default (`defaultValue: 'current_user'`, `'NOW()'`, a CEL envelope) - resolves when the record is SAVED with the field empty. Describe it as - save-time; whether a create form pre-displays it is a client capability you - cannot promise. +More: [Field Types](./rules/field-types.md#choosing-a-type). ### Relationship Patterns -| Pattern | Implementation | -|:--------|:---------------| -| One-to-Many (independent) | `lookup` field on child | -| One-to-Many (owned) | `master_detail` field on child | -| Many-to-Many (simple) | multi-value `lookup` (`multiple: true`) — an **array column** of ids | -| Many-to-Many (with attributes) | Junction object with two `lookup` fields | -| Hierarchical | `tree` field (self-reference) | -| Record status / lifecycle | a `select` on the business object (plus a `state_machine` validation) — never a separate status / stage / step table | -| Approval, review, routing, audit trail | not objects: an approval is a flow node (**objectstack-automation**) and its trail is platform history; model only the people it references (approver, reviewer), as `user` fields beside the owner | -| Record owner | the platform's `owner_id` (`ownership: 'user'`, the default), also when the request says assignee, 负责人 or 处理人 — never a hand-added owner field, a second owner that owner-scoped visibility and "My records" views never read. A handler the request names apart from the owner is a `user` field that grants no access, with a label no other visible field carries, injected ones included: `owner_id` (Owner, 负责人), `created_by` (创建人), `updated_by` (更新人), `created_at` (创建时间), `updated_at` (更新时间). `ownership: 'none'` only for a shared catalog or a pure junction table | +| Need | Model it as | +|:--|:--| +| Many-to-many | multi-value `lookup` (`multiple: true`), an **array of ids**; with attributes, a junction object with two `lookup` fields | +| Record status / lifecycle | a `select` on the business object (plus a `state_machine` validation), never a separate status / stage / step table | +| Approval, review, routing, audit trail | not objects: an approval is a flow node (**objectstack-automation**) and its trail is platform history; model only the people, as `user` fields | +| Record owner | the platform's `owner_id` (`ownership: 'user'`, the default), also when the request says assignee, 负责人 or 处理人; never a hand-added owner field, which owner-scoped visibility and "My records" views never read | -> A `multiple: true` lookup's ids are referenced positionally (`{record.tags.0}` in flow values). +The rest, and a handler named apart from the owner: +[Relationships](./rules/relationships.md). ### Validation Patterns -**⚠️ Script validation is inverted:** Validation **fails** when expression is `true`. - -The **complete** set of types (`ValidationRuleSchema` discriminators): `script`, -`state_machine`, `format`, `cross_field`, `json_schema`, `conditional`. - -A `state_machine` rule that runs on insert declares `initialStates`, or publish -refuses it (`state-machine-no-initial-states`): a record could be created -already `approved`. An update-only machine (`events: ['update']`) needs none. -List only entry states (usually one: `draft` / `new`), never a terminal one; -keys and values are option `value`s, never labels. - -> **There is NO `unique` validation type** — uniqueness is a unique **index** -> with its scope ([rules/validation.md § Uniqueness](./rules/validation.md#uniqueness--use-unique-indexes)). - -### Index Patterns - -**The whole declaration surface is `fields` / `unique` / `name`.** - -```typescript -indexes: [ - { fields: ['status', 'created_at'] }, // composite - { fields: ['email'], unique: 'organization' }, // unique per organization - { fields: ['hostname'], unique: 'global' }, // unique platform-wide - { name: 'idx_acct_status', fields: ['status'] }, // custom name -] -``` - -See [rules/indexing.md](./rules/indexing.md) for unique scope -(on a declared index bare `unique: true` is refused), the retired `type` / `partial`, and partial / gin / gist indexes at the -database layer. - ---- - -## Object Extension Model - -To add fields/validations/indexes to an object you do not own, author -`defineObjectExtension({ extend, fields, fieldPatches, place, priority })` and register it on -`defineStack({ objectExtensions: [...] })`. `priority` sets merge order (default -`200`, `0–999`); an extension adds, never removes, except that a new -`label` without `pluralLabel` clears the base plural unless a tenant authored it (set both). ⛔ `extend` -is not object-level `ownership` (`'user' | 'business_unit' | 'org' | 'none'`). - -`place: [{ field: 'tax_id', group: 'basic', after: 'industry' }, { list: 'acme_contract', after: 'crm_opportunity' }]` -puts the extension's own fields, groups (`{ group: { key, label }, after }`) and child lists -after (or `before`) a named item, where the target declares `fieldGroups` / `relatedLists`. - -**Relabel a field the owner declares with `fieldPatches` — never by redeclaring -it in `fields`**, which takes the field over whole and cuts it off from the -owner's upgrades. A patch carries display keys only: -`label`, `description`, `inlineHelpText`, -`placeholder`, and an option's `label` keyed by its stored `value`; the type, -values and rules stay the owner's. A key the tenant edited keeps the tenant's -text; between two extensions the higher `priority` wins. A patch naming a field -or option value the target lacks is refused at install and by `os validate`, and -a `picklist`-bound field's options are never patchable. Example: -`defineObjectExtension({ extend: 'crm_account', fieldPatches: { industry: { label: 'Sector' }, type: { options: { customer: { label: 'Client' } } } } })`. -Translate patched text in the patching package's `translations`, under the -owner's keys (`objects.crm_account.fields.industry.label`, `.help`, -`.options.`): the owner's translation of the replaced text never applies, a -pair `.custom` translation comes first on `/meta`, and an untranslated locale -serves the patch text. +**⚠️ Script validation is inverted:** it **fails** when the expression is +`true`. -**An object an installed package ships** is extended from the -base's paired `.custom` package (`hotcrm.custom`; **objectstack-platform** -§ Customizing an installed package), never replaced: it takes no `overrides` -declaration. Every field the pair adds ends in `__c` (`region__c`). The suffix is -reserved to the pair, so a `__c` field in any other package, or an unsuffixed -field in a `.custom` extension, is refused at save, publish and install and by -`os validate` / `os build`. -Only the pair's extension also writes `fieldGroups`, `relatedLists` and `actionLayout` -(**objectstack-ui**), shaped as on an object. A written key replaces that arrangement -whole (the owner's and every `place`; `actionLayout`, each arm it writes): an unlisted -field shows after the last group, an unnamed tab after the listed ones, and -`{ list: 'crm_note', hidden: true }` hides a tab. Outside a `.custom` package they are -refused at those doors: use `place`, or for an action its own `locations` and `order`. -Studio's **Add field** on a base object writes the same extension, as an -`object_extension` item of the pair. - ---- - -## Security & Access Control - -Per-object access control is authored in **permission sets**, not on the object -schema. There is no object-level `permissions` key (and no `hooks` key either) — -`ObjectSchema.create()` **rejects** both as unknown keys. +A `state_machine` rule that runs on insert declares `initialStates` (entry +states only), or publish refuses it: a record could be created already +`approved`. **There is NO `unique` validation type**: +uniqueness is a unique index with its scope +([Validation](./rules/validation.md#uniqueness--use-unique-indexes)). ### Access depth (scope-depth) — the ERP "see my unit / my unit and below" axis -On an owner-scoped (`private`) object, a per-object grant in a permission set may -carry `readScope` / `writeScope` to widen the owner match declaratively instead of -hand-writing an RLS policy (ADR-0057 D1): `own` (default) · `own_and_reports` · -`unit` · `unit_and_below` · `org`. It resolves at request time into an -`owner_id IN (…)` set and AND-injects like RLS. ⚠️ Open-core boundary (ADR-0016): -only `own` and `org` work in open source — the hierarchy-relative three need the -paid `@objectstack/security-enterprise` plugin in `plugins[]`, **fail closed to -`own`** without it, and `defineStack` errors unless the stack declares -`requires: ['hierarchy-security']`. The CLI only advises on a missing or unwired -plugin: `os validate` warns, `os verify --json` lists it in `capabilities`. - -### Ownership queues — park a record for a team to claim - -Every `ownership: 'user'` object carries a platform-injected `queue` column -beside `owner_id` (an object declaring its own `queue` field is refused). A -record **sits in** a queue when `owner_id` is empty and `queue` names it: the -queue's members read and edit it (rows widen, verbs never — no delete). Declare -the queue on the stack; a declared queue's members are positions only, an -organization adds users and teams through `sys_queue_member` rows: - - -```typescript -import { defineQueue } from '@objectstack/spec/security'; - -export const supportIntake = defineQueue({ - name: 'crm_support_intake', // the one name the `queue` column, a rule, an approver and a sharing recipient use - label: 'Support Intake', - members: [{ type: 'position', value: 'crm_service_agent' }], -}); -// defineStack({ queues: [supportIntake], assignmentRules: [...] }) — routing rows in: objectstack-automation -``` - -**Claim** is an ordinary by-id update, `{ owner_id: }`, admitted to a -member while the record is unowned; one writer wins, the other gets `409 -CONCURRENT_UPDATE`. **Release**: the owner writes `owner_id: null` and the record -sits in its home queue again. **Move**: writing another `queue` is a transfer -(`allowTransfer` or `modifyAllRecords`). ⛔ Never a per-record `assigned_to` -picklist, a round-robin counter field, or a hook that picks an owner. - ---- - -## Verify your work - -After authoring or editing any `*.object.ts` / `*.seed.ts`, run the author-time -gate before reporting done: - -```bash -os validate # Zod schema + CEL predicates (record. existence) + bindings -# or: os build # the same gates, plus emits dist/ -``` - -It catches what otherwise surfaces only at runtime, where a bare field ref -(`done` for `record.done`) faults: an `error` validation rule or `requiredWhen` -refuses the write naming it, an option `visibleWhen` only a write picking the -option (forms still offer it); a `readonlyWhen` field stays editable and the -save succeeds without its change (logged); a formula reads `null` (logged). -`os lint` is a *separate* -pass that additionally checks the data model against the conventions in this -skill (relationships, master-detail, roll-ups) — run it too. -In a scaffolded project the gate is `npm run validate`. - ---- - -## 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. +On a `private` object a permission-set grant may carry `readScope` / +`writeScope`: `own` (default) · `own_and_reports` · `unit` · `unit_and_below` · +`org`. Only `own` and `org` work in open source: the other three need the paid +`@objectstack/security-enterprise` plugin, **fail closed to `own`** without +it, and need `requires: ['hierarchy-security']` on the stack. diff --git a/.claude/skills/objectstack-data/evals/README.md b/.claude/skills/objectstack-data/evals/README.md index 41ef4dd..26cfeba 100644 --- a/.claude/skills/objectstack-data/evals/README.md +++ b/.claude/skills/objectstack-data/evals/README.md @@ -6,7 +6,8 @@ JSON fixtures in the objectui shape (`skill_name`, `evals[]`: `prompt`, - `objects-fields-relationships.json` — naming, field types (`secret` vs `password`), relationships (junction vs multi-value lookup, `deleteBehavior`, on a `user` field too), validation (`state_machine`, unique **index**), - conditional field rules, the record owner (负责人 is `owner_id`), an + conditional field rules, the hand lock (a `uiReadonly` status field), the + record owner (负责人 is `owner_id`), an object extension placing what it brings (`place`), the `.custom` pair's whole arrangement (`relatedLists`, `{ list, hidden: true }`). - `hooks-security-seeds-datasources.json` — search mirrors via hooks, diff --git a/.claude/skills/objectstack-data/evals/hooks-security-seeds-datasources.json b/.claude/skills/objectstack-data/evals/hooks-security-seeds-datasources.json index 1cd33b5..7df9d5f 100644 --- a/.claude/skills/objectstack-data/evals/hooks-security-seeds-datasources.json +++ b/.claude/skills/objectstack-data/evals/hooks-security-seeds-datasources.json @@ -104,10 +104,11 @@ { "id": 7, "prompt": "We serve English and Chinese users. An `order` whose `amount` exceeds its account's `credit_limit` must not save; API clients branch on `CREDIT_LIMIT`, a zh-CN rep reads `超出账户信用额度`.", - "expected_output": "A `beforeInsert` / `beforeUpdate` hook on `order` declares `refusals: { CREDIT_LIMIT: { message: 'Over the account credit limit.' } }`; its sandboxed `body: { language: 'js', source }` reads the account via `ctx.api` and refuses by code only (`throw Object.assign(new Error(), { code: 'CREDIT_LIMIT' })`); the zh-CN bundle's `hooks: { : { refusals: { CREDIT_LIMIT: { message: '超出账户信用额度' } } } }` is served in the caller's locale; a catalogue on a hook without a `js` body is refused at save.", + "expected_output": "A `beforeInsert` / `beforeUpdate` hook on `order` declares `refusals: { CREDIT_LIMIT: { message: 'Over the account credit limit.' } }`; its sandboxed `body: { language: 'js', source }` reads the account via `ctx.api` and refuses by code only (`throw Object.assign(new Error(), { code: 'CREDIT_LIMIT' })`); the zh-CN bundle's `hooks: { : { refusals: { CREDIT_LIMIT: { message: '超出账户信用额度' } } } }` (or the same entry as the dotted key `hooks..refusals.CREDIT_LIMIT.message`) is served in the caller's locale; a catalogue on a hook without a `js` body is refused at save.", "files": [], "assertions": { - "must_contain": ["refusals:", "CREDIT_LIMIT: {", "code: 'CREDIT_LIMIT'", "language: 'js'", "hooks: {", "超出账户信用额度"], + "must_contain": ["refusals:", "CREDIT_LIMIT: {", "code: 'CREDIT_LIMIT'", "language: 'js'", "超出账户信用额度"], + "must_contain_any": [["hooks: {", "\"hooks\": {", ".refusals.CREDIT_LIMIT"]], "must_not_contain": ["new Error('", "handler:"] } }, @@ -234,7 +235,7 @@ { "id": 28, "prompt": "A blocking `afterUpdate` hook body on `invoice` (default `onError: 'abort'`) runs `ctx.api.transaction`: it inserts a `payment`, then throws when the balance would go negative. The body catches that throw so the save still succeeds. Is the `payment` row rolled back? Is it committed when the callback returns? We also want it to insert a `bank_transfer`, a business object on our `finance` datasource, in the same callback.", - "expected_output": "Inside the save's unit (a blocking `afterUpdate` that can abort runs in it) `ctx.api.transaction` joins that unit: its throw is no rollback and its return is no commit. The caught throw keeps the `payment` row, and the outer unit commits it with the save, or rolls back all of it. To undo the payment, check the balance before inserting, or let the throw out of the body so the save is refused and everything rolls back. A body transaction is on the default datasource only: the `bank_transfer` insert is refused before it runs, `400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`, and a plain `ctx.api` write to it inside the save's unit is refused the same way. Keep the objects it writes on the default datasource, or make that write outside the unit (an `async: true` hook).", + "expected_output": "Inside the save's unit (a blocking `afterUpdate` that can abort runs in it) `ctx.api.transaction` joins that unit: its throw is no rollback and its return is no commit. The caught throw keeps the `payment` row, and the outer unit commits it with the save, or rolls back all of it. To undo the payment, check the balance before inserting, or let the throw out of the body so the save is refused and everything rolls back. A body transaction is on the default datasource only: the `bank_transfer` insert is refused before it runs, `400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE` (only an append-only ledger, `lifecycle.class` `audit` / `telemetry` / `event`, is written outside the unit, and `bank_transfer` is not one), and a plain `ctx.api` write to it inside the save's unit is refused the same way. Keep the objects it writes on the default datasource, or make that write outside the unit (an `async: true` hook).", "files": [], "assertions": { "must_contain": ["join", "ERR_CROSS_DATASOURCE_TRANSACTION_WRITE"], @@ -314,7 +315,7 @@ { "id": 25, "prompt": "A `beforeInsert` hook on `time_entry`, declared in the stack's `hooks`, creates the week's `timesheet` row through `ctx.api` when there is none. A validation rule then refuses the entry (`hours > 24`). Is an empty timesheet left behind? Would `onError: 'log'` on the hook keep it? In which setups does it stay?", - "expected_output": "No: the save and the hook's `ctx.api` insert run in one transaction, so the refusal rolls the `timesheet` row back with the entry. `onError: 'log'` does not keep it: there is no per-hook opt-out. It stays stored only where no transaction is opened: `time_entry`, the hooked object, is off the default datasource, or the default driver has no transactions (Turso's remote transport). A hook registered in code with `registerHook` opens no transaction either, and inside a transaction the caller opened, the caller decides. MongoDB needs a replica set for this transaction (read in code, not measured).", + "expected_output": "No: the save and the hook's `ctx.api` insert run in one transaction, so the refusal rolls the `timesheet` row back with the entry. `onError: 'log'` does not keep it: there is no per-hook opt-out. It stays stored only where no transaction is opened: `time_entry`, the hooked object, is off the default datasource, or the default driver has no transactions (Turso's remote transport). A hook registered in code with `registerHook` opens no transaction either, and inside a transaction the caller opened, the caller decides. A standalone MongoDB server refuses every write such a transaction carries (`NOT_IMPLEMENTED`, 501); a single-node replica set is enough. On PostgreSQL and a MongoDB replica set, a `ctx.api` statement of the hook that fails at the database refuses the save even when the body catches it, `onError: 'log'` swallows it or `retryPolicy` re-runs it (`25P02` on PostgreSQL, code `251` on MongoDB); SQLite lets a caught failure through.", "files": [], "assertions": { "must_contain": ["roll", "default datasource", "registerHook"], diff --git a/.claude/skills/objectstack-data/evals/objects-fields-relationships.json b/.claude/skills/objectstack-data/evals/objects-fields-relationships.json index 5a6363b..d658205 100644 --- a/.claude/skills/objectstack-data/evals/objects-fields-relationships.json +++ b/.claude/skills/objectstack-data/evals/objects-fields-relationships.json @@ -172,14 +172,14 @@ { "id": 10, "prompt": "给 `task` 加一个「是否完成」字段,设成必填,免得有人忘了填。", - "expected_output": "Adds `is_done: { type: 'boolean', label: '是否完成', defaultValue: false }`; `required: true` may stay or go, and either way the answer says what it does: on a boolean `required` refuses only `null`, and an unchecked box is a value, so it never means \"must be ticked\" and nobody can forget to fill it — the default lands every row, imported or seeded ones included, on a real `false`. Tells the user that \"must be ticked\" (terms, a consent) is a `validations[]` `script` rule whose `condition` is true while the box is not `true`, not `required`. The label is Chinese, as the request is.", + "expected_output": "Adds `is_done: { type: 'boolean', label: '是否完成', defaultValue: false }` (or the factory form, `Field.boolean({ label: '是否完成', defaultValue: false })`); `required: true` may stay or go, and either way the answer says what it does: on a boolean `required` refuses only `null`, and an unchecked box is a value, so it never means \"must be ticked\" and nobody can forget to fill it — the default lands every row, imported or seeded ones included, on a real `false`. Tells the user that \"must be ticked\" (terms, a consent) is a `validations[]` `script` rule whose `condition` is true while the box is not `true`, not `required`. The label is Chinese, as the request is.", "files": [], "assertions": { "must_contain": [ - "type: 'boolean'", "defaultValue: false", "label: '是否完成'" ], + "must_contain_any": [["type: 'boolean'", "Field.boolean("]], "must_not_contain": [ "label: 'Is Done'" ] @@ -275,7 +275,7 @@ { "id": 16, "prompt": "Our `consent_change` audit log must show it if anyone edits, inserts or deletes rows directly in the database, but whatever proof is stored must not carry the consent text itself. How do I declare that?", - "expected_output": "Keep `lifecycle.class: 'audit'` with its bounding `retention` (or a `ttl` on `created_at`) and add `seal: { valueFields: ['consent_text'] }`: the audit plugin signs each `created_at` hour into one checkpoint per organization, chained to the one before, where `valueFields` columns enter as salted commitments and every other column in clear. The object declares its own `id` and a text or lookup `tenant_id` field; without that `tenant_id` (and with no `chainField` naming another chain column, such as the injected `organization_id`) it is refused at parse, and without `id` it parses but is not sealed, and the sealer reports it at `error` each hour. Refused at parse: `seal` on a class other than `audit`, `valueFields` naming `id`, `created_at` or an undeclared field, and beside `seal` a `retention` or `ttl` `onlyWhen`, a `ttl` on another field, or rotation `storage`. Signed expiry covers objects whose lifecycle is declared in packaged metadata, as this one is: its sealed rows leave only by whole checkpoints and read as `expired`. With no `archive`, a retention override below the declared window is rejected and the declared window applies; to keep rows for less time, shorten the declared window. On any other sealed object (one created at runtime) the sweeper still deletes sealed rows, which then read as missing. Field history is not tamper evidence.", + "expected_output": "Keep `lifecycle.class: 'audit'` with its bounding `retention` (or a `ttl` on `created_at`) and add `seal: { valueFields: ['consent_text'] }`: the audit plugin signs each `created_at` hour, per organization chain, into one checkpoint (or consecutive checkpoints of at most 10,000 rows), each chained to the one before, where `valueFields` columns enter as salted commitments and every other column in clear. The object declares its own `id` and a text or lookup `tenant_id` field; without that `tenant_id` (and with no `chainField` naming another chain column, such as the injected `organization_id`) it is refused at parse, as is a `chainField` naming a column the object lacks or one that cannot name an organization, and without `id` it parses but is not sealed, and the sealer reports it at `error` each hour. Refused at parse: `seal` on a class other than `audit`, `valueFields` naming `id`, `created_at` or an undeclared field, and beside `seal` a `retention` or `ttl` `onlyWhen`, a `ttl` on another field, or rotation `storage`. Signed expiry covers objects whose lifecycle is declared in packaged metadata, as this one is: its sealed rows leave only by whole checkpoints and read as `expired`. With no `archive`, a retention override below the declared window is rejected and the declared window applies; to keep rows for less time, shorten the declared window. On any other sealed object (one created at runtime) the sweeper still deletes sealed rows, which then read as missing. `os audit verify` checks the ledger and exits 1 on a changed, missing or unsealed row or a chain fault such as a row `listed_twice`. Field history is not tamper evidence.", "files": [], "assertions": { "must_contain": [ @@ -515,6 +515,19 @@ ], "must_not_contain": [] } + }, + { + "id": 30, + "prompt": "On `sales_order`, `status` (`draft`, then `confirmed`) should change only through the Confirm button: nobody may pick another status in the form, in a grid cell or by dragging a card on the board. A colleague set `readonly: true` on `status`; now Confirm answers success and the order stays `draft`. Why, and how should the field be declared so that Confirm works and can only take a draft order to confirmed?", + "expected_output": "`readonly: true` is the server lock: every non-system write to the field is dropped, not refused, and the Confirm action's own update is such a write, so it answers success without the change (`X-ObjectStack-Dropped-Fields` names the field). Declare the hand lock instead: `status: Field.select({ options: [...], defaultValue: 'draft', uiReadonly: true })`. Forms, inline edit, grid cells and board drags stop offering the field, while the action, an import and the API still write it, each write judged by the object's validations; so the legal move goes in a `state_machine` rule on `status` (`draft: ['confirmed']`). It is not security: whoever may edit the record can still write the field through the API.", + "files": [], + "assertions": { + "must_contain": [ + "uiReadonly: true", + "state_machine" + ], + "must_not_contain": [] + } } ] } diff --git a/.claude/skills/objectstack-data/references/data-hooks.md b/.claude/skills/objectstack-data/references/data-hooks.md index a027597..2843973 100644 --- a/.claude/skills/objectstack-data/references/data-hooks.md +++ b/.claude/skills/objectstack-data/references/data-hooks.md @@ -57,8 +57,8 @@ after an operation — see [Before vs After](#before-vs-after-hooks). | **Purpose** | Validation, enrichment, transformation | Side effects, notifications, logging | | **Can modify** | `ctx.input` (mutable) | `ctx.result` (mutable) | | **Can abort** | Yes (throw error → rollback) | A sync after-hook's throw still rolls back the transaction (see error handling) | -| **Transaction** | One transaction with the outer write: a refusal anywhere in it (a validation, a later hook, a driver constraint) rolls back the hook's `ctx.api` writes; no per-hook opt-out. Exits: a caller's open transaction decides; a hooked object off the default datasource, or a default driver with no transactions (Turso's remote transport), opens none, so those writes stay stored after a refusal; a hook registered in code (`registerHook`) opens none. MongoDB needs a replica set (read in code, not measured) | **Within the transaction**. `async: true` on `afterInsert` / `afterUpdate` / `afterDelete`: starts once the outermost transaction commits, never if it rolls back (a failed commit included); on `afterFind`: starts as the read is dispatched; outside a transaction: starts at once | -| **Error handling** | Aborts by default (`onError: 'abort'`) | **Also aborts by default** — `onError` defaults to `'abort'` unconditionally; set `onError: 'log'` on side-effect hooks | +| **Transaction** | One transaction with the outer write: a refusal anywhere in it (a validation, a later hook, a driver constraint) rolls back the hook's `ctx.api` writes; no per-hook opt-out. Exits: a caller's open transaction decides; a hooked object off the default datasource, or a default driver with no transactions (Turso's remote transport), opens none, so those writes stay stored after a refusal; a hook registered in code (`registerHook`) opens none. A standalone MongoDB refuses every write of such a transaction (501 `NOT_IMPLEMENTED`); a single-node replica set is enough. On PostgreSQL and a MongoDB replica set a failed `ctx.api` statement refuses the outer write even when caught, logged (`onError: 'log'`) or retried (`25P02` / `251`); SQLite lets it through | **Within the transaction**. `async: true` on `afterInsert` / `afterUpdate` / `afterDelete`: starts once the outermost transaction commits, never if it rolls back (a failed commit included); on `afterFind`: starts as the read is dispatched; outside a transaction: starts at once | +| **Error handling** | Aborts by default (`onError: 'abort'`) | **Also aborts by default**; set `onError: 'log'` on side-effect hooks | --- @@ -79,13 +79,13 @@ const myHook = defineHook({ // Required: Unique identifier (snake_case) name: 'crm_validation_hook', - // Required: Target object(s) + // Required object: 'account', // string | string[] | '*' - // Required: Events to subscribe to + // Required events: ['beforeInsert', 'beforeUpdate'], - // The logic: a sandboxed body (the inline `handler` is deprecated) + // The logic: a sandboxed body body: { language: 'js', source: `/* statements against ctx */`, @@ -101,16 +101,16 @@ const myHook = defineHook({ // Optional: Conditional execution (CEL predicate over `record`) condition: P`record.status == 'active' && record.amount != null && record.amount > 1000`, - // Optional: Human-readable description + // Optional description: 'Validates account data before save', - // Optional: Error handling strategy + // Optional onError: 'abort', // 'abort' | 'log' - // Optional: Execution timeout (ms) + // Optional, ms timeoutMs: 5000, - // Optional: Retry policy + // Optional retryPolicy: { maxRetries: 3, backoffMs: 1000, @@ -145,8 +145,7 @@ in neither). So: `record.done == true` works on an update that only sets `status`. - `record` describes the record's **state**, not the diff. `record.done == true` fires on every update of an already-done record, not only on the update that - set it. **For the transition, compare against `previous`**: - `previous.done != true && record.done == true`. `previous` is the stored + set it. **For the transition, compare against `previous`**, as above. `previous` is the stored pre-write row, made total over the same declared fields, and it is the same binding a validation predicate reads. - **`previous` is `null` on insert** (`beforeInsert` / `afterInsert`), so @@ -166,8 +165,7 @@ in neither). So: object) — the engine refuses the batch whole, before any write, when two rows' key sets differ (`MULTI_UPDATE_HOOK_KEY_DIVERGENCE`, status 400; ADR-0058 Amendment II.3). -- **`after*` hooks dispatch once per matched row too** (`record` is that row's - real state, not the bare payload), so a transition condition on `afterUpdate` / +- **`after*` hooks dispatch once per matched row too**, so a transition condition on `afterUpdate` / `afterDelete` means the same whether the write carried an id or a predicate. - **Guard optional values with `!= null`, never with `has(...)`.** A declared field holding `null` is *present*, so `has(record.spent)` is uniformly true and @@ -206,11 +204,9 @@ body: { ``` - `source` is the **function body**, which the runtime wraps as - `(async (ctx) => { })(ctx)`. Write **statements** against `ctx`; - `await` is allowed. + `(async (ctx) => { })(ctx)`. Write **statements** against `ctx`. - In a `before*` hook, change the write by assigning `ctx.input.x = …` **or** - `return { x: … }` (a returned object is shallow-merged onto `ctx.input`). In an - `after*` hook the body is for side effects (cross-object writes, logging). + `return { x: … }` (a returned object is shallow-merged onto `ctx.input`). - `language: 'expression'` is a pure CEL formula for a computed value or predicate — no IO, no `ctx.api`. @@ -300,7 +296,7 @@ tokens (`HookBodyCapability`) are exactly seven: |:--|:--| | `api.read` | `ctx.api.object(n).find` / `findOne` / `count` / `aggregate`; also `ctx.title('')`. | | `api.write` | `ctx.api.object(n).insert` / `update` / `delete` | -| `api.transaction` | `ctx.api.transaction(async () => { … })` — runs the callback's `ctx.api` ops in **one transaction on the default datasource**: commit on return, rollback on throw. A write in it to an object on any other datasource is refused before it runs (`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`). Inside a unit already open (the one the hook's write runs in, or a caller's) it **joins** that unit: its return is no commit and its throw no rollback; the outer unit commits or rolls back all of it, so a throw the body catches keeps the callback's writes. Pair it with `api.write`. | +| `api.transaction` | `ctx.api.transaction(async () => { … })` — runs the callback's `ctx.api` ops in **one transaction on the default datasource**: commit on return, rollback on throw. A write in it to an object on another datasource is refused before it runs (`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`), except an append-only ledger (`lifecycle.class` `audit` / `telemetry` / `event`), written outside the unit and surviving its rollback. Inside a unit already open (the hook's write's, a caller's, or one an action body opened with `ctx.api.transaction`) it **joins** that unit: its return is no commit and its throw no rollback; the outer unit commits or rolls back all of it, so a throw the body catches keeps the callback's writes. Hooks of a write made inside a body's transaction run in that unit, and their `ctx.api` writes and own `ctx.api.transaction` join it. One level per body: a nested call is refused ("nested ctx.api.transaction is not supported"). On PostgreSQL and a MongoDB replica set a failed statement aborts the whole unit, even when caught. A driver with no transactions runs the callback with none and no warning: each write is stored as made, and a throw undoes none. Pair it with `api.write`. | | `crypto.uuid` | `ctx.crypto.randomUUID()` | | `log` | `ctx.log.debug` / `info` / `warn` / `error(msg, data?)` | | `email.send` | `ctx.email.send({ to, subject, text })` — mail via the mail service; sender, user and organization are stamped (`BodyMailSendInputSchema`). **Not in a hook body** (refused at parse and at bind): a message cannot be taken back if the hook's write rolls back. Mail on a record change goes through an action, a job or a flow. | @@ -312,7 +308,7 @@ There is **no `http.fetch` capability** by design — outbound calls go through ### Sandbox restrictions -The body runs in an isolated QuickJS VM, **not** Node: +The body's VM is **not** Node: - **Available:** standard JS built-ins — `Date`, `Math`, `JSON`, `Object`, `Array`, `String`, `Number`, `RegExp`, `Map`, `Set`, `Promise`, `parseInt`, @@ -345,13 +341,7 @@ The body runs in an isolated QuickJS VM, **not** Node: On `afterUpdate`, both `ctx.result` and `ctx.input` carry only the fields this PATCH touched (`ctx.result` adds `id`). A field you did **not** write — a lookup FK, a status you want to branch on — is **absent**, not stale. To read the whole record, -re-query it: - -```js -// afterUpdate on `candidate` -const full = await ctx.api.object('candidate').findOne({ where: { id: ctx.result.id } }); -// full.position_id is present even though this PATCH only set `stage`. -``` +re-query it by `ctx.result.id`, as the example below does. ### ⚠️ Gotcha 2 — cross-object writes obey the *target's* sharing model @@ -365,14 +355,13 @@ FORBIDDEN: ``` **An admin is not automatically exempt** — the gate is `canEdit`, driven by the -sharing model, not a global admin bypass. If a hook must write a target, give the +sharing model. If a hook must write a target, give the acting principal edit access to it (sharing rule / permission set), or drive the write from a system-context automation. ### Copy-paste example — afterUpdate + cross-object update + re-query + capabilities -When a `candidate` is marked `hired`, look up its `position` (a lookup FK that -is **not** in the partial patch) and flip that position to `filled`: +When a `candidate` is marked `hired`, look up its `position` and flip that position to `filled`: ```typescript @@ -408,10 +397,9 @@ export default fillPositionOnHire; wrapped message names the hook; the usual causes are a missing capability, a `FORBIDDEN` cross-object write (gotcha 2), or a `ReferenceError` from a free identifier or an unavailable global (e.g. `console`). -- **`ctx.log.*` produced no output** — two independent causes: (1) without the - `log` capability the call **throws** (surfaces as a hook error); (2) **with** the - capability it emits only when the runtime wired a logger into the hook context — - otherwise it is a **silent no-op**. Treat `ctx.log` as best-effort diagnostics, +- **`ctx.log.*` produced no output** — without the `log` capability the call + **throws**; **with** it, it emits only when the runtime wired a logger into the + hook context — otherwise it is a **silent no-op**. Treat `ctx.log` as best-effort diagnostics, never proof a hook ran; to observe an effect, assert on the data it writes. --- @@ -425,17 +413,15 @@ export default fillPositionOnHire; ```typescript interface HookContext { - // Immutable identifiers + // Immutable id?: string; // Unique execution ID for tracing object: string; // Target object name (e.g., 'account') event: HookEventType; // Current event (e.g., 'beforeInsert') - // Mutable data input: Record; // Operation parameters (MUTABLE) result?: unknown; // Operation result (MUTABLE, after* only) previous?: Record; // Previous state (update/delete) - // Execution context session?: { userId?: string; organizationId?: string; // Active org — the single blessed name. @@ -446,11 +432,10 @@ interface HookContext { isSystem?: boolean; // Elevated system context (engine self-writes). }; - transaction?: unknown; // Database transaction handle + transaction?: unknown; - // Engine access ql: IDataEngine; // ObjectQL engine instance - api?: ScopedContext; // Cross-object CRUD API + api?: ScopedContext; notice?: (message: string) => void; // User info shortcut (undefined for system / unauthenticated writes) @@ -491,7 +476,6 @@ const org = ctx.user?.organizationId ?? ctx.session?.organizationId; `ctx.input` varies by event: -**Insert operations:** ```typescript // beforeInsert, afterInsert { @@ -502,26 +486,22 @@ const org = ctx.user?.organizationId ?? ctx.session?.organizationId; } ``` -**Update operations:** ```typescript // beforeUpdate, afterUpdate { - id: '123', // Record ID being updated - // Only fields being changed + id: '123', status: 'active', updated_at: '2026-04-13T10:00:00Z', } ``` -**Delete operations:** ```typescript // beforeDelete, afterDelete { - id: '123', // Record ID being deleted + id: '123', } ``` -**Query operations:** ```typescript // beforeFind, afterFind { @@ -537,8 +517,6 @@ const org = ctx.user?.organizationId ?? ctx.session?.organizationId; ### `result` — Operation Result -Available in `after*` hooks: - ```typescript // afterInsert result: { id: '123', name: 'Acme Corp', ... } @@ -660,7 +638,6 @@ const maskSensitiveData = defineHook({ const isElevated = ctx.session?.isSystem === true; if (!isElevated) { - // Mask sensitive fields const maskField = (record: any) => { if (record.ssn) { record.ssn = '***-**-' + record.ssn.slice(-4); @@ -738,14 +715,15 @@ export default defineStack({ }); ``` -**2. Programmatic — `ctx.ql.registerHook()`, the plugin escape hatch.** Pass +**2. Programmatic — `ctx.ql.registerHook()`, the `onEnable` escape hatch.** Pass `packageId` so the hook can be unregistered cleanly. ⚠️ Hooks bound this way get **none** of the declarative `condition` / `retryPolicy` / `timeoutMs` / `onError` / `async` semantics — those apply only through `defineStack({ hooks })` or `ql.bindHooks([...])`. ```typescript -// in your plugin's onEnable() +// in the app's `onEnable` export (objectstack.config.ts). A kernel plugin has no +// `ctx.ql`: from `start(ctx)`, `ctx.getService('objectql').registerHook(…)`. ctx.ql.registerHook('beforeInsert', async (hookCtx) => { /* ... */ }, { object: 'account', priority: 100, packageId: 'my-plugin' }); ``` @@ -764,9 +742,8 @@ the layout both real hook modules in the repo use. ❌ **DON'T** — do expensive work in `before*` (it blocks the transaction); write business records to another datasource from a `before*` hook through `ctx.api` -(its transaction refuses that write with `CrossDatasourceTransactionWriteError`; -only an append-only ledger, `lifecycle.class` `audit` / `telemetry` / `event`, is -written outside it and survives its rollback); let a hook re-trigger itself; +(its transaction refuses that write with `CrossDatasourceTransactionWriteError`, +except an append-only ledger, as under `api.transaction`); let a hook re-trigger itself; use `object: '*'` unless you mean every object; throw in `after*` unless the failure must abort the operation; react to a refused or rolled-back write from an `async: true` hook, which never runs then — use a sync @@ -828,8 +805,10 @@ export default defineHook({ - For several reasons throw `reasons: [{ reason: 'on_loan', params: { due } }, …]`, not `reason`: one translated line each, filled from its own `params`. `userMessage` joins them by newlines and ends with the entry's `message`, filled from the throw's - top-level `params` (else its holes are empty); the HTTP doors answer - `details.refusals: [{ reason, message }]`, absent for a single `reason`. + `params` (else holes are empty). `@objectstack/rest`'s `/data` routes cut + `userMessage` (a single sentence's too) at 500 characters, so a long list loses its + closing line. They and `/actions` answer `details.refusals: [{ reason, message }]` + uncut (MCP tools relay them as text), absent for a single `reason`. - Translated via `hooks..refusals..message` (or `…..reasons..message`); the thrown text and `status` are unused. - An undeclared code (or none), or a reason missing from a code's `reasons` (a listed diff --git a/.claude/skills/objectstack-data/references/examples-objects.md b/.claude/skills/objectstack-data/references/examples-objects.md index 292c81e..47eca46 100644 --- a/.claude/skills/objectstack-data/references/examples-objects.md +++ b/.claude/skills/objectstack-data/references/examples-objects.md @@ -1,4 +1,28 @@ -# Data — object authoring examples (moved verbatim from SKILL.md) +# Data — object keys, examples, search, extensions + +## Object keys + +Beyond `SKILL.md` § Object Definition. Every key, `enable` flag +(`ObjectCapabilities`) and default: `data/object.zod.ts` +([_index.md](./_index.md)). The ones to get right: + +| Property | Default | Description | +|:--|:--|:--| +| `color` | `gray` | Tile colour behind the white `icon`: `gray` `blue` `teal` `green` `amber` `orange` `red` `pink` `purple` (no hex). Group the app's objects into a few business families, one name each, as the platform's own objects do: people `blue`, security `purple`, approvals and work `orange`, messaging `pink`, integrations `teal`, reference data and finance `green`, audit and settings `amber`. `red` only for an alert object; one nobody opens gets none | +| `highlightFields` | derived | Ordered field keys used as a record's compact face: the columns a **related list** renders on the parent's detail page, and what a lookup picker shows. Declare it on the CHILD object (see [Relationships](../rules/relationships.md)) | +| `nameField` | derived (e.g. `'name'`/`'title'`) | Record-title field: the stored field used as the record's display name. Use a single text/email field; a composite title to import, sort or search by is a stored computed field (a non-`formula` field with an `expression`); a text formula is display-only | +| `ownership` | `'user'` | Whether `owner_id` exists at all, a different axis from `sharingModel` | + +### Object Capabilities (`enable`) + +| Flag | Default | Purpose | +|:--|:--|:--| +| `fieldHistory` | on | A changed field's old → new values on the activity timeline, served per the reader's field read rule. `false`: off for the object. A field opts out with its own `fieldHistory: false`; a media or structured field (`json`, `address`, `code`…) shows values only with `true`, a credential never. `sys_audit_log` keeps its own grant | +| `trackHistory` | `false` | Ledger view on the record page and the `history` API verb; not the values switch | +| `apiMethods` | all | Whitelist over the six primitives (`get`, `list`, `create`, `update`, `delete`, `bulk`); derived verbs (search/export/upsert/…) follow automatically | +| `feeds` | `true` | Feed, comments, mentions; `false` hides the feed UI and rejects new comments | +| `activities` | `true` | Activity timeline (`sys_activity` mirror of CRUD); `false` stops mirroring and hides the timeline | +| `aiReadable` | — | Platform `sys_*` objects only; on an app object, `false` included, refused at parse | ## Field Groups (MVP) @@ -190,3 +214,92 @@ agents, tools, skills, reports, email-templates). Enforcement: `PUT`/`DELETE` on `/api/v1/meta/:type/:name` return `403 item_locked`, and an artifact lock overrides a package lock. Default to **no** `protection` block for tenant-authored metadata. + +## Search Fields (`searchableFields`) + +`searchableFields` on the object is the canonical set `$search` scans. +Leave it unset and search auto-defaults to the `nameField` plus the object's +short-text and enum columns (`text` / `email` / `phone` / `url` / `autonumber` / +`textarea` / `markdown` / `select`) plus every field marked `searchable: true`, +of any type except `secret` / `password` / `vector` or a virtual `formula`. `searchable: false`, the +default, never removes a field the type default scans; declare +`searchableFields` to choose the set. Views may narrow it, never widen it. + +### ⛔ Searching by a related record's title — mirror the value, always + +`$search` scans **the queried object's own columns**. A dotted path is never a +search target: unlike `fields` / `sort` / `filters`, the search axis does not +resolve traversal, and `project_id.name` in `searchableFields` (or in a +`$searchFields` override) is **refused** (`os validate` +`searchable-field-unknown`; a request, `400 INVALID_FIELD`). + +**The one prescription** (`SKILL.md` trap 2), for a task list searched by project name: + +```typescript +{ + name: 'task', + enable: { searchable: true }, + fields: { + name: { type: 'text', required: true }, + project_id: { type: 'lookup', reference: 'project' }, + project_name: { type: 'text', label: 'Project Name' }, + }, + searchableFields: ['name', 'project_name'], +} +``` + +`?search=apollo` expands to `name $contains 'apollo' OR project_name $contains +'apollo'` — one single-table scan, every driver. + +❌ **Never mirror onto a `formula` field.** It is *virtual* (no column to scan) +and CEL reads only this record's own fields, so it cannot hold the related title; +a `formula` entry in any `searchableFields` is refused — `os validate` +`searchable-field-unsearchable`, a request `400 INVALID_FIELD`. + +**Mirror maintenance is the trade-off.** Cover both paths: a `beforeInsert` / `beforeUpdate` hook on `task` +stamps `project_name` from the incoming `project_id`'s parent; an `afterUpdate` +hook on `project` re-stamps its tasks when it is renamed. Rows written past the hooks (bulk import, direct SQL) need a +one-off backfill. See [Lifecycle Hooks](./data-hooks.md). + +## Object Extension Model + +To add fields/validations/indexes to an object you do not own, author +`defineObjectExtension({ extend, fields, fieldPatches, place, priority })` and register it on +`defineStack({ objectExtensions: [...] })`. `priority` sets merge order (default +`200`, `0–999`); an extension adds, never removes, except that a new +`label` without `pluralLabel` clears the base plural unless a tenant authored it (set both). ⛔ `extend` +is not object-level `ownership` (`'user' | 'business_unit' | 'org' | 'none'`). + +`place: [{ field: 'tax_id', group: 'basic', after: 'industry' }, { list: 'acme_contract', after: 'crm_opportunity' }]` +puts the extension's own fields, groups (`{ group: { key, label }, after }`) and child lists +after (or `before`) a named item, where the target declares `fieldGroups` / `relatedLists`. + +**A `fieldPatches` patch** (`SKILL.md` trap 3) carries display keys only: +`label`, `description`, `inlineHelpText`, +`placeholder`, and an option's `label` keyed by its stored `value`; the type, +values and rules stay the owner's. A key the tenant edited keeps the tenant's +text; between two extensions the higher `priority` wins. A patch naming a field +or option value the target lacks is refused at install and by `os validate`, and +a `picklist`-bound field's options are never patchable. Example: +`defineObjectExtension({ extend: 'crm_account', fieldPatches: { industry: { label: 'Sector' }, type: { options: { customer: { label: 'Client' } } } } })`. +Translate patched text in the patching package's `translations`, under the +owner's keys (`objects.crm_account.fields.industry.label`, `.help`, +`.options.`): the owner's translation of the replaced text never applies, a +pair `.custom` translation comes first on `/meta`, and an untranslated locale +serves the patch text. + +**An object an installed package ships** is extended from the +base's paired `.custom` package (`hotcrm.custom`; **objectstack-platform** +§ Customizing an installed package), never replaced: it takes no `overrides` +declaration. Every field the pair adds ends in `__c` (`region__c`). The suffix is +reserved to the pair, so a `__c` field in any other package, or an unsuffixed +field in a `.custom` extension, is refused at save, publish and install and by +`os validate` / `os build`. +Only the pair's extension also writes `fieldGroups`, `relatedLists` and `actionLayout` +(**objectstack-ui**), shaped as on an object. A written key replaces that arrangement +whole (the owner's and every `place`; `actionLayout`, each arm it writes): an unlisted +field shows after the last group, an unnamed tab after the listed ones, and +`{ list: 'crm_note', hidden: true }` hides a tab. Outside a `.custom` package they are +refused at those doors: use `place`, or for an action its own `locations` and `order`. +Studio's **Add field** on a base object writes the same extension, as an +`object_extension` item of the pair. diff --git a/.claude/skills/objectstack-data/rules/field-types.md b/.claude/skills/objectstack-data/rules/field-types.md index 8d9e4b5..b2eed5c 100644 --- a/.claude/skills/objectstack-data/rules/field-types.md +++ b/.claude/skills/objectstack-data/rules/field-types.md @@ -271,3 +271,48 @@ The `format` is literal text interleaved with `{...}` tokens: 2. **Put a delimiter between adjacent variable tokens** — `{section}-{zone}{000}`, not `{section}{zone}{000}`. Without one, `('AB','C')` and `('A','BC')` both render prefix `ABC` and share a counter (to keep numbers unique). 3. **Pad width is a MINIMUM, not a cap.** `{000}` → `001`…`999`, then `1000`. 4. **Only known tokens are interpolated.** Date tokens are **case-sensitive** — `{yyyy}` parses as a `{field}` reference and renders **empty** (rule 1 applies). Only a spelling no field could have — `{ YYYY }`, `{YYYY-MM}` — is emitted **literally**. + +## Choosing a type + +Beyond `SKILL.md` § Field Type Selection (`secret` is encrypted at rest per +ADR-0100): + +- A yes/no flag, `{ type: 'boolean', defaultValue: false }`, is any `is_*`, + `has_*`, "done?" or "active?". An unchecked box is + a value. A box that must be checked (terms, consent) is the rule + `{ name: 'terms', type: 'script', + condition: { dialect: 'cel', source: 'record.accepted != true' }, message: 'Accept the terms.' }`. + The `false` default also lands seeded or imported rows that omit the column on + `false`, not a null that only looks unchecked. +- A person (approver, reviewer) stays optional because the platform already + stamps the owner and `created_by`. +- A dynamic default may also be `'NOW()'` or a CEL envelope. Whether a create + form pre-displays it is a client capability you cannot promise. + +## Changing a field that has data + +Beyond `SKILL.md` trap 1 (the sync only adds; the column wins at write time): + +| Change | Existing DB on restart | +|--|--| +| add object / field / index | ✅ applied automatically | +| `storage: { notNull: true }` removed (relax `NOT NULL`) | ⚠️ **never auto-applied** — the drift is `category: 'needs_confirm'` (`relax_not_null`), so `os migrate apply` confirms it | +| `unique` re-scoped global → per-tenant | dev auto-heals; otherwise `os migrate apply` (`replace_unique_index`) | +| type / length change, drop field | `os migrate apply` (`--allow-destructive` for drops / tightenings) | +| rename a field | `renamedFrom: ['old_key']` on the new key: the sync carries the column's values | +| declared index removed, or its columns changed | `os migrate apply` (`--allow-destructive` when it drops, or rebuilds as `UNIQUE`) | + +**`required` is not the `NOT NULL` dial.** `required` is the +**write contract** — the engine refuses an insert that omits the value — and it +implies nothing about the column. The physical constraint is a separate explicit +opt-in, `storage: { notNull: true }`, and it is what drift detection compares +against. So tightening `required` on a deployed object is safe (existing null +rows stay readable), while declaring `storage.notNull` over null rows is a +destructive migration. The two cannot be combined with `requiredWhen`. + +Tell-tale: `/meta` reports a field optional (no `required`, no `storage.notNull`) +but writes that omit it fail with a **raw driver error** rather than a clean +validation 400 — that is a stale `NOT NULL` column, not a validator bug. Run +`os migrate plan` to preview and `os migrate apply` to reconcile, or ratify the +column by declaring `storage: { notNull: true }`. CLI details: see +**objectstack-platform**. diff --git a/.claude/skills/objectstack-data/rules/lifecycle.md b/.claude/skills/objectstack-data/rules/lifecycle.md index f2372b2..420fe3d 100644 --- a/.claude/skills/objectstack-data/rules/lifecycle.md +++ b/.claude/skills/objectstack-data/rules/lifecycle.md @@ -17,8 +17,8 @@ expired rows under a system context, and reclaims driver space. ## Lifecycle Classes | Class | Contract | Typical use | -|:------|:---------|:------------| -| `record` | Business truth — permanent; policies FORBIDDEN | accounts, orders, invoices | +|:-|:-|:-| +| `record` | Business truth — permanent; policies FORBIDDEN | accounts, orders | | `audit` | Compliance ledger — retain → archive → delete | audit trails | | `telemetry` | High-frequency log — rotation / short retention | activity streams, run history | | `transient` | Ephemeral state — TTL auto-expire | receipts, codes, sessions | @@ -34,58 +34,33 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; export const ApiCallLog = ObjectSchema.create({ name: 'api_call_log', sharingModel: 'private', - lifecycle: { - class: 'telemetry', - retention: { maxAge: '14d' }, // reap past 14 days (created_at) - storage: { strategy: 'rotation', shards: 14, unit: 'day' }, - }, - fields: { - endpoint: Field.text({}), - status: Field.number({}), - }, + // reap past 14 days (created_at) + lifecycle: { class: 'telemetry', retention: { maxAge: '14d' }, storage: { strategy: 'rotation', shards: 14, unit: 'day' } }, + fields: { endpoint: Field.text({}), status: Field.number({}) }, }); // ✅ Ephemeral token: TTL on its own expiry field export const ImportTicket = ObjectSchema.create({ name: 'import_ticket', sharingModel: 'private', - lifecycle: { - class: 'transient', - ttl: { field: 'expires_at', expireAfter: '1d' }, // reap 1 day after expires_at - }, - fields: { - expires_at: Field.datetime({}), - }, + // reap 1 day after expires_at + lifecycle: { class: 'transient', ttl: { field: 'expires_at', expireAfter: '1d' } }, + fields: { expires_at: Field.datetime({}) }, }); // ✅ Compliance ledger: hot window, then cold storage export const ConsentLog = ObjectSchema.create({ name: 'consent_log', sharingModel: 'private', - lifecycle: { - class: 'audit', - retention: { maxAge: '90d' }, - archive: { after: '90d', to: 'archive', keep: '7y' }, - }, - fields: { - subject: Field.text({}), - }, + lifecycle: { class: 'audit', retention: { maxAge: '90d' }, archive: { after: '90d', to: 'archive', keep: '7y' } }, + fields: { subject: Field.text({}) }, }); -// ✅ MIXED table: terminal history is telemetry, but paused rows are live -// workflow state — `onlyWhen` scopes the age sweep to the declared filter +// ✅ Mixed table: paused rows are live workflow state — `onlyWhen` scopes the age sweep export const AutomationRun = ObjectSchema.create({ name: 'sys_automation_run', - lifecycle: { - class: 'telemetry', - retention: { - maxAge: '30d', - onlyWhen: { status: { $in: ['completed', 'failed'] } }, - }, - }, - fields: { - status: Field.select(['running', 'paused', 'completed', 'failed'], {}), - }, + lifecycle: { class: 'telemetry', retention: { maxAge: '30d', onlyWhen: { status: { $in: ['completed', 'failed'] } } } }, + fields: { status: Field.select(['running', 'paused', 'completed', 'failed'], {}) }, }); ``` @@ -100,20 +75,15 @@ lifecycle: { class: 'telemetry' } // ❌ archive.after must equal retention.maxAge lifecycle: { class: 'audit', retention: { maxAge: '90d' }, archive: { after: '30d', to: 'archive' } } -// ❌ onlyWhen + rotation/archive — shard DROPs and the Archiver act on age -// alone and would destroy/move rows the filter protects -lifecycle: { - class: 'telemetry', - retention: { maxAge: '14d', onlyWhen: { status: 'done' } }, - storage: { strategy: 'rotation', shards: 14, unit: 'day' }, -} +// ❌ onlyWhen + rotation/archive: both act on age alone, destroying/moving rows the filter protects +lifecycle: { class: 'telemetry', retention: { maxAge: '14d', onlyWhen: { status: 'done' } }, storage: { strategy: 'rotation', shards: 14, unit: 'day' } } ``` ## Safety Semantics - **Archive-then-delete**: an object declaring `archive` is never - hot-deleted before the copy to the archive datasource succeeded. If no - datasource is registered under the `archive.to` name, rows are retained. + hot-deleted before the copy to the archive datasource succeeded. No + datasource registered under the `archive.to` name ⇒ rows are retained. - **Rotation** time-shards the table on SQLite (writes hit the current shard, reads go through a view under the object's name, expired shards are DROPped). Other dialects enforce the same window with an @@ -123,39 +93,38 @@ lifecycle: { ## Sealing (`seal`) -`seal` makes an `audit` ledger tamper-evident (ADR-0154): an edit, insert or -delete outside the platform breaks its signed checkpoints. Ten minutes after each `created_at` -hour, `@objectstack/plugin-audit` signs its rows into a chained checkpoint -per organization (`tenant_id`; rows with none share a deployment chain); late -rows get a `late` checkpoint. Columns enter in clear, `valueFields` as salted -commitments. +`seal` makes an `audit` ledger tamper-evident (ADR-0154): `os audit verify` +(read-only) exits with code 1 on a changed, missing or unsealed row or a chain fault (a +link, a signature, a row `listed_twice`). + +Ten minutes after each `created_at` hour, `@objectstack/plugin-audit` signs +its rows, per organization chain (plus one chain for rows about no +organization), into one checkpoint, or consecutive checkpoints of at most +10,000 rows; late rows get a `late` checkpoint. Columns enter in clear, +`valueFields` as salted commitments. + +`chainField` (optional, default `tenant_id`) names the chain column: a text +or lookup column holding the organization id, e.g. the injected +`organization_id`. Fixed once checkpoints exist: a change reads `listed_twice`. ```typescript import { ObjectSchema, Field } from '@objectstack/spec/data'; -// ✅ The sealer needs declared `id` and `tenant_id` +// ✅ The sealer needs declared `id` and `tenant_id` (stamped on insert) export const PolicyChangeLog = ObjectSchema.create({ name: 'policy_change_log', sharingModel: 'private', lifecycle: { class: 'audit', retention: { maxAge: '1y' }, seal: { valueFields: ['new_value'] } }, - fields: { - id: Field.text({}), - tenant_id: Field.lookup('sys_organization', {}), // stamped on insert - new_value: Field.textarea({}), - }, + fields: { id: Field.text({}), tenant_id: Field.lookup('sys_organization', {}), new_value: Field.textarea({}) }, }); ``` -```typescript -// ❌ Refused at parse time: id / created_at order the leaves -seal: { valueFields: ['created_at'] } -``` - -Also refused: `seal` off class `audit`, an undeclared `valueFields` name, no -text `tenant_id` outside `valueFields` (or `chainField: 'organization_id'`), -and beside `seal` any `onlyWhen`, a `ttl` not on `created_at`, or rotation -`storage`. Unsealed, `error` hourly: no declared `id`; a `password`, +Refused at parse: `seal` off class `audit`, a `valueFields` name that is +undeclared, `id` or `created_at` (they order the leaves), a chain column (`chainField`, else `tenant_id`) the object lacks or that +cannot name an organization (not one text value, `id`, `created_at`, or in +`valueFields`), and beside `seal` any `onlyWhen`, a `ttl` not on +`created_at`, or rotation `storage`. Unsealed, `error` hourly: no declared `id`; a `password`, `secret`, `formula`, `summary`, `image`, `file`, `avatar`, `video` or `audio` column; no `cryptoProvider` on `AuditPlugin`. @@ -169,9 +138,9 @@ runtime) the sweeper still deletes sealed rows, which then read as missing. ## Operations | Knob | Where | Effect | -|:-----|:------|:-------| +|:-|:-|:-| | `enabled` | `lifecycle` settings namespace | Runtime master switch | -| `retention_overrides` | settings, **tenant-scoped** | Per-object window overrides — a regulated tenant sets `'2y'` while dev keeps days; sealed objects: see § Sealing | +| `retention_overrides` | settings, **tenant-scoped** | Per-object window overrides; sealed objects: see § Sealing | | `quotas` / `quota_defaults` | settings | Row ceilings; breaches ALERT (never delete beyond declared policy) | | `growth_alert_rows` | settings | Per-sweep growth spike alert | | `OS_LIFECYCLE_DISABLED=1` | env | Disables sweeping entirely | diff --git a/.claude/skills/objectstack-data/rules/relationships.md b/.claude/skills/objectstack-data/rules/relationships.md index 3cfaff1..32848e7 100644 --- a/.claude/skills/objectstack-data/rules/relationships.md +++ b/.claude/skills/objectstack-data/rules/relationships.md @@ -11,7 +11,7 @@ | Type | Lifecycle | Required | Sharing | Roll-ups | Use Case | |:-----|:----------|:---------|:--------|:---------|:---------| | `lookup` | Independent | Optional by default | Independent | Via `summary` | "Related to" | -| `master_detail` | Coupled (cascade delete) | Forced only under `controlled_by_parent`, unless the optional master (below); else lint-warned | Inherits parent; read-on-master opt-ins (below) | Via `summary` | "Owned by" | +| `master_detail` | Coupled | Forced only under `controlled_by_parent`, unless the optional master (below); else lint-warned | Inherits parent; read-on-master opt-ins (below) | Via `summary` | "Owned by" | | `tree` | Self-reference | Optional — and so is `reference`, which when written must name this object itself; any other object is refused at parse, not lint-warned | N/A | Not available | Hierarchical | ## Patterns @@ -188,7 +188,7 @@ transaction. } ``` -`object` is the child object to aggregate, `field` its field (ignored for +`object` is the child object, `field` its field (ignored for `count`), `function` one of `count` / `sum` / `min` / `max` / `avg`. Optional: `filter` (below) and `relationshipField` (omitted: the child's `lookup` / `master_detail` referencing this parent). Refused at publish when omitted and the @@ -254,7 +254,7 @@ and parent + children save in **one atomic transaction**. A parent or child declaring `enable.apiMethods` must list `'bulk'`, or that save is refused `405 OBJECT_API_METHOD_NOT_ALLOWED`. ```typescript -// PARENT `invoice`: the group places the lines and holds no fields +// PARENT `invoice`: the group holds no fields fieldGroups: [{ key: 'lines', label: 'Line Items', relatedList: 'invoice_line' }], // CHILD `invoice_line`: its master_detail FK, declaring no `relatedList` @@ -289,7 +289,7 @@ editable fields, else `grid`. **Modeling a `'grid'` line item for the full editor:** ```typescript -// Parent (a field group names invoice_line, as above) +// Parent Invoice = { fields: { tax_rate: Field.number({ label: 'Tax Rate (%)' }), // → live Subtotal/Tax/Total stack @@ -360,7 +360,8 @@ audit_ref: { type: 'master_detail', reference: 'invoice', relatedList: false }, arrangement re-stating the entry with no `label`, or hiding it, leaves none (a bare child's name, labelled or not, covers each of its `child.field` lists too) and `os validate` refuses the key: drop it, or re-state the entry, shown, with the - owner's `label`. A child in the stack with no inbound FK + owner's `label`, or the arrangement's own, translated at that key in the `.custom` + package's bundle. A child in the stack with no inbound FK is refused everywhere; one that exists nowhere is refused by `os validate` / `os build` (bar a platform or sibling-artifact name) and by a metadata write naming no package (one into a package is stored, placing nothing). @@ -381,3 +382,12 @@ A line item on a `lookup` can exist without its parent: use `master_detail`. No `many_to_many` field type exists: use a junction object. +## Record owner, and other people on a record + +Beyond `SKILL.md` § Relationship Patterns: a handler the request names apart +from the owner is a `user` field that grants no access, with a label +no other visible field carries, injected ones included: `owner_id` (Owner, 负责人), +`created_by` (创建人), `updated_by` (更新人), `created_at` (创建时间), `updated_at` +(更新时间). `ownership: 'none'` only for a shared catalog or a pure junction table. + +A `multiple: true` lookup's ids are referenced positionally (`record.tags[0]` in a flow's CEL). diff --git a/.claude/skills/objectstack-data/rules/security.md b/.claude/skills/objectstack-data/rules/security.md index 191cd5c..39cbcc6 100644 --- a/.claude/skills/objectstack-data/rules/security.md +++ b/.claude/skills/objectstack-data/rules/security.md @@ -173,7 +173,7 @@ rowLevelSecurity: [ a parent's owner, parent optional → an optional master (relationships.md); one record, once → a sharing rule or a manual share; a team's records → a sharing rule whose `sharedWith: { type: 'queue', value: '' }` - reaches an ownership queue's members (SKILL.md § Ownership queues). + reaches an ownership queue's members (§ Ownership queues below). - A package's rule reads `value` as its package's queue, else the one holder in its declared `dependencies` closure plus `sys`, else (none declares it) an org's `sys_queue` row. Else it grants no one new, warned @@ -192,7 +192,7 @@ rowLevelSecurity: [ in its declared `dependencies` closure plus `sys`; else it is refused. It still loads; the boot's catalog reference report logs each refusal with every candidate, and the position grants nothing through that name (its other sets - still do). `outside-closure` / `ambiguous-in-closure` as for a queue above + still do). The two closure refusals are as for a queue above (the environment: a set authored in Setup; a second package shipping a name is refused at install). Fix: declare the dependency. Stored grants, environment-authored positions, admin overlays of a package position and the @@ -347,3 +347,42 @@ references by table (sharing, queue and share recipients, pending approvers, invitations) for an admin. Not carried (warned): an old name still a position anywhere, claimed twice, recorded under another owner (a package or the environment), switched off, or a disabled claimant. + +## Access depth — `readScope` / `writeScope` + +Beyond `SKILL.md` § Access depth: a scope +widens the owner match declaratively instead of a hand-written RLS policy +(ADR-0057 D1): it resolves at request time into an `owner_id IN (…)` set and +AND-injects like RLS. Open-core boundary ADR-0016: the plugin goes in +`plugins[]`, and `defineStack` errors unless the stack declares +`requires: ['hierarchy-security']`. The CLI only advises on a +missing or unwired plugin: `os validate` warns, `os verify --json` lists it in +`capabilities`. + +## Ownership queues — park a record for a team to claim + +Every `ownership: 'user'` object carries a platform-injected `queue` column +beside `owner_id` (an object declaring its own `queue` field is refused). A +record **sits in** a queue when `owner_id` is empty and `queue` names it: the +queue's members read and edit it (rows widen, verbs never — no delete). Declare +the queue on the stack; a declared queue's members are positions only, an +organization adds users and teams through `sys_queue_member` rows: + + +```typescript +import { defineQueue } from '@objectstack/spec/security'; + +export const supportIntake = defineQueue({ + name: 'crm_support_intake', // the one name the `queue` column, a rule, an approver and a sharing recipient use + label: 'Support Intake', + members: [{ type: 'position', value: 'crm_service_agent' }], +}); +// defineStack({ queues: [supportIntake], assignmentRules: [...] }) — routing rows in: objectstack-automation +``` + +**Claim** is an ordinary by-id update, `{ owner_id: }`, admitted to a +member while the record is unowned; one writer wins, the other gets `409 +CONCURRENT_UPDATE`. **Release**: the owner writes `owner_id: null` and the record +sits in its home queue again. **Move**: writing another `queue` is a transfer +(`allowTransfer` or `modifyAllRecords`). ⛔ Never a per-record `assigned_to` +picklist, a round-robin counter field, or a hook that picks an owner. diff --git a/.claude/skills/objectstack-data/rules/validation.md b/.claude/skills/objectstack-data/rules/validation.md index 4eb1d43..be92231 100644 --- a/.claude/skills/objectstack-data/rules/validation.md +++ b/.claude/skills/objectstack-data/rules/validation.md @@ -3,8 +3,7 @@ - [Available Rule Types](#available-rule-types) · [Expression Syntax](#expression-syntax) · [Script Validation](#script-validation) - [Uniqueness — Use Unique Indexes](#uniqueness--use-unique-indexes) · [State Machine Validation](#state-machine-validation) - [Format](#format-validation) · [Cross-Field](#cross-field-validation) · [JSON Schema](#json-schema-validation) · [Conditional](#conditional-validation) -- [External / Custom Validation → Lifecycle Hooks](#external--custom-validation--lifecycle-hooks) · [Validation Properties](#validation-properties) -- [Incorrect vs Correct](#incorrect-vs-correct) +- [External / Custom Validation → Lifecycle Hooks](#external--custom-validation--lifecycle-hooks) · [Messages](#messages--record-values-in-holes) · [Validation Properties](#validation-properties) Unmarked blocks are fragments; `check:skill-examples` skips them. @@ -48,8 +47,7 @@ exemption, so a row that already violates the rule is refused on any edit until a repairing write lands (frozen, not bricked). A condition that must hold only from a transition onward is not this tool: use `requiredWhen` or a field bound (`min` / `max` / `minLength` / `maxLength`), which judge the write, not the -stored row (see **Choose by intent — invariant or transition gate** in -`SKILL.md`). +stored row (`SKILL.md` § Conditional Field Rules). ```typescript @@ -103,7 +101,8 @@ driver layer. See [indexing.md](./indexing.md) for index options. A `validations[]` entry. `initialStates` holds the one state a record may be CREATED in; publish refuses a machine without it (`state-machine-no-initial-states`) unless it is update-only -(`events: ['update']`). `[]` marks a terminal state: +(`events: ['update']`). `[]` marks a terminal state; `transitions` keys and +values are option `value`s, never labels: ```json { @@ -198,25 +197,6 @@ is a **single** nested rule applied when it holds, `otherwise` (optional) a single rule applied when it doesn't. There is no `validations: []` array — compose multiple checks as multiple top-level rules or nested conditionals. -```typescript -validations: [ - { - name: 'enterprise_requires_manager', - type: 'conditional', - when: P`record.type == 'enterprise'`, - message: 'Enterprise account validation', - then: { - name: 'manager_required', - type: 'script', - condition: P`isBlank(record.account_manager)`, - message: 'Enterprise accounts must have an account manager', - }, - }, -] -``` - -With an `otherwise` branch: - ```typescript { name: 'payment_validation', @@ -267,6 +247,32 @@ const taxIdCheck = defineHook({ }); ``` +## Messages — Record Values in Holes + +`message` is a `{{ }}` template: a hole names one of the object's own fields, +one segment deep, under `record` (the record the rule judged) or `previous` +(the stored row before an update; empty on insert), with at most one formatter. + +```typescript +message: 'Total {{ record.total_price | currency }} is below what was received ({{ record.received_amount | currency }}).' +``` + +- Formatters: `number` / `number:2`, `currency` / `currency:EUR`, `percent`, + `date` / `date:long`, `datetime`, `upper`, `lower`, `trim`, `truncate:80`, + `default:'n/a'`. A single-brace `{total}`, a hole through a field + (`{{ record.account.name }}`) or over another root (`{{ user.name }}`) and + logic in a hole are refused by `os validate` and at publish. +- Bare `| currency` formats in the organization's default currency (Setup → + Localization). With none set, that hole renders empty and the server log + names the setting. A field holding its own currency names it: + `| currency:EUR`, or `| number:2`. +- A field the person whose write was refused cannot read, or sees masked, + renders empty, `default:` included. The verdict never depends on the sentence. +- The translation at `objects.._validations..message` takes the + same holes and is filled first; if it does not render, the authored message is + filled instead. +- The sentence is plain text: a value shows as stored, never as markup. + ## Validation Properties ### Severity Levels @@ -303,27 +309,113 @@ priority: 100 // Application validations (default) priority: 1000 // User validations (run last) ``` -## Incorrect vs Correct +## Conditional Field Rules -### ❌ Incorrect — Validation Fires Too Often +A rule that belongs to the data model goes on the **field definition** and +applies everywhere the field is edited: +New and Edit, named and public forms, inline master-detail grids, API writes. + ```typescript -{ - type: 'script', - condition: P`record.status == 'draft'`, - message: 'Record is still in draft', - // ❌ No events — runs on all operations -} +import { P } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; + +export const Invoice = ObjectSchema.create({ + name: 'invoice', + sharingModel: 'public_read_write', + fields: { + status: Field.select({ + options: [ + { label: 'Draft', value: 'draft' }, + { label: 'Sent', value: 'sent' }, + { label: 'Paid', value: 'paid' }, + { label: 'Void', value: 'void' }, + ], + }), + paid_at: Field.datetime({ + visibleWhen: P`record.status == 'paid'`, + requiredWhen: P`record.status == 'paid'`, + }), + locked_total: Field.currency({ + readonlyWhen: P`record.status == 'paid'`, + }), + }, +}); ``` -### ✅ Correct — Validation Scoped to Events +- `showOnCreate: false` keeps a field off every create surface; edit, the + record page and lists keep it. Refused beside `required: true`. +- `readonly`, `readonlyWhen` and the console-only lock: + [Locking a Field](#locking-a-field). +- Use `requiredWhen` for conditional requiredness; the ObjectQL validator + enforces it on submit. The removed `conditionalRequired` alias is a parse + error. +- **Choose by intent — invariant or transition gate** + ([Script Validation](#script-validation), Tool choice). "Required when X" + reads like an invariant and is not one; an invariant written as a gate never + enforces itself. +- For inline `master_detail` grids, predicates are evaluated row-by-row against + the child row's `record`, so line-item rules should live on child fields. +- For complex predicates, load **objectstack-formula** and emit CEL via + `P\`...\``; do not use Salesforce-style `AND`, `IN (...)`, or `{field}` + syntax. + +`os validate` catches a bare field ref (`done` for `record.done`) in any of +these predicates. Unchecked, it faults at run time: an `error` validation rule +or `requiredWhen` refuses the write naming it, an option `visibleWhen` only a +write picking the option (forms still offer it); a `readonlyWhen` field stays +editable and the save succeeds without its change (logged); a formula reads +`null` (logged). + +## Locking a Field + +Two questions pick the key: who is kept out, and when. + +| | Every write | Only a person at the console | +|:--|:--|:--| +| Always | `readonly: true` (system writes pass) | `uiReadonly: true` | +| While a `record.*` predicate is TRUE | `readonlyWhen` | `uiReadonlyWhen` | + ```typescript -{ - name: 'no_draft_publish', - type: 'script', - condition: P`record.status == 'draft'`, - message: 'Cannot publish draft records', - events: ['update'], // ✅ Only validate on update -} +import { P } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; + +export const SalesOrder = ObjectSchema.create({ + name: 'sales_order', + sharingModel: 'public_read_write', + uiReadonlyWhen: P`record.status != 'draft'`, // once confirmed, only actions change the order + fields: { + status: Field.select({ // moved by the Confirm action, never typed + options: [{ label: 'Draft', value: 'draft' }, { label: 'Confirmed', value: 'confirmed' }], + defaultValue: 'draft', + uiReadonly: true, + }), + order_number: Field.text({ readonlyWhen: P`true` }), // set on create, then fixed + notes: Field.textarea({ uiReadonlyWhen: P`false` }), // editable on a confirmed order too + }, +}); ``` + +- **Left column, the server lock: the value is dropped, the write is not + refused.** REST, the UI, an import, a declarative action and a + `runAs:'user'` flow answer success without the change + (`X-ObjectStack-Dropped-Fields` names the field). `readonly: true` lets a + system writer through (a seed, a migration, a system hook, a + `runAs:'system'` flow: + [objectstack-automation → Failure routing & `runAs`](../../objectstack-automation/SKILL.md#failure-routing--runas)), + so keep it on a field automation maintains. `readonlyWhen` holds for + everyone (per permission set: a field permission `when`, + [Security](./security.md)) and is not judged on a create. +- **Right column, the hand lock: forms, inline edit, grid cells and board or + calendar drags do not offer the field, and every write still lands**, + judged by the validations (a `state_machine` on `status`). Under `readonly` + a declarative Confirm's write would be dropped. Not security: whoever may + edit the record can write the field through the API. +- A console create leaves a `uiReadonly` field out: the record takes its + `defaultValue`, and a `required` field without one fails the create. +- On the **object**, `uiReadonlyWhen` locks every field of an existing record. + A field's own `uiReadonly: true` or `uiReadonlyWhen` replaces it; + `uiReadonly: false` does not. +- `uiReadonly` beside `readonly: true` is refused. Only read-only has a `ui` + twin: there is no `uiVisibleWhen`. diff --git a/.claude/skills/objectstack-formula/SKILL.md b/.claude/skills/objectstack-formula/SKILL.md index 919ca24..a58d3cc 100644 --- a/.claude/skills/objectstack-formula/SKILL.md +++ b/.claude/skills/objectstack-formula/SKILL.md @@ -11,475 +11,125 @@ license: Apache-2.0 compatibility: Requires @objectstack/spec 19.x and @objectstack/formula 19.x (CEL) metadata: author: objectstack-ai - version: "19.0.0-next.2" + version: "19.0.0-next.3" domain: expression tags: cel, formula, predicate, condition, validation, visibility, seed-dynamic --- # Expressions (CEL) — ObjectStack Formula Protocol -ObjectStack has **one** expression language across every domain that needs -computation or boolean predicates: **CEL** (Google Common Expression -Language). - -> **Predicates / formulas are bare CEL — never wrap field references in `{…}` -> braces.** The #1 authoring mistake is a condition like -> `{record.rating} >= 4`: in CEL, `{…}` is a **map literal**, so it is a parse -> error. Write bare CEL: `record.rating >= 4`. Braces are *only* for `{{ … }}` -> text templates (see Cron and template surfaces). - ---- - -## Skill Boundaries - -| Need | Use instead | -|:---|:---| -| Define a `type: 'formula'` field | objectstack-data (and embed CEL via `F\`...\``) | -| Define seed records | objectstack-data (use `cel\`...\`` for dynamic dates) | -| Author flow / automation step | objectstack-automation (use `P\`...\`` for `condition`) | -| Author L2 hook body (TS code) | objectstack-data | -| Cron schedule | objectstack-automation | -| SQL fragment | driver-native; not unified into the expression registry | - ---- - -## Core contract - -Every expression in metadata is the same envelope — `dialect` plus `source`, -with optional `ast` and `meta` — declared as `Expression` / `ExpressionInput` in -`shared/expression.zod.ts`. **Three registered dialects**: - -| Dialect | Engine | Purpose | Helper | Example | -|:-----------|:-----------------------|:--------------------------------------------------|:--------------|:---------------------------------------| -| `cel` | `@marcbachmann/cel-js` | Computed values + boolean predicates | `` cel`...` `` / `` F`...` `` / `` P`...` `` | `` cel`record.amount * 1.1` `` | -| `cron` | built-in validator | Recurring schedules | `` cron`...` `` | `` cron`0 6 * * MON` `` | -| `template` | built-in interpolator | `{{path}}` text interpolation (notif/prompt/title) | `` tmpl`...` `` | `` tmpl`Hello {{record.first_name}}` ``| - -There is **no `js` dialect** — it was retired. Procedural JavaScript is -the L2 `ScriptBody { language: 'js' }` authoring surface (hook bodies, mapping -transforms — see objectstack-data), not an expression dialect. - -> **AI authors:** when emitting structured-output JSON for metadata, always -> emit the full envelope `{ dialect, source }` — never a bare string. - ---- - -## CEL syntax cheat-sheet - -| Concept | CEL | -|:---|:---| -| Current record field | `record.first_name` | -| Previous record (update hooks, validation rules) | `previous.status` — §5 | -| Master-detail line item's header | `parent.status` — cell `readonlyWhen` / `requiredWhen` | -| Metadata-editing form row | `data` — the row under edit, repeater rows included | -| Hook input payload | `input.amount` | -| Identity context | `os.user.id`, `os.org.id`, `os.org.tier`, `os.env` | -| Equality | `==` / `!=` | -| Logical | `&&` / `\|\|` / `!` | -| Ternary | `cond ? a : b` | -| String literal | `'abc'` — CEL parses `"abc"` too | -| Membership | `record.region in ['us', 'eu']` | -| Key existence (NOT null-safety) | `has(record.foo)` | -| Null check | `record.foo == null` or `isBlank(record.foo)` | - -**`==` / `!=` between a list field and a scalar literal is refused** (`list-equality`, "list compared -with a scalar": one constant on every row) — `multiselect` / `checkboxes` / `tags`, or `select` / -`radio` / `lookup` / `user` / `file` / `image` with `multiple: true`. Test membership, null-guarded -(`in` faults on `null`) and parenthesised, per site — the `==` rewrite, then the `!=` one: - -```text -record.tags == 'vip' # REFUSED -# evaluated as CEL; has() covers a sparse action row and a null `previous` -(has(record.tags) && record.tags != null && 'vip' in record.tags) -(!has(record.tags) || record.tags == null || !('vip' in record.tags)) -# bare name in a flow condition (has() takes no bare name) -(tags != null && 'vip' in tags) -(tags == null || !('vip' in tags)) -# SharingRule `condition`: compiled to a query filter, where has() and a literal-first `in` do not lower -(record.tags != null && record.tags.contains('vip')) -(record.tags == null || !record.tags.contains('vip')) -``` - -The org context is `{ id, tier }` — there is no `os.org.slug` or `os.org.name`. -The evaluator also binds the current user as `current_user` (alias `user`) per -ADR-0068 — spec field docs write predicates like `current_user.positions`. - -### `has()` is NOT a null check - -Every server-evaluated predicate — validation rules, `requiredWhen`, option -`visibleWhen`, `readonlyWhen`, hook `condition`, the flow trigger record — -reads a `record` (and, where §5 binds it, a `previous`) that is **total over -the object's declared fields**: a declared column the driver never returned -reads as `null`, not as a fault. There `has(record.)` and -`has(previous.)` are uniformly `true`, and `!= null` is the -whole guard. The idiom that reads like a guard is not one: - -```text -# WRONG — both has() calls are true on a NULL row, so this reaches `null < null`, -# CEL has no overload, the predicate aborts and the write is rejected. -has(record.start_date) && has(record.end_date) && record.end_date < record.start_date - -# RIGHT -record.start_date != null && record.end_date != null && record.end_date < record.start_date -``` - -**This is a publish-time rejection, not advice.** `os build` / -`os validate` / `os lint` and the runtime publish gate reject any validation-rule -or hook predicate — and a record-triggered flow's (`triggerType: 'record-*'`) -start `config.condition`, edge `condition` (nested regions too) or `decision` -branch `expression` — that applies an ordering (`< <= > >=`) or arithmetic -(`+ - * / %`) operator to a **declared nullable** field — no `required: true`, -no `defaultValue`, no default option, not a `count` / `sum` roll-up (empty reads -`0`; `min` / `max` / `avg` stay nullable) — unless an explicit `!= null` / `== null` / -`!isBlank()` test dominates it in the same boolean branch. `has()` deliberately -does not satisfy that gate. `has()` over an **undeclared** key stays legal: that -is its use there — telling "absent from this PATCH" apart from "explicitly null". - -**The exception: action `visible` / `disabled` are client-side and sparse.** -They bind the row the client already holds, and that row — a `list_item` row -above all — lacks a key when the column is outside the view's projection, when -field-level security refuses it, or when it was never written (the mongo and -memory drivers). -Reading an absent key faults `No such key`: a `visible` predicate hides the -action, a `disabled` one leaves it refused, silently either way. -There the guard is `has(record.x) && record.x != null`; `has()` alone is enough -beside a literal `==` / `!=`; a nested path takes one `has()` per segment: - -```text -has(record.status) && record.status != 'resolved' -has(record.amount) && record.amount != null && record.amount > 1000 -has(record.viewer) && has(record.viewer.can_approve) && record.viewer.can_approve == true -``` - ---- - -## ObjectStack CEL standard library - -Registered automatically by `@objectstack/formula`, which ships `dist` only. Its exported -`CEL_STDLIB_FUNCTIONS` is the advertised bare-callable subset, pinned by two -tests: every entry resolves at runtime, and this table documents them all. - -**Dates** - -| Function | Returns | Notes | -|:---|:---|:---| -| `now()` | timestamp | Current instant. Pinned per evaluation run; deterministic in build | -| `today()` | timestamp | Reference-timezone **calendar day**, expressed as **UTC midnight** (not plain UTC start-of-day) | -| `daysFromNow(n)` | timestamp | Calendar-day: `today()` + `n` days, at **UTC midnight** (never carries time-of-day) | -| `daysAgo(n)` | timestamp | Calendar-day: `today()` − `n` days, at **UTC midnight** | -| `daysBetween(a, b)` | int | Whole days from `a` to `b` (negative if `b` precedes `a`). `daysBetween(today(), record.due)` = days remaining | -| `addDays(d, n)` | timestamp | Shift **any** date by `n` days (negative ok). `addDays(record.last_service, record.cycle_days)` = next due date | -| `addMonths(d, n)` | timestamp | Shift **any** date by `n` months; clamps to month-end (`addMonths(date('2026-01-31'), 1)` → Feb 28) | -| `date(s)` / `datetime(s)` | timestamp | Parse an ISO date / date-time string to a timestamp | -| `isoDate(t)` / `isoDatetime(t)` | string | Timestamp to UTC ISO text, `2026-10-08` / `2026-10-08T17:55:06.123Z` | - -> **A `date` / `datetime` field is its ISO text.** The build refuses it in a -> timestamp-only call or method (`date-text-call`); wrap it in `date()` first: -> `isoDate(date(record.start_at))`, `date(record.start_date).getFullYear()`. -> `+` with text and ordering against a text literal take the text as is. - -| Want | The build refuses `end - start`, `date + n`, `today() + 30` (they read `null` / `{}`); write | -|:---|:---| -| Inclusive span | `daysBetween(record.start_date, record.end_date) + 1` | -| Shift a date | `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` | -| Tenure in years | `daysBetween(record.hire_date, today()) / 365` | -| Hours between | `double((datetime(record.end_at) - datetime(record.start_at)).getMinutes()) / 60.0` | -| Sub-day offset | `now() + duration("3h")` | - -**Working days** (the organization's working calendar, holidays and make-up days included): -`addWorkingDays(d, n[, code])` is the day `n` working days after `d` (`d` not counted); -`workingDaysBetween(a, b[, code])` its inverse (`b` counted); `addWorkingHours(t, h[, code])` the -instant `h` working hours after `t`. No `code`: the default calendar; a `code` is a quoted literal. -Only in a formula or a stored field's `expression` (refused in rules, flows, defaults, seeds and -filters): to filter, store the due time in a `datetime` field. No default calendar, or a count past -its maintained span, reads null; a stored due time is then blank until the record's next write. - -**Numbers** - -| Function | Returns | Notes | -|:---|:---|:---| -| `abs(x)` | double | Absolute value | -| `round(x)` | int | Round to the nearest integer | -| `floor(x)` / `ceil(x)` | int | Round toward −∞ / +∞ (`floor(-1.2)` = −2, not −1) | -| `min(a, b)` / `max(a, b)` | dyn | Smaller / larger operand (numeric comparison) | -| `rmbUpper(x)` | string | Amount in Chinese capitals, rounded to 分: `rmbUpper(10500.5)` = `壹万零伍佰元伍角`; `''` for null | - -**Strings** - -| Function | Returns | Notes | -|:---|:---|:---| -| `upper(s)` / `lower(s)` | string | Case conversion | -| `trim(s)` | string | Strip surrounding whitespace (`''` for null) | -| `contains(s, sub)` | bool | Substring test | -| `startsWith(s, p)` / `endsWith(s, p)` | bool | Prefix / suffix test | -| `matches(s, re)` | bool | Regex test | -| `joinNonEmpty(list, sep)` | string | Join, dropping null/empty entries | - -**Collections / null-ish** - -| Function | Returns | Notes | -|:---|:---|:---| -| `isBlank(v)` | bool | true for `null`, `undefined`, `''`, `[]` | -| `isEmpty(v)` | bool | true for `null`, `undefined`, empty string / list / map | -| `coalesce(v, fallback)` | dyn | `v` when non-null, else `fallback` | -| `len(v)` | int | Length of a string / list / map | - -**Options** - -| Function | Returns | Notes | -|:---|:---|:---| -| `label(record.f)` | string | A select value's option label in the reader's locale: `'v' + string(record.version_no) + ' · ' + label(record.kind)` reads `v2 · 清稿` (zh-CN), `v2 · Clean` (en-US). Only `record.`; `''` for null or an empty selection. A multi-select (`multiple: true`) reads each selected label in stored order, joined with `, `. A stored (non-formula) field stores the declared label. Formula fields only: in a predicate (validation, visibility, hook) it faults, so compare the stored value | - -Plus CEL built-ins: `has(x)`, `size(x)`, `int(x)`, `string(x)`, `bool(x)`, -`double(x)`, `timestamp(s)` (a full ISO instant only; over a `date` field write -`isoDate(addDays(record.d, n))`, never `+ duration(…)`), `duration(s)`. - -> Receiver methods (`s.split(',')`, -> `list.map(...)`) are called on a value, never bare, and are not in this table; -> four bare primitives (`bytes`, `dyn`, `type`, `uint`) resolve but are withheld -> from the catalogue by an authoring decision — don't reach for them. An UNKNOWN -> function — `PRIOR()`, a legacy `ISBLANK()`, a typo'd `isBlnk()` — **fails -> `os build`** with a "no matching overload" type error, rather than silently -> no-op'ing the predicate at run time. Use `previous.x`, not `PRIOR()`; more in the table below. - ---- - -## Mandatory patterns for AI emission - -The ❌ blocks are wrong on purpose, so `check:skill-examples` skips them. - -### 1. Computed text formula — always coalesce nullable operands - -✅ **Correct** +Every expression in metadata is one envelope, `{ dialect, source }` (`Expression`, +`shared/expression.zod.ts`); a computed value or a condition is **CEL**. Dialects: `cel`, +`cron`, `template`; there is no `js`. + +## First checks + +1. **Version.** Where the installed `@objectstack/spec` version differs from this skill's + `compatibility` line, the installed contract is right. +2. **Read first**: the object's declared fields (every `record.` must be one, and whether + it is nullable decides its guard) and the contract of the key that takes the expression + ([references/_index.md](./references/_index.md)). Never recall a function: the list below + is the advertised bare-callable set; an unknown name fails `os build`. +3. **Bare CEL under a tag**: `F` for a formula field's `expression`, `P` for a predicate, + `cel` for a seed or default value. Never wrap a field reference in braces: `{…}` is a CEL + map literal, a parse error. Structured-output JSON carries the envelope, never a bare + string; a bare-string `defaultValue` is a literal. Salesforce spellings fail the build: + `AND` / `OR` / `NOT` are `&&` / `||` / `!`, `=` / `<>` are `==` / `!=`, `ISBLANK(x)` is + `isBlank(record.x)`, `OLD.x` / `NEW.x` are `previous.x` / `record.x`, a bare field is + `record.field`. +4. **Verify**: `os validate` and `os build` judge every expression in the stack; the + `validate_expression` agent tool judges one before it is saved. ```ts -import { F } from '@objectstack/spec'; -F`coalesce(record.salutation, '') + ' ' - + coalesce(record.first_name, '') + ' ' - + coalesce(record.last_name, '')` -``` - -❌ **Wrong** (CEL throws on null + string) - -```ts -F`record.salutation + ' ' + record.first_name + ' ' + record.last_name` -``` - -### 2. Conditional numeric formula — guard divisor - -✅ +import { F, P, cel } from '@objectstack/spec'; - -```ts -import { F } from '@objectstack/spec'; -F`coalesce(record.cost, 0) > 0 - ? ((coalesce(record.revenue, 0) - record.cost) * 100) / record.cost - : 0.0` -``` - -### 3. Predicate (field rules / visibility / validation) - -✅ - - -```ts -import { P } from '@objectstack/spec'; - -P`record.status == 'qualified'`; +F`coalesce(record.first_name, '') + ' ' + coalesce(record.last_name, '')`; // null + text throws +F`coalesce(record.cost, 0) > 0 ? ((coalesce(record.revenue, 0) - record.cost) * 100) / record.cost : 0.0`; +F`isoDate(date(record.start_at))`; +F`isoDate(addDays(record.due_date, 7))`; +F`'v' + string(record.version_no) + ' · ' + label(record.kind)`; P`record.amount != null && record.amount > 10000 && record.region in ['us', 'eu']`; -P`!isBlank(record.po_number)`; -``` - -Conditional requiredness: [objectstack-data](../objectstack-data/SKILL.md#conditional-field-rules). -Salesforce-flavor (`AND`, `IN (…)`, `NOT(ISBLANK(x))`) fails CEL compile: see the translation table. - -### 4. Dynamic seed value — use `cel\`\`` not `new Date()` - -✅ - - -```ts -import { cel } from '@objectstack/spec'; -const seed = { close_date: cel`daysFromNow(45)`, created_at: cel`now()` }; -``` - -❌ Compile-time evaluation — every customer gets the package author's clock: - -```ts -{ close_date: new Date(Date.now() + 45 * 86400000), created_at: new Date() } +P`previous != null && previous.status != 'escalated' && record.status == 'escalated'`; +const seed = { close_date: cel`daysFromNow(45)` }; ``` -This is the determinism gate: two consecutive `os build` runs produce -byte-identical `dist/objectstack.json` only when every dynamic seed value is -`` cel`...` `` — no `new Date()`, no `Date.now()`, no random or otherwise -impure source. - -### 5. Update hook condition — `previous` vs `record` - -✅ - - -```ts -import { P } from '@objectstack/spec'; -P`previous.status != 'escalated' && record.status == 'escalated'` -``` - -`record` is the record's **state**, not this write's diff: stored row ⊕ -payload, so `record.status == 'escalated'` is true on *every* update of an -already-escalated record. Comparing against `previous` is the only way to say -"just became". - -**Where `previous` is bound, and where it is not:** - -| Surface / event | `previous` | -|:---|:---| -| Update hook `condition` (single-record write), validation rule on update | the stored pre-write row | -| Insert events (`beforeInsert` / `afterInsert`), validation rule on insert | **`null`** — `previous == null \|\| …` judges an insert, `previous != null && …` skips one; a column read off it (`previous.x`) has no value and faults | -| A write to an existing row whose prior state is not in hand | **unbound** — fails closed, so `previous == null` never reads an update as an insert | -| **`after*` hook `condition` / record-change flow trigger on a predicate (`multi: true`) write** | **that row's pre-write row** — a bulk write fires after-hooks once PER MATCHED ROW | -| Validation rule on a predicate bulk update | that row's pre-write row — per row | -| `before*` hook `condition` on a predicate (`multi: true`) write | **that row's pre-write row** — `beforeUpdate` / `beforeDelete` dispatch once PER MATCHED ROW too, each on a single-record-shaped context whose `input.id` names the row (ADR-0058 Addendum II, D1/D2); `record` is that row's state, stored ⊕ payload, as on any update. Only the *payload* stays batch-scoped — see below the table | - -⚠️ **An unevaluable condition ABORTS the operation.** A column read off -`previous` on an insert — like -a typo'd key (`record.stauts`), a retired field, or a comparison CEL has no -overload for — does **not** degrade to "the hook did not fire": it **fails the -write**, with an error naming the hook and the key — `before*` and `after*` -alike, with no `onError` escape (`onError` governs a handler that throws, and -the condition is evaluated before any handler runs). - -**A transition condition needs no special handling for bulk writes.** -Write it once, on a `before*` or an `after*` event, and it means the same thing -whether the write carries an id or a predicate. - -A predicate (`multi: true`) write is N record changes, so every record-scoped -declaration on it is evaluated **per row** — `previous` is that row's own -pre-write state, `record` its real state, not the bare payload (ADR-0058, -bulk-write Addenda I and II). `before*` is no exception to the *condition*; the asymmetry is what a -`before*` handler WRITES: one `updateMany` takes one SET clause, so every row's -dispatch carries the one payload and a rewrite made on any row applies to every -matched row (D3). A rewrite *decided* per row must assign the same key set on -every row, in place — assigned onto the payload object, never a replaced one — -because the engine records the keys each row's chain wrote and refuses the -batch whole, before any write, when two rows disagree -(`MULTI_UPDATE_HOOK_KEY_DIVERGENCE`, status 400; ADR-0058 Amendment II.3). - -Above 10 000 matched rows the platform refuses a predicate write on an object -with per-row hooks in either phase — one ceiling for `before*` and `after*`, -checked before the first dispatch (ADR-0058 Addendum II, D6) — rather than fan -out that many handler runs inside one write; paginate the write. - ---- - -## Mechanical translation table (legacy → CEL) - -When migrating Salesforce-flavor metadata, apply these rules in order: - -| Legacy | CEL | -|:---|:---| -| `bare_field` | `record.bare_field` — except in a flow condition, below | -| `OLD.x` | `previous.x` | -| `NEW.x` | `record.x` | -| `=` (comparison) | `==` | -| `<>` | `!=` | -| `AND` | `&&` | -| `OR` | `\|\|` | -| `NOT(x)` | `!x` | -| `IF(c, a, b)` | `c ? a : b` | -| `ISBLANK(x)` | `isBlank(record.x)` | -| `CONCAT(a, b)` | `coalesce(a, '') + coalesce(b, '')` | -| `TODAY()` / `NOW()` | `today()` / `now()` | -| `IN (a, b, c)` | `in [a, b, c]` | -| `ISCHANGED(x)` | `previous.x != record.x` | -| `MONTH_DIFF`, `MID`, `LEFT`, `RIGHT`, `SUBSTITUTE` | _not in stdlib — propose addition_ | - -> ⚠️ **Flow conditions are the exception to row 1.** The engine spreads the -> trigger record's fields, nulls included, to top level wherever no flow variable -> or node id holds the name, so in a start, edge or `decision` condition a bare -> `budget` IS `record.budget`: `os validate` judges either spelling (bare names -> only while the flow's bound names are provable) and a guard on one guards both. -> What the start condition proves non-null is presumed at every edge and branch; -> spell that guard `record.budget != null` — the runtime publish gate judges the -> written flow alone and resolves no bare name. An unguarded null fails the -> **run** at that condition; the write that fired it still lands. - ---- - -## Surfaces that take an Expression - -All of these spec fields accept `string | Expression`. The build normalizes -to the envelope. - -### CEL surfaces (predicates + computed values) - -| Surface | Field | Dialect | -|:---|:---|:---| -| `Field` | `expression` (when `type: 'formula'`) | cel | -| `Field` | `visibleWhen` / `readonlyWhen` / `requiredWhen` | cel | -| `View` / `Page` | `visibleWhen` (form section/field, page component) | cel | -| `Field` | `defaultValue` (envelope only; bare string = literal) | cel | -| `ConditionalValidation` | `when` | cel | -| `Action` | `visible` / `disabled` — client-side, sparse | cel (or boolean) | -| `Hook` | `condition` | cel | -| `SharingRule` | `condition` | cel | -| `Flow.decision` | `expression` / edge `condition` | cel (use `vars..`) | -| `Seed.records[*]` | any value | cel (via `cel\`\``) | -| `audit` / `metrics` / `tracing` | `condition` / `successCriteria` | structured \| cel | - -⚠️ **A `formula` field is virtual — no driver materialises a column for it**, so -all three query axes refuse one at both doors: `where` and `searchableFields` -answer `400 INVALID_FIELD`, `orderBy` answers `400 INVALID_SORT`. It still READS -correctly, which is why refusing matters: a `where` on one used to answer -`200` with zero rows. Denormalise onto a stored field and query that. `summary` -and `autonumber` have real columns and need no such care. - -⚠️ **A form-view `visibleWhen` is the one predicate here that faults OPEN.** It -is CLIENT-SIDE only, and an unbound root falls back to `true`, so the control -renders for everyone — never use one as access control; that is permission-set -field-level security. Everywhere else on this table the opposite holds: an -unevaluable `Hook` `condition` or validation predicate **aborts the write** -(§5); a `SharingRule` `condition` that does not lower to a filter fails the -build, and at runtime the rule is skipped and grants nothing (one WARN). - -View list filters are **not** a CEL surface — they are structured JSON filter -rules (`ViewFilterRuleSchema`), so do not emit CEL there. For "last 30 days" -style windows use the **date macro tokens** (`data/date-macros.zod.ts`) — -objectstack-query `rules/filters.md` has the token list. - -### Cron and template surfaces - -Neither dialect is CEL; both take -a bare string (auto-wrapped) or their helper, and read the same variable scope. - -| Dialect | Helper | Grammar | Carriers | -|:---|:---|:---|:---| -| `cron` | `` cron`0 6 * * MON` `` | 5- or 6-field cron, or one of `@yearly` `@annually` `@monthly` `@weekly` `@daily` `@hourly` `@reboot` | `Job.schedule.expression` (canonical) | -| `template` | `` tmpl`Hello {{ record.first_name }}` `` | `{{ path }}` or `{{ path \| formatter[:arg] }}` — double braces only, no conditionals; the formatter whitelist is `TEMPLATE_FORMATTERS`, exported from `@objectstack/formula` | `system/email-template` `subject` / `bodyHtml` / `bodyText`, `ai/model-registry` `promptTemplate.system` / `.user`, `Object.titleFormat` (a save and `os validate` refuse it; move it to `nameField`, ADR-0079) | - -Missing template paths render as the empty string. Move logic into a CEL field. -A `currency` argument is a -literal code (`currency:EUR`); only an email template may read it from the send's -data instead, `{{ amount | currency:@currency_code }}`. - ---- - -## Verify your work - -A malformed expression does not fail silently (ADR-0032): `os validate` and -`os build` run the shared validator over every formula and predicate in the -stack — CEL syntax **plus** `record.` existence on the target object — -and fail non-zero with a located, did-you-mean message, while at runtime the -engine **throws** and the rule fails loudly. Use `os validate` as the fast -post-edit check (no artifact emitted; `npm run validate` in a scaffolded -project). To check a *single* expression before saving it, call the -`validate_expression` agent tool, which runs the same validator inline. - ---- - -## See also - -- [references/_index.md](./references/_index.md) — the Zod schemas behind every - surface above -- `node_modules/@objectstack/spec/src/shared/expression.zod.ts` — `Expression`, - `ExpressionInput`, `cel` / `F` / `P` +## Scope and functions + +Roots: `record`, `previous`, `input` (hook payload), `parent` (a line item's header), `data` (a +metadata-form row), `current_user` (alias `user`), `os.user.id`, `os.org.id`, `os.org.tier` (no +`slug` or `name`), `os.env`; in a flow, `vars..`. + +- Dates: `now()`, `today()`, `daysFromNow(n)`, `daysAgo(n)`, `daysBetween(a, b)`, `addDays(d, n)`, + `addMonths(d, n)`, `date(s)`, `datetime(s)`, `isoDate(t)`, `isoDatetime(t)`, + `addWorkingDays(d, n[, code])`, `workingDaysBetween(a, b[, code])`, `addWorkingHours(t, h[, code])` +- Numbers: `abs(x)`, `round(x)`, `floor(x)`, `ceil(x)`, `min(a, b)`, `max(a, b)`, `rmbUpper(x)` +- Text: `upper(s)`, `lower(s)`, `trim(s)`, `contains(s, sub)`, `startsWith(s, p)`, `endsWith(s, p)`, + `matches(s, re)`, `joinNonEmpty(list, sep)` +- Null-ish: `isBlank(v)`, `isEmpty(v)`, `coalesce(v, fallback)`, `len(v)`. Options: `label(record.f)` +- CEL built-ins: `has(x)`, `size(x)`, `int(x)`, `string(x)`, `bool(x)`, `double(x)`, + `timestamp(s)`, `duration(s)` + +## Traps + +1. **`has()` is not a null check.** A server-evaluated predicate (validation, `requiredWhen`, + `readonlyWhen`, option `visibleWhen`, hook `condition`, a record-triggered flow) reads a + record total over the declared fields: an empty one is `null`, `has(record.f)` is always + true, and the guard is `!= null` or `!isBlank()`: + `record.start_date != null && record.end_date != null && record.end_date < record.start_date`. + The build refuses a validation, hook or record-triggered flow predicate with an ordering or + arithmetic operator on a nullable field (no `required`, no default) and no such test in the + same branch. In a flow condition a bare `budget` is `record.budget` unless a flow variable + or node id holds it; spell the guard `record.budget != null && record.budget > 200000`, or + a null fails the run after the write that fired it has landed. +2. **Action `visible` / `disabled` are the exception.** They read the row the client holds, + where a key can be absent and reading it faults: the action is hidden, or left refused, + silently. Guard `has(record.x) && record.x != null`, one `has()` per segment of a nested + path; `has()` alone is enough beside a literal `==` / `!=`. +3. **A transition compares `previous`.** `record` is the state after the write, true on every + later update too. `previous` is that row's pre-write row, per row on a bulk + (`multi: true`) write (hooks in both phases, validation, record-change triggers); on + insert it is `null`, so `previous.x` faults: write `previous != null && …`. A hook + `condition` that cannot evaluate (a typo'd key, a read off a null `previous`) ABORTS the + write with no `onError` escape. Above 10 000 matched rows a predicate write on an object + with per-row hooks is refused: paginate. +4. **A list field never `==` a scalar.** `record.tags == 'vip'` is refused (`list-equality`) for + `multiselect` / `checkboxes` / `tags` and any `multiple: true` field. Test membership, + null-guarded and parenthesised, per site: + - evaluated as CEL (hook, validation, visibility): `(has(record.tags) && record.tags != null && 'vip' in record.tags)` + - a flow condition's bare name: `(tags != null && 'vip' in tags)` + - a `SharingRule` `condition`, compiled to a query filter where `has()` and a literal-first + `in` do not lower (the build fails): `(record.tags != null && record.tags.contains('vip'))` +5. **A `date` / `datetime` field is its ISO text.** The build refuses it in a timestamp-only + call or method (`date-text-call`); wrap it in `date()` first, as above and in + `date(record.start_date).getFullYear()`. `daysBetween`, `addDays` and `addMonths` take the + field as is. `timestamp(s)` parses a full instant only, never a `date` field. The build + refuses date arithmetic (`end - start`, `date + n`): days remaining is + `daysBetween(today(), record.due)`, `n` days ahead `daysFromNow(n)`, hours + `double((datetime(record.end_at) - datetime(record.start_at)).getMinutes()) / 60.0`, a + sub-day offset `now() + duration("3h")`. +6. **`label()` and the working-day functions are for a formula or a stored field's + `expression`.** `label(record.kind)` reads a select value's option label in the reader's + locale, `''` for null; on a `multiple: true` select, every selected label in stored order + joined with `, `; a stored field stores the declared label. In a predicate it faults: + compare the stored value. The working-day functions (calendar `code` a quoted literal) are + refused anywhere else; with no default calendar, or a count past its maintained span, they + read null. +7. **A dynamic seed value is `` cel`…` ``, never a JavaScript date**: that is evaluated at + build, so every customer gets the author's clock and two builds differ. +8. **A `template` is not CEL.** It is `{{ path }}` or `{{ path | formatter[:arg] }}`: double + braces only, no conditionals, a missing path renders empty; the formatters are + `TEMPLATE_FORMATTERS` (`@objectstack/formula`). `currency` takes a literal code + (`currency:EUR`); only an email template may read it from the send's data, + `{{ amount | currency:@currency_code }}`. + +## Where to go + +| Need | Open | +|:-|:-| +| The envelope and helpers; which keys take an expression | `node_modules/@objectstack/spec/src/shared/expression.zod.ts`, then the key's own schema | +| What a function returns, the cookbook, working days, the legacy table, formatters | https://objectstack.ai/docs/data-modeling/formulas | +| Filter, sort or search: a `formula` field is virtual and all three refuse it (`400`); a view filter is a structured rule or date macro, not CEL | **objectstack-query** | +| Fields, [conditional rules](../objectstack-data/SKILL.md#conditional-field-rules), validation, hooks (per-row rewrites), seeds, sharing | **objectstack-data** | +| Flow conditions, schedules | **objectstack-automation** | +| View and action predicates; a form-view `visibleWhen` is client-side and faults OPEN (it renders for everyone), never access control | **objectstack-ui** | diff --git a/.claude/skills/objectstack-i18n/SKILL.md b/.claude/skills/objectstack-i18n/SKILL.md index 7e8df63..d960c04 100644 --- a/.claude/skills/objectstack-i18n/SKILL.md +++ b/.claude/skills/objectstack-i18n/SKILL.md @@ -11,496 +11,150 @@ license: Apache-2.0 compatibility: Requires @objectstack/spec 19.x (Zod v4 schemas) metadata: author: objectstack-ai - version: "19.0.0-next.2" + version: "19.0.0-next.3" domain: i18n tags: i18n, translation, locale, l10n, bundle, coverage --- # Internationalization — ObjectStack I18n Protocol -## Translation Configuration +## First checks -### Stack-Level I18n Config +1. **Read first**: the stack's `i18n` block and `translations`, the declared names a key + must match, and the contract for any shape, + `node_modules/@objectstack/spec/src/system/translation.zod.ts` + ([references/_index.md](./references/_index.md)). Never recall a key. +2. **Which language is which.** `defaultLocale` is what a user who has not chosen gets; + `sourceLocale` (defaults to it) is the language inline labels are written in, + read by `os lint`, `os i18n check`, `os i18n extract` and label serving; + `supportedLocales` are BCP-47 codes (`ja-JP`); `fallbackLocale` serves a missing + translation. An app authored in English for Chinese users declares + `defaultLocale: 'zh-CN', sourceLocale: 'en'`, not an English `defaultLocale`. +3. **Verify**: `os i18n check` lists missing keys per locale (`--locales=zh-CN`; CI: + `--strict --threshold=95`); `os validate` refuses a key naming nothing the metadata + declares (`translation-target-unknown`). - -```typescript -import { defineStack } from '@objectstack/spec'; +## A bundle -export default defineStack({ - i18n: { - defaultLocale: 'en', - supportedLocales: ['en', 'zh-CN', 'ja-JP', 'es-ES'], - fallbackLocale: 'en', - }, - // translations: [MyTranslations], ← register your bundles here (see below) -}); -``` - -| Property | Type | Required / Default | Description | -|:---------|:-----|:-------------------|:------------| -| `defaultLocale` | `string` | **required** | The locale a user who has not chosen one gets | -| `sourceLocale` | `string` | optional, defaults to `defaultLocale` | The language inline `label:` text is written in: a request in it is served that text; read by `os lint`, `os i18n check`, `os i18n extract` | -| `supportedLocales` | `string[]` | **required** | All supported locales | -| `fallbackLocale` | `string` | optional | Fallback when translation missing | - -An app authored in English for Chinese users declares `defaultLocale: 'zh-CN', sourceLocale: 'en'`, -not an English `defaultLocale`. Validation, delete-restriction and permission-denial messages name fields -and objects in the request's language, as label serving does: an `en` request reads the inline label. -`sourceLanguage`, `authoringLocale` and `authoringLanguage` are refused, each naming `sourceLocale`. - ---- - -## Authoring Translation Bundles (`objects.*`) - -The canonical authoring path: one `TranslationData` per locale, assembled with -`defineTranslationBundle` and registered on the stack: +One `TranslationData` per locale, assembled by `defineTranslationBundle` and registered on +the stack; nothing loads a directory. ```typescript -// src/translations/en.ts — one TranslationData per locale import { defineStack, defineTranslationBundle } from '@objectstack/spec'; import type { TranslationData } from '@objectstack/spec/system'; -const en: TranslationData = { - objects: { - task: { - label: 'Task', - pluralLabel: 'Tasks', - fields: { - subject: { label: 'Subject', help: 'Brief title of the task' }, - status: { - label: 'Status', - options: { - not_started: 'Not Started', - in_progress: 'In Progress', - completed: 'Completed', - }, - }, - }, - _views: { - all_tasks: { - label: 'All Tasks', - emptyState: { title: 'No tasks yet', message: 'Create your first task' }, - }, - }, - _sections: { - details: { label: 'Details' }, - }, - _actions: { - todo_complete: { - label: 'Complete', - confirmText: 'Mark this task as completed?', - successMessage: 'Task completed', - }, - }, - }, - }, - apps: { - todo_app: { label: 'Todo Manager', description: 'Personal task management' }, - }, - messages: { - 'common.save': 'Save', - 'welcome.user': 'Welcome, {{userName}}!', - }, -}; - -// src/translations/zh-CN.ts — same shape, translated values const zhCN: TranslationData = { objects: { task: { label: '任务', - pluralLabel: '任务', - fields: { - subject: { label: '主题', help: '任务的简要标题' }, - status: { - label: '状态', - options: { not_started: '未开始', in_progress: '进行中', completed: '已完成' }, - }, - }, + fields: { status: { label: '状态', options: { in_progress: '进行中' } } }, + _actions: { todo_complete: { label: '完成' } }, }, }, - messages: { - 'common.save': '保存', - 'welcome.user': '欢迎,{{userName}}!', - }, + messages: { 'welcome.user': '欢迎,{{userName}}!' }, }; +const en: TranslationData = { messages: { 'welcome.user': 'Welcome, {{userName}}!' } }; +export const TodoTranslations = defineTranslationBundle({ en, 'zh-CN': zhCN }); -// src/translations/index.ts — assemble the locales into one bundle… -export const TodoTranslations = defineTranslationBundle({ - en, - 'zh-CN': zhCN, -}); - -// objectstack.config.ts — …and register it on the stack export default defineStack({ - i18n: { defaultLocale: 'en', supportedLocales: ['en', 'zh-CN'] }, + i18n: { defaultLocale: 'en', supportedLocales: ['en', 'zh-CN'], fallbackLocale: 'en' }, translations: [TodoTranslations], }); ``` -`defineTranslationBundle` validates the bundle at authoring time via `.parse()` — -prefer it over a bare `: TranslationBundle` literal. - ---- - -## Object-Level Translation Structure - -All translatable content for a single object is aggregated under -`objects.{object_name}` with these sub-keys: - -| Sub-key | Holds | -|:--------|:------| -| `label` / `pluralLabel` / `description` | Object-level text (every key optional) | -| `fields.{field_name}` | `label`, `help`, `placeholder`, `options` (option value → label), `inlineTitle` (the heading of the inline child grid a `master_detail` field draws on its parent's form — the field lives on the child object, so the key is the child's; untranslated it keeps its authored text, never the child's plural label), `relatedListTitle` (likewise, the title of the related list a `lookup` or `master_detail` field draws on its parent's record page) per field | -| `_views.{view_name}` | `label`, `description`, `title` (a form view's own heading — only a form that authors one is translated; a list view has none), `submitBehavior.title` / `submitBehavior.message` (the thank-you panel of a form whose `submitBehavior` is `kind: 'thank-you'`; only the copy the form authors is translated, and the other kinds carry none), `emptyState.title` / `emptyState.message`, `bulkActions.{def_name}` (`label`, `confirmText`, `confirmLabel`, `params`) | -| `_actions.{action_name}` | `label`, `description`, `confirmText`, `submitText` (the param dialog's button verb — only under an action that declares `params`), `cancelText` (the dismiss button of the confirm or param dialog — only under an action that declares `confirmText` or a non-empty `params`), `successMessage`, `disabledReason` (the sentence a greyed action shows; absent keeps the console's default), `params.{param_name}` (and `.options.{value}` beneath it — an option's stored `value` in that param's inline `options`), `outcomeMessages.{outcome}` (an outcome the action's own `outcomeMessages` declares), `resultDialog.title` / `.description` / `.acknowledge` (only under an action that declares a `resultDialog`), `resultDialog.fields.{path}` (the literal `path` of a field in `resultDialog.fields[]`, dots included — `client.secret` is one key), `preflight.fields.{path}` (only under an action that declares `preflight`: a field's literal `path` in its `preflight.fields[]`, its value a plain string as under `resultDialog.fields`), `resultDialog.columns.{path}.{column_path}` / `preflight.columns.{path}.{column_path}` (a table's column headers, beside `fields`: the literal `path` of a `format: 'table'` field, then of one of its `columns[]`, each a plain string; `defineTranslationBundle` refuses any other key under `preflight`, a `title` included); the same keys hold under `globalActions.{action_name}` | -| `_sections.{section_name}` | Form section `label`, `description`; `fields.{field_name}` — the `label`, `placeholder`, `helpText` an entry overrides for that form alone (`helpText` here, `help` under `fields.{field_name}` above: each spells what its source does) | -| `_tabs.{tab_name}` | Filter-preset tab `label` (`ViewTabSchema.name`) | -| `_relatedLists.{list}` | `label` of an object-form `relatedLists` entry on this (parent) object, by its literal `list` (`event.related_to` is one key); an entry with no `label` has no key and keeps the child field's `relatedListTitle`, else the child's plural label. Where the paired `.custom` package's `relatedLists` (**objectstack-data**) re-states the entry without a `label`, or hides it, `os validate` refuses the key: drop it, or re-state the entry, shown, with the owner's own `label`. Spelled `relatedLists`, the group is refused, naming this one | -| `_milestones.{field}.{value}` | `summary`, the timeline sentence of the `activityMilestones` entry firing on that field and value, same `{field}` tokens: composed at read time in the reader's language (a select token as its option label), stored row unchanged, redacted as the stored sentence is | -| `_validations.{rule_name}` | `message` only — the sentence a rejected write returns (replaces the retired `validationMessages`) | -| `_actions.{action_name}.refusals.{CODE}` | `message`, and `reasons.{reason}.message` per declared reason — the sentences of the action's `refusals` catalogue (**objectstack-ui** → Actions), for a code and reason it declares (any other is `translation-target-unknown`); the same under `globalActions.{action_name}` | - -Top-level groups alongside `objects`: `apps` (label, description, navigation), -`messages`, `globalActions` (actions with no `objectName` — a key naming a bound action is -an **error** whose message names the `objects.{owner}._actions.{action_name}` key to write -instead), `picklists` (`label`, `options` by stored value — every field referencing the -picklist inherits them), `dashboards`, `datasets`, `reports`, `pages`, `flows`, `positions`, -`permissions` (permission sets, spelled as the stack's `permissions[]`), `books` (a doc book's -spine, by `Book.name`: `books.{book}.label` / `.description`, and `groups.{group_key}.label` by -each group's stable `key`, never its position — `books.crm_manual.groups.getting_started.label`; -the pages themselves localize through `doc.translations`, and the inline `translations` map a -book once carried stays retired), `mappings` (an import mapping's `label` by its `name`: -`mappings.{mapping}.label`), `metadataForms`, `settingsCommon`; `reports`, `positions` and -`permissions` hold `label` + `description` by name, so do `datasets` and each dataset member at -`datasets.{dataset}.{dimensions,measures}.{member}` (a member's `synonyms` have no key: one -authored list carries every language), and a joined report's block headings sit at -`reports.{report}.blocks.{block_name}.{label,description}`, keyed by the block's required `name`. -Four keys sit deeper than their group's `label`: a `page:tabs` item at -`pages.{page}.components.{tabs_id}.items.{value}.label` (by the item's `value`; an item without -one has no key), an approval step at `flows.{flow}.approvals.{node_id}.label`, any other step's -name at `flows.{flow}.nodes.{node_id}.label` (a screen is named by its heading, -`flows.{flow}.screens.{node_id}.title`, and takes a `nodes` key only beside a `title` of its own; -`os i18n check` asks for a flow's top-level steps, and for one of `FLOW_TECHNICAL_NODE_TYPES` — -`script`, `http`, `connector_action`, `assignment`, `boundary_event`, the four `*_record` types — -only where a decision's branch leads to it), and the text a -`create_record` / `update_record` writes into a field marked `{ dialect: 'template', source }` at -`flows.{flow}.records.{node_id}.fields.{field}`. That text, and each sentence a hook or a `script` -action declares in `texts` and writes through `ctx.text` — `hooks.{hook}.texts.{key}.message`, -`_actions.{action_name}.texts.{key}.message` (also under `globalActions`) — is picked in the -organization's language (the Localization setting if set, else `i18n.defaultLocale`; never the caller's). -`os i18n extract --no-objects-only` scaffolds every group above but `messages` and -`settingsCommon`, all four keys included. The `inlineTitle`, report-block, table-column and -mapping keys, as the shipped `app-crm`, `app-showcase` and platform bundles spell them for `zh-CN` -(`rows` is the table field's `path`, `error.message` one column's): - -```typescript -objects: { crm_opportunity_line_item: { fields: { opportunity: { inlineTitle: '产品明细' } } } }, -reports: { showcase_task_overview: { blocks: { open_block: { label: '未完成任务' } } } }, -objects: { sys_user: { _actions: { import_sso_users: { resultDialog: { columns: { rows: { email: '邮箱', 'error.message': '未添加的原因' } } } } } } }, -mappings: { showcase_inquiry_feed: { label: '询盘导入(营销 CSV)' } }, -``` - -`settings` is **platform-only** — it is keyed by a settings manifest's namespace and only -the platform declares one, so an app bundle carrying it is refused by name. - ---- - -## Naming Conventions - -| Context | Convention | Example | -|:--------|:-----------|:--------| -| Locale codes | BCP-47 | `en`, `en-US`, `zh-CN`, `pt-BR` | -| Object keys in `objects.*` | `snake_case` | `objects.project_task`, `objects.support_case` | -| Field keys | `snake_case` | `fields.first_name`, `fields.due_date` | -| Option values | lowercase | `options.status.in_progress` | -| Message keys | dot-separated | `common.save`, `validation.required` | - -Option sub-keys are the option's stored **`value`**, never its display label: -for `options: [{ value: 'direct_mail', label: 'Direct Mail' }]` write -`options: { direct_mail: '直邮' }` — both `'Direct Mail'` and `'direct-mail'` -parse, ship, and resolve to nothing. - -`os validate` / `os lint` / `os compile` check this direction: `translation-target-unknown` -is an **error** and fails the run; `translation-option-key-unknown` is a warning. -A key naming an object, field, view, tab, action, param, section, validation rule, app, -nav item, dashboard, widget or flow screen that does not exist is listed alongside the names -that do. Six more shapes under an action entry are the error: an outcome the action does -not declare in `outcomeMessages`; a `resultDialog.fields` or `preflight.fields` path it does -not declare; a `columns` key whose field path is no declared `format: 'table'` field, or -whose column path that field's `columns[]` does not list; -`resultDialog` `title` / `description` / `acknowledge` under an action that declares no -`resultDialog`; `submitText` under an action with no non-empty `params`; and `cancelText` -under an action that declares neither `confirmText` nor a non-empty `params` — a bundle -translates a dialog the action declares and cannot add one. A -param's inline option keys share the option warning with a field's `options`; a param that -references a `field` and declares no inline `options` is not judged. - ---- - -## File Organization Strategies - -Layout is an **authoring convention**: whichever one you pick, your own import graph -assembles it into the `TranslationBundle` you register on the stack — nothing loads a -directory tree for you. - -| Layout | Files | Use when | -|:--|:--|:--| -| Bundled | one `crm.translation.ts` holding every locale | under 5 objects, 2-3 locales | -| Per-locale (recommended) | `src/translations/{en,zh-CN,ja-JP}.ts` + `index.ts` | 5-20 objects, 3-5 locales | -| Per-namespace | `i18n/{locale}/{object}.json` | 20+ objects, 5+ locales | - ---- - -## Authoring at Runtime: the `translation` Item - -A **`translation` metadata item** — created in -the Studio, through the metadata API, or by an agent — carries one locale's worth of the -**same** `objects.*` groups documented above plus the `locale` it translates. `locale` is -required, and published items load at boot and on every publish, layering **over** -the file bundles (delete the item and the shipped value returns). Author with `defineTranslation`; -exact Zod shape is `TranslationItemSchema` in -`node_modules/@objectstack/spec/src/system/translation.zod.ts`. - ---- - -## Message Interpolation - -### Simple Format (Default) - -Both shipped adapters substitute -**double-brace** `{{variable}}` placeholders only — single braces pass through -unchanged. (The schema docstring mentions `{variable}` notation, but that is not -what the runtime implements.) - -```json -{ - "messages": { - "welcome": "Welcome, {{userName}}!" - } -} -``` - -### No ICU MessageFormat - -There is no ICU MessageFormat engine. To pluralize, select the form in application code before calling `t()`. - ---- - -## Translation Coverage - -### `os i18n check` - -```bash -os i18n check # every locale found in the config -os i18n check --locales=zh-CN # scope to specific locales -os i18n check --strict --threshold=95 # CI gate: locale parity + minimum coverage -``` - -It compares registered bundles against source metadata and reports missing keys -per locale for every surface the extractor walks. The platform's metadata -forms count only for a stack that ships their translations (`--include-platform` -audits them anyway). Gaps in the source locale are errors, `--strict` promotes -the rest, `--show-keys` lists them all; `os lint --i18n-strict` folds it in. - -### `os i18n extract --check` — freshness, not coverage - -If you commit **generated** bundles (`*.generated.ts` produced by -`os i18n extract`), coverage is only half the gate: - -```bash -os i18n extract --locales=zh-CN,ja-JP --fill=default \ - --out=src/translations --check +With no redeploy, the same groups plus a required `locale` are a **`translation` metadata +item**, in Studio or the metadata API: author with `defineTranslation` +(`TranslationItemSchema`). It loads at boot and on every publish, layered over the file +bundles; delete it and the shipped value returns. + +## Key map + +`{path}`, `{column_path}` and `{list}` are the declared string as one key, dots included +(`'event.related_to'`); `fields.{path}` and `{column_path}` hold plain strings. + +```text +objects.{object}: label, pluralLabel, description + fields.{field}: label, help, placeholder, options.{value}, inlineTitle, relatedListTitle + _views.{view}: label, description, title, emptyState.{title,message}, + submitBehavior.{title,message}, bulkActions.{def} + _actions.{action}: label, description, confirmText, submitText, cancelText, + successMessage, disabledReason, params.{param}(.options.{value}), + outcomeMessages.{outcome}, resultDialog.{title,description,acknowledge}, + resultDialog.fields.{path}, resultDialog.columns.{path}.{column_path}, + preflight.fields.{path}, preflight.columns.{path}.{column_path}, + refusals.{CODE}.message, refusals.{CODE}.reasons.{reason}.message, texts.{key}.message + _sections.{section}: label, description, fields.{field}.{label,placeholder,helpText} + _tabs.{tab}.label, _relatedLists.{list}.label + _milestones.{field}.{value}.summary, _validations.{rule}.message +globalActions.{action}: the _actions keys (an action with no objectName) +apps.{app}: label, description, navigation.{id}.label +picklists.{picklist}: label, options.{value} +reports, positions, datasets, permissions (as the stack's permissions[]): + {name}.label, {name}.description +reports.{report}.blocks.{block_name}.label +datasets.{dataset}.{dimensions,measures}.{member} +books.{book}: label, description, groups.{group_key}.label +mappings.{mapping}.label, packages.{manifest.id}: name, description +pages.{page}.components.{tabs_id}.items.{value}.label +flows.{flow}: approvals.{node_id}.label, screens.{node_id}.title, nodes.{node_id}.label, + records.{node_id}.fields.{field} +hooks.{hook}: texts.{key}.message, and refusals as under _actions +messages: flat dotted ids ('common.save'); dashboards, metadataForms, settingsCommon ``` -`--check` writes nothing. It re-renders what a real extract would produce and -fails if that differs from what is committed in `--out`, naming each stale or -missing file and printing the regenerate command. - -**Use both gates:** renaming a label or removing a spec key leaves coverage at -100% while the bundles go stale. - -It runs in the same **merge mode** as a normal extract, so it never asks for -re-translation: an up-to-date bundle re-extracts byte-identically. Requires `--out`. - -### Diff & Coverage Schemas - -The spec models coverage results for tooling — the return shapes of the optional `getCoverage()` / `suggestTranslations()` (see *Service Contract* below): `TranslationCoverageResult` -(totals, `coveragePercent`, per-group `breakdown`) and `TranslationDiffItem` — -`key` (dot path), `status` (`missing | redundant | stale`), `locale`, optional -`objectName`, optional `sourceHash` for stale detection, and AI-enrichment -fields (`aiSuggested`, `aiConfidence`). Full Zod shape: `TranslationCoverageResultSchema`, -`TranslationDiffItemSchema` (`translation.zod.ts`). - ---- - -## Integration with II18nService - -### Service Contract - -`II18nService` is the kernel service (name `'i18n'`) that loads bundles and -resolves keys with fallback: - -```typescript -import type { II18nService } from '@objectstack/spec/contracts'; -``` - -(Only `src/**/*.zod.ts` ships, so the contract's `.ts` source is not in `node_modules`.) - -Methods both shipped adapters implement (`FileI18nAdapter` from -`@objectstack/service-i18n`, and the in-memory fallback `@objectstack/core` -registers when no i18n plugin is present): - -- **`t(key, locale, params?)`** — dot-path resolution (e.g. `objects.account.label`) - with `{{param}}` interpolation and fallback-locale lookup -- **`getTranslations(locale)`** — a locale's full snapshot -- **`loadTranslations(locale, data)`** — programmatic load (deep-merge) -- **`getLocales()`** / **`setSupportedLocales()`** / **`getDefaultLocale()`** / **`setDefaultLocale()`** / **`getSourceLocale()`** / **`setSourceLocale()`** - -The in-memory fallback additionally resolves locale codes through `resolveLocaleAmong` -(`@objectstack/spec/system`), the one ladder `resolveBundleLocale` also runs: exact → -case-insensitive → same platform-table language (`zh-TW` → `zh-Hant`) → base language -`zh-CN` → `zh` → first registered variant `zh` → `zh-CN`. - -The contract declares optional methods — `getFieldLabels`, `getCoverage`, -`suggestTranslations` — that **no shipped implementation provides**: extension -points for a custom workbench or TMS adapter. - -### Registration - -Don't wire this plugin: `os serve` registers `I18nServicePlugin` itself whenever the -stack config carries `translations` or `i18n` (kernel bootstrap is -**objectstack-platform → Runtime Boot Sequence**). The runtime's HTTP dispatcher, -which `os serve` composes, mounts `GET /api/v1/i18n/locales`, `/translations/:locale` and -`/labels/:object/:locale`, served from the i18n service; the locales -answer marks the default locale (`isDefault`) and names `sourceLocale` (the declared one, else the default). - ---- - -## Server-Composed User Text (`userMessage`) - -Text the server addresses to the end user — `userMessage` on an error envelope, a save / -publish advisory, a 422 or `probes` issue — comes back in the REQUEST's locale, composed where it is -produced; a client renders it as received. - -- **Platform-composed** text follows one ladder over the platform locale table - (`PLATFORM_LOCALES`, `@objectstack/spec/system`): the locale the request names (its - `Accept-Language`, or `?locale` on the REST door), else the workspace default (the - `localization` settings' locale), else `en`. Each code is read whole and then one subtag - shorter at a time (`fr-FR` → `fr`, `zh-Hant-US` → `zh-Hant`), so a Traditional Chinese - code is never handed Simplified text. -- **App-authored** refusal text is not on this ladder: a hook's catalogued refusal is served - through `hooks..refusals..message` (a declared reason's through - `…..reasons..message`), an action's through its `_actions.{action_name}.refusals` - keys (table above), each in the caller's locale, negotiated over - whatever locales the app's translations hold, and otherwise as declared, in the app's own - source language. No `en` floor is supplied for it. Under an entry declaring `params`, a - translation keeps its `{{ name }}` holes; the runtime fills them after picking it. - ---- - -## Translation Workflow Best Practices - -### 1. Extract Skeletons from Metadata - -```bash -os i18n extract --locales=zh-CN --out=./src/translations -``` - -This writes `.objects.generated.ts` TypeScript modules (not JSON), plus a -`.metadata-forms.generated.ts` companion unless `--no-metadata-forms` — -the source locale is filled from schema labels, other locales follow `--fill` -(`empty | default | todo`). `--default-locale` overrides the source locale for one run -(`i18n.sourceLocale`, else `i18n.defaultLocale`, else `en`). `os i18n extract --help` lists -the rest: `--filter`, `--no-merge`, `--dry-run`, `--json`, … - -⚠️ **`--objects-only` is on by DEFAULT**, so extract writes only the `objects` / -`globalActions` subtree while `os i18n check` still asks for the other groups: pass -`--no-objects-only`, or author them by hand. - -### 2. Register - -A **package or plugin shipping its own generated bundle** has one more step than -`defineStack({ translations: [...] })`: a generated module exports an objects *subtree* -(`NonNullable`), not a `TranslationData`, so it must be -wrapped before it is a bundle at all. - -```typescript -// src/translations/index.ts -import { defineTranslationBundle } from '@objectstack/spec'; -import type { TranslationData } from '@objectstack/spec/system'; -import { withSourceFallback } from '@objectstack/platform-objects/apps'; -import { enObjects } from './en.objects.generated.js'; -import { zhCNObjects } from './zh-CN.objects.generated.js'; -import { zhCNGeneratedSourceHashes } from './zh-CN.source-hashes.generated.js'; - -const enSource: TranslationData = { objects: enObjects }; - -export const StorageTranslations = defineTranslationBundle({ - en: enSource, - // 4th argument = the `--source-hashes` companion. Without it a leaf whose SOURCE has - // moved goes on serving the superseded fill under a green `os i18n check` forever. - // The 3rd stays undefined: it judges hand-authored `apps` / `dashboards` / `pages`, - // which a fully generated set does not have. - 'zh-CN': withSourceFallback({ objects: zhCNObjects }, enSource, undefined, zhCNGeneratedSourceHashes), -}); -``` - -A plugin that owns its objects loads that bundle from its own `kernel:ready` hook rather -than registering it on the stack: `i18n.loadTranslations(locale, data)` deep-merges, so -every plugin contributes its own `objects.*` slice. - ---- - -## Shipped examples - -`examples/app-crm` — the bundled layout (`en` + `zh-CN`). -`examples/app-todo` — the per-locale layout. - ---- - -## Common Pitfalls - -### ❌ The Retired `o.*` Shape - -Everything reads `objects.*`. The `o.*` dialect was removed. Both doors reject it, files included. - -```typescript -// WRONG -{ o: { account: { label: '客户' } } } - -// CORRECT (TranslationData) -{ objects: { account: { label: '客户' } } } -``` - -Same rule for its sibling keys: `app` → `apps`, `nav` → -`apps..navigation..label`, `dashboard` → `dashboards`, -`_globalOptions` → `objects..fields..options`, `_meta.locale` → -top-level `locale`, and `_actions.confirmMessage` → `_actions.confirmText`. - ---- - -## Verify your work - -```bash -os i18n check # coverage: which keys are missing, per locale -os validate # the bundle conforms to the protocol schema -``` - -For the build and scaffold -gates see objectstack-platform → **Verify your work**. - ---- - -## 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. - -## See Also - -- **objectstack-data** — For understanding object and field metadata structure -- **objectstack-ui** — For view, app, and action translations -- **objectstack-automation** — For workflow and flow message translations +- `inlineTitle` (the grid a `master_detail` or `lookup` field draws on its parent's form) and + `relatedListTitle` (its related list on the parent's record page) are keys of the CHILD + object, where the field lives: `objects.crm_opportunity_line_item.fields.opportunity.inlineTitle`. + Untranslated, the authored text shows, never the child's plural label. +- `_views.{view}.title` is a form's own heading. `_sections` `fields` is that form's + override: `helpText` there, `help` under `fields.{field}`. +- `columns` is a sibling of `fields`: a `format: 'table'` field's `path`, then a column's + (`resultDialog: { columns: { rows: { email: '邮箱', 'error.message': '原因' } } }`). + `preflight` holds `fields` and `columns` only, no `title`. +- `_relatedLists.{list}` is on the parent, for a `relatedLists` entry that authors a `label`; + one without has no key and shows the child field's `relatedListTitle`, else its plural label. +- A report block is keyed by its `name` + (`reports.showcase_task_overview.blocks.open_block.label`); a `books` group by its stable + `key`, never its position (`books.crm_manual.groups.getting_started.label`); its pages + localize through `doc.translations`. +- A flow step is keyed under `approvals` (approval), `screens` (screen) or `nodes` (any + other). `os i18n check` asks for a technical step (`script`, `http`, `connector_action`, + `assignment`, `boundary_event`, `*_record`) only where a decision's branch leads to it. + +## Traps + +1. **An option key is the stored `value`, never the label.** For + `{ value: 'direct_mail', label: 'Direct Mail' }` write `options: { direct_mail: '直邮' }`; + `'Direct Mail'` and `'direct-mail'` resolve to nothing and only warn. +2. **Double braces only.** `t()` fills `{{variable}}`; a single-brace `{variable}` is left + as written (a milestone `summary` keeps its `{field}` tokens). No ICU + MessageFormat: pick the plural form in code before `t()`. +3. **`os i18n extract --locales=ja-JP --out=./src/translations` writes `objects` / + `globalActions` only** (`--objects-only` defaults on) while `os i18n check` asks for + every group: pass `--no-objects-only` and author `messages` by hand. +4. **Coverage is not freshness.** A renamed label leaves `os i18n check` at 100% while a + committed `*.generated.ts` goes stale; `os i18n extract … --out=… --check` writes nothing + and names each stale file. +5. **A generated module exports an `objects` subtree, not a `TranslationData`**: wrap it, + and pass `withSourceFallback` (`@objectstack/platform-objects/apps`) the `--source-hashes` + companion 4th, or a leaf whose source moved serves the superseded fill under a green check. + With `enSource = { objects: enObjects }`: + `defineTranslationBundle({ en: enSource, 'zh-CN': withSourceFallback({ objects: zhCNObjects }, enSource, undefined, zhCNGeneratedSourceHashes) })`. + A plugin that owns its objects loads its bundle from its own `kernel:ready` hook, + `i18n.loadTranslations(locale, data)`, not on the stack. +6. **Text the server writes is in the organization's language, never the caller's**: a + `ctx.text` sentence (`texts`) and a flow field marked `{ dialect: 'template', source }` + (`records`) use the Localization setting, else `i18n.defaultLocale`. +7. **An app-authored refusal has no `en` floor.** A `refusals` sentence answers in the + caller's locale, negotiated over the locales the app's bundles hold, else as declared. Its + translation keeps the `{{ name }}` holes; the runtime fills them after picking it. + +## Where to go + +| Need | Open | +|:-|:-| +| A key or shape not above | `translation.zod.ts`: `.describe()` text, refusals | +| `II18nService`; no adapter ships its optional `getFieldLabels`, `getCoverage`, `suggestTranslations` | `@objectstack/spec/contracts` | +| Locale resolution and fallback | https://objectstack.ai/docs/protocol/kernel/i18n-standard | +| What a key names; boot | **objectstack-data** (and hooks), **objectstack-ui** (and actions), **objectstack-automation**; **objectstack-platform** | diff --git a/.claude/skills/objectstack-mcp-build/SKILL.md b/.claude/skills/objectstack-mcp-build/SKILL.md index 513f698..bd25a9f 100644 --- a/.claude/skills/objectstack-mcp-build/SKILL.md +++ b/.claude/skills/objectstack-mcp-build/SKILL.md @@ -15,7 +15,7 @@ license: Apache-2.0 compatibility: Requires an environment whose @objectstack/runtime 19.x serves the MCP draft door (none through 18.6.0 does), on a connection granted metadata:write metadata: author: objectstack-ai - version: "19.0.0-next.2" + version: "19.0.0-next.3" domain: process tags: mcp, build, draft, save_metadata_draft, verdict, studio, no-project, 草稿 --- diff --git a/.claude/skills/objectstack-platform/SKILL.md b/.claude/skills/objectstack-platform/SKILL.md index e11ab25..c54be90 100644 --- a/.claude/skills/objectstack-platform/SKILL.md +++ b/.claude/skills/objectstack-platform/SKILL.md @@ -17,18 +17,29 @@ license: Apache-2.0 compatibility: Requires @objectstack/spec 19.x and @objectstack/core 19.x (Zod v4 schemas), Node 22+ metadata: author: objectstack-ai - version: "19.0.0-next.2" + version: "19.0.0-next.3" domain: platform tags: project, defineStack, driver, hono, plugin, kernel, service, requires, capability, DI, lifecycle, cli, deploy, ops --- # 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/.claude/skills/objectstack-platform/evals/config-plugins-ops.json b/.claude/skills/objectstack-platform/evals/config-plugins-ops.json index bdbacba..36eca68 100644 --- a/.claude/skills/objectstack-platform/evals/config-plugins-ops.json +++ b/.claude/skills/objectstack-platform/evals/config-plugins-ops.json @@ -343,9 +343,7 @@ "must_contain": [ "--preset minimal" ], - "must_not_contain": [ - "requires: ['storage', 'settings']" - ] + "must_not_contain": [] } }, { diff --git a/.claude/skills/objectstack-platform/references/bootstrap.md b/.claude/skills/objectstack-platform/references/bootstrap.md index 204e80c..db701f8 100644 --- a/.claude/skills/objectstack-platform/references/bootstrap.md +++ b/.claude/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`**: @@ -142,13 +329,13 @@ or `module` package id are refused (`STACK_SINGLE_APP_VIOLATION`, 422). "validate": "objectstack validate" }, "dependencies": { - "@objectstack/spec": "19.0.0-next.2", - "@objectstack/runtime": "19.0.0-next.2", - "@objectstack/driver-memory": "19.0.0-next.2", - "@objectstack/plugin-hono-server": "19.0.0-next.2" + "@objectstack/spec": "19.0.0-next.3", + "@objectstack/runtime": "19.0.0-next.3", + "@objectstack/driver-memory": "19.0.0-next.3", + "@objectstack/plugin-hono-server": "19.0.0-next.3" }, "devDependencies": { - "@objectstack/cli": "19.0.0-next.2", + "@objectstack/cli": "19.0.0-next.3", "typescript": "^5.3.0" } } diff --git a/.claude/skills/objectstack-platform/references/operations.md b/.claude/skills/objectstack-platform/references/operations.md index e5ebfaa..d706e80 100644 --- a/.claude/skills/objectstack-platform/references/operations.md +++ b/.claude/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/.claude/skills/objectstack-platform/references/plugin-development.md b/.claude/skills/objectstack-platform/references/plugin-development.md index 43a9b4a..9e81db2 100644 --- a/.claude/skills/objectstack-platform/references/plugin-development.md +++ b/.claude/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 diff --git a/.claude/skills/objectstack-project/SKILL.md b/.claude/skills/objectstack-project/SKILL.md index 105ca67..d07d33a 100644 --- a/.claude/skills/objectstack-project/SKILL.md +++ b/.claude/skills/objectstack-project/SKILL.md @@ -13,7 +13,7 @@ license: Apache-2.0 compatibility: Requires @objectstack/cli 19.x and @objectstack/verify 19.x; the check lists below are that version's. metadata: author: objectstack-ai - version: "19.0.0-next.2" + version: "19.0.0-next.3" domain: process tags: project, process, testing, verify, release, changeset, upgrade, backfill, platform-gap --- @@ -168,11 +168,11 @@ command fails on it, then replace the test with a one-line ## 5 · Bumping the platform, and customer data on upgrade Bump: -1. Move every `@objectstack/*` package to one version together, `@objectstack/skills` +1. Move every `@objectstack/*` package to one version, `@objectstack/skills` included, then re-sync the skills and commit them: `npx skills@1.7.2 experimental_sync --agent claude-code --copy -y` (name your own runtime after `--agent`). -2. Read each package's `CHANGELOG.md` between the two versions for breaking +2. Read each package's `CHANGELOG.md` between the versions for breaking entries. Crossing a protocol major: objectstack-upgrade. 3. Run the four checks. A new rule that reports existing metadata is fixed in the metadata, ⛔ never silenced. @@ -182,16 +182,16 @@ Bump: Data already installed: - Added objects, fields and indexes apply on boot. A rename carries - `renamedFrom`. A type change, a drop or a relaxed `NOT NULL` goes through + `renamedFrom`. A type change, a drop or a relaxed `NOT NULL` takes `os migrate plan` then `os migrate apply` (`--allow-destructive` for a drop). - Detail: objectstack-data, "Schema evolution". + Detail: objectstack-data `rules/field-types.md` § Changing a field that has data. - Removing a field or object, or changing what its value means, puts the old values out of reach once the new metadata is installed. Copy them first with a backfill script in `scripts/`: - - run it against each deployment while it is still on the old release; + - run it on each deployment while still on the old release; - REST API only, no import from `src/`, so it works on any installed metadata; - report by default, write only with `--apply`; - - touch only the rows that need it; a second run reports zero; + - touch only rows that need it; a second run reports zero; - sign in as an administrator named on the command line; the password or token comes from the environment or a prompt, never an argument. - ★ The release note names the script and when to run it. diff --git a/.claude/skills/objectstack-project/evals/project-process.json b/.claude/skills/objectstack-project/evals/project-process.json index 50b72c6..310ba07 100644 --- a/.claude/skills/objectstack-project/evals/project-process.json +++ b/.claude/skills/objectstack-project/evals/project-process.json @@ -142,7 +142,7 @@ { "id": 9, "prompt": "Users of our ObjectStack app need to see who changed which field on a record and when. Create an `audit_entry` object (object name, record id, field, old value, new value, user, time) and hooks on every object that fill it.", - "expected_output": "Does not build it: the platform catalog lists `sys_audit_log` (every write is recorded) and `sys_activity` (the record timeline, `enable.activities`, on by default) as what the platform ships for change history, read through the record page's activity stream and the data API. Leaves `activities` on, sets `trackHistory` where field-level history is wanted, and points the users at the timeline; `view_all_audit_log` is the capability for rows a reader could not otherwise open. No `audit_entry` object and no hooks.", + "expected_output": "Does not build it: the platform catalog lists `sys_audit_log` (every write is recorded) and `sys_activity` (the record timeline, `enable.activities`, on by default) as what the platform ships for change history, read through the record page's activity stream and the data API. Leaves `activities` on, where a changed field's old and new values show by default (`fieldHistory`), and points the users at the timeline; `view_all_audit_log` is the capability for rows a reader could not otherwise open. No `audit_entry` object and no hooks.", "files": [], "assertions": { "must_contain": [ diff --git a/.claude/skills/objectstack-query/SKILL.md b/.claude/skills/objectstack-query/SKILL.md index d70c08e..97e6c40 100644 --- a/.claude/skills/objectstack-query/SKILL.md +++ b/.claude/skills/objectstack-query/SKILL.md @@ -12,7 +12,7 @@ license: Apache-2.0 compatibility: Requires @objectstack/spec 19.x (Zod v4 schemas) metadata: author: objectstack-ai - version: "19.0.0-next.2" + version: "19.0.0-next.3" domain: query tags: query, filter, sort, paginate, aggregate, ObjectQL, full-text --- @@ -111,7 +111,7 @@ The simplest filter — field equals value: ### Comparison Operators | Operator | Purpose | SQL Equivalent | Types | -|:---------|:--------|:---------------|:------| +|:-|:-|:-|:-| | `$eq` | Equal | `=` | Any | | `$ne` | Not equal | `<>` | Any | | `$gt` | Greater than | `>` | Number, Date | @@ -127,7 +127,7 @@ The simplest filter — field equals value: ### Set & Range Operators | Operator | Purpose | SQL Equivalent | -|:---------|:--------|:---------------| +|:-|:-|:-| | `$in` | In list | `IN (...)` | | `$nin` | Not in list | `NOT IN (...)` | | `$between` | Inclusive range | `BETWEEN ? AND ?` | @@ -140,7 +140,7 @@ The simplest filter — field equals value: ### String Operators | Operator | Purpose | SQL Equivalent | -|:---------|:--------|:---------------| +|:-|:-|:-| | `$contains` | Contains substring | `LIKE '%?%'` | | `$notContains` | Does not contain | `NOT LIKE '%?%'` | | `$startsWith` | Starts with prefix | `LIKE '?%'` | @@ -157,19 +157,19 @@ only). So the user-facing cases want `$icontains`: { where: { email: { $icontains: '@company.com' } } } ``` -Full table, `$like` portability and the `$ilike` boundary: **[filter rules](./rules/filters.md)**. +All examples, `$like` portability and the `$ilike` boundary: **[filter rules](./rules/filters.md)**. ### Null & Existence Operators | Operator | Purpose | SQL / NoSQL | -|:---------|:--------|:------------| +|:-|:-|:-| | `$null` | Is null check | `IS NULL` / `IS NOT NULL` | | `$exists` | Has a value | `IS NOT NULL` / `IS NULL` | | `$empty` | Is empty by the field's declared type | `IS NULL`, plus `''` (text types) or `[]` (multi-value) | ```typescript { where: { deleted_at: { $null: true } } } -{ where: { notes: { $empty: true } } } // false = has content +{ where: { notes: { $empty: true } } } // false = has content ``` A view filter's `is_empty` / `is_not_empty` lowers to `$empty`. A face that judges @@ -185,14 +185,7 @@ Combine conditions with `$and`, `$or`, and `$not`: { where: { $or: [{ status: 'active' }, { revenue: { $gt: 1000000 } }] } } // AND + OR combined -{ - where: { - $and: [ - { type: 'enterprise' }, - { $or: [{ region: 'us' }, { region: 'eu' }] }, - ] - } -} +{ where: { $and: [{ type: 'enterprise' }, { $or: [{ region: 'us' }, { region: 'eu' }] }] } } // NOT: exclude closed accounts { where: { $not: { status: 'closed' } } } @@ -200,10 +193,14 @@ Combine conditions with `$and`, `$or`, and `$not`: ### Filtering by a related record -`{ customer: { country: 'US' } }` beneath a lookup is served in `where`: the -engine reads the related object as the caller and matches its ids. The limits -(one level, forward only, `where` only, 1000 ids, the caller's permissions) and -the two-step route past them: **[filter rules → Relation Filters](./rules/filters.md)**. +`{ customer: { country: 'US' } }` beneath a lookup is served in `where`, read +as the caller: on `find` / `findOne` / `count` / `aggregate` a single-valued +relation is one in-database subquery per relationship — no id list, no cap — +and a relation key may carry its own condition, up to three relationships. +The driver it needs (`DriverCapabilities.readableIdsLeaf`; MongoDB and OData +refuse it), the limits (forward only, `where` only, the 1000-id cap where ids +are still read, the caller's permissions at every hop) and the two-step route +past them: **[filter rules → Relation Filters](./rules/filters.md)**. ### Cross-field comparisons @@ -221,10 +218,7 @@ Sort with `orderBy` — an array of sort nodes: import type { QueryInput } from '@objectstack/spec/data'; const query: QueryInput = { object: 'account', - orderBy: [ - { field: 'priority', order: 'desc' }, - { field: 'name', order: 'asc' }, // Secondary sort - ] + orderBy: [{ field: 'priority', order: 'desc' }, { field: 'name', order: 'asc' }], // name: secondary sort }; ``` @@ -268,8 +262,6 @@ const rows = await engine.aggregate('deal', { { function: 'count', alias: 'deal_count' }, ], }); -// SQL: SELECT region, SUM(amount) AS total_revenue, COUNT(*) AS deal_count -// FROM deal GROUP BY region ``` `fields` and `orderBy` are NOT in `ENGINE_AGGREGATE_OPTION_KEYS` — do not put @@ -288,14 +280,11 @@ key in `fields`** — the relation is carried by that column: import type { IDataEngine } from '@objectstack/spec/contracts'; declare const engine: IDataEngine; const tasks = await engine.find('task', { - fields: ['title', 'status', 'owner_id', 'project'], // the FK columns stay + fields: ['title', 'status', 'owner_id', 'project'], // the FK columns stay expand: { owner_id: { object: 'user', fields: ['name', 'email'] }, - project: { - object: 'project', - fields: ['name'], - expand: { org: { object: 'org', fields: ['name'] } }, // nested expand - }, + // nested expand + project: { object: 'project', fields: ['name'], expand: { org: { object: 'org', fields: ['name'] } } }, }, }); ``` @@ -369,9 +358,9 @@ related record's column, `where: { relation: { column: value } }`; to *display* ### Cross-Object Queries: Which Tool to Use? | Scenario | Use | -|:---------|:----| +|:-|:-| | Load lookup fields for display | `expand` | -| Filter rows by their lookup target's column | `{ lookup: { column: value } }` in `where`, up to 1000 related ids; past the cap query the target, then `{ lookup: { $in: ids } }` — `$contains` per id when `multiple` | +| Filter rows by their lookup target's column | `{ lookup: { column: value } }` in `where`; past the 1000-id cap where ids are still read, query the target, then `{ lookup: { $in: ids } }` — `$contains` per id when `multiple` | | Filter parent by child conditions | Query the child with `fields: [lookup]`, then `{ id: { $in: those ids } }` on the parent | | **Keyword-search by a related record's title** | **Mirror the title into a stored field on this object and search that** — `search` never traverses | | Paginate/sort a parent's related records | Query the related object directly | diff --git a/.claude/skills/objectstack-query/rules/filters.md b/.claude/skills/objectstack-query/rules/filters.md index 44591ad..9554684 100644 --- a/.claude/skills/objectstack-query/rules/filters.md +++ b/.claude/skills/objectstack-query/rules/filters.md @@ -4,31 +4,31 @@ Every block below is a `where` fragment, so `check:skill-examples` skips it. ## Operator Reference -| Category | Operator | SQL Equivalent | Example | -|:---------|:---------|:---------------|:--------| -| Equality | `$eq` | `=` | `{ status: { $eq: 'active' } }` | -| Equality | `$ne` | `<>` | `{ status: { $ne: 'deleted' } }` | -| Comparison | `$gt` | `>` | `{ age: { $gt: 18 } }` | -| Comparison | `$gte` | `>=` | `{ amount: { $gte: 100 } }` | -| Comparison | `$lt` | `<` | `{ price: { $lt: 50 } }` | -| Comparison | `$lte` | `<=` | `{ score: { $lte: 100 } }` | -| Set | `$in` | `IN (...)` | `{ status: { $in: ['active', 'pending'] } }` | -| Set | `$nin` | `NOT IN (...)` | `{ role: { $nin: ['guest'] } }` | -| Range | `$between` | `BETWEEN ? AND ?` | `{ age: { $between: [18, 65] } }` | -| String | `$contains` | `LIKE %?%` | `{ name: { $contains: 'john' } }` | -| String | `$notContains` | `NOT LIKE %?%` | `{ email: { $notContains: 'spam' } }` | -| String | `$startsWith` | `LIKE ?%` | `{ code: { $startsWith: 'PRJ-' } }` | -| String | `$endsWith` | `LIKE %?` | `{ file: { $endsWith: '.pdf' } }` | -| String | `$icontains` | `LIKE %?%`, case-blind | `{ name: { $icontains: 'john' } }` | -| String | `$like` | `LIKE ?` — caller binds `%` / `_` | `{ code: { $like: 'PRJ-%-26' } }` | -| String | `$ilike` | `$like`, case-blind | `{ code: { $ilike: 'prj-%' } }` | -| Null | `$null` | `IS NULL` / `IS NOT NULL` | `{ deleted_at: { $null: true } }` | -| Null | `$exists` | `IS NOT NULL` / `IS NULL` | `{ metadata: { $exists: true } }` | -| Null | `$empty` | `IS NULL`, `''` or `[]` by type | `{ notes: { $empty: true } }` | - -Case sensitivity: SKILL.md, **String Operators**. `$like`/`$ilike` match the +An example of each operator: + +- `{ status: { $eq: 'active' } }` +- `{ status: { $ne: 'deleted' } }` +- `{ age: { $gt: 18 } }` +- `{ amount: { $gte: 100 } }` +- `{ price: { $lt: 50 } }` +- `{ score: { $lte: 100 } }` +- `{ status: { $in: ['active', 'pending'] } }` +- `{ role: { $nin: ['guest'] } }` +- `{ age: { $between: [18, 65] } }` +- `{ name: { $contains: 'john' } }` +- `{ email: { $notContains: 'spam' } }` +- `{ code: { $startsWith: 'PRJ-' } }` +- `{ file: { $endsWith: '.pdf' } }` +- `{ name: { $icontains: 'john' } }` +- `{ code: { $like: 'PRJ-%-26' } }` +- `{ code: { $ilike: 'prj-%' } }` +- `{ deleted_at: { $null: true } }` +- `{ metadata: { $exists: true } }` +- `{ notes: { $empty: true } }` + +Purpose, SQL equivalent, case sensitivity: SKILL.md, **Filter Operators**. `$like`/`$ilike` match the WHOLE value, so a pattern with no wildcard is an exact comparison, not -a substring search. Their reach is narrower than the rest of the table: the SQL +a substring search. Their reach is narrower than the other operators': the SQL family, `driver-memory` and `@objectstack/formula` answer them, while `driver-mongodb`, objectql `having` and service-analytics each keep an operator allowlist that omits them and refuse — `Unsupported filter operator`, @@ -43,9 +43,7 @@ unpaired backslash is refused by every face. ```typescript // ✅ Projects that ran over budget -where: { - actual_cost: { $gt: { $field: 'budget' } } -} +where: { actual_cost: { $gt: { $field: 'budget' } } } ``` Legal in a **comparison** position only. As an `$in` / `$nin` member or a @@ -61,10 +59,8 @@ reference there. ```typescript // ✅ Overdue by each record's own grace period: due_at < now + grace_days_offset, -// the number field holding the grace period as NEGATIVE days -where: { - due_at: { $lt: { $now: true, addDays: { $field: 'grace_days_offset' } } } -} +// the number field holding the grace period as NEGATIVE days +where: { due_at: { $lt: { $now: true, addDays: { $field: 'grace_days_offset' } } } } ``` `addDays` is **required** and always ADDED: an integer of any sign (`-30` @@ -81,22 +77,33 @@ answers it — not a stored formula field plus a hook. ## Relation Filters A condition on a related record's fields beneath a relation field (`lookup`, -`master_detail`, `user`, `tree`) is served in `where`: the engine reads the -related object with it **as the caller**, then matches the field against the -ids it returns (`$in`; any member when `multiple: true`). +`master_detail`, `user`, `tree`) is served in `where`, each hop read **as the caller**. On `find` / +`findOne` / `count` / `aggregate` a single-valued relation is matched with one +in-database subquery per relationship — no id list, no cap — on drivers +declaring `DriverCapabilities.readableIdsLeaf` (every `driver-sql` dialect, +Turso; `driver-memory` evaluates it in process); a driver without it +(MongoDB, OData) refuses the condition before anything is read, +`INVALID_FILTER` / 400. ```typescript // ✅ Orders whose customer is in the US where: { customer: { country: 'US' } } ``` -Limits — one level: every key a field the related object declares, no relation -or dotted key inside; forward only: never a parent by its children; `where` -only: an aggregation's `filter` and `having` refuse it, `INVALID_FILTER` / 400; -at most 1000 related ids, refused past that, `INVALID_FILTER` / 400, never -truncated; as the caller: the related object's row scope and field permissions -apply, so a field the caller cannot read is refused, `PERMISSION_DENIED` / 403, -never an empty result. Past the cap, run the two steps yourself — filter the +Limits — up to three relationships (ADR-0071's hop limit): every key a field the related object +declares, and a relation key may carry its own condition +(`{ customer: { owner: { region: 'NA' } } }`); a fourth, and a dotted key +inside, are refused, `INVALID_FILTER` / 400; forward only: never a parent by +its children; `where` only: an aggregation's `filter` and `having` refuse it, +`INVALID_FILTER` / 400; where ids are read and matched (`$in`; any member when `multiple: true`) — a +multi-valued relation, `update` / `delete`, and on a read verb a +related object on another datasource, federated, shaped by a middleware or +`afterFind` hook, or read under different driver options — at most 1000, +refused past that, `INVALID_FILTER` / 400, never truncated; as the caller, at +every hop: the related object's row scope and field permissions apply, so a +field the caller cannot read is refused, `PERMISSION_DENIED` / 403, never an +empty result, and a related record the caller cannot read excludes the row, +`$ne` included. Past the cap, run the two steps yourself — filter the related object, then `$in` its ids: ```typescript @@ -140,9 +147,7 @@ State absence with `$null`: `null` is not an ordering comparand For **ad-hoc queries in application code**, compute the date yourself: ```typescript -where: { - created_at: { $gte: new Date('2025-01-01') } -} +where: { created_at: { $gte: new Date('2025-01-01') } } ``` ### Date Macros (declarative filter metadata) @@ -152,10 +157,7 @@ pages — cannot run code, so they use **date macro tokens** instead (defined in `@objectstack/spec` `data/date-macros.zod.ts`): ```typescript -where: { - signal_at: { $gte: '{30_days_ago}' }, - published_at: { $gte: '{last_quarter_start}' } -} +where: { signal_at: { $gte: '{30_days_ago}' }, published_at: { $gte: '{last_quarter_start}' } } ``` - **Fixed tokens:** `{today}`, `{yesterday}`, `{tomorrow}`, `{now}`, plus diff --git a/.claude/skills/objectstack-ui/SKILL.md b/.claude/skills/objectstack-ui/SKILL.md index 68c24d0..a771260 100644 --- a/.claude/skills/objectstack-ui/SKILL.md +++ b/.claude/skills/objectstack-ui/SKILL.md @@ -11,7 +11,7 @@ license: Apache-2.0 compatibility: Requires @objectstack/spec 19.x (Zod v4 schemas) metadata: author: objectstack-ai - version: "19.0.0-next.2" + version: "19.0.0-next.3" domain: ui tags: view, app, page, dashboard, report, chart, action, widget, doc --- @@ -41,10 +41,10 @@ metadata: Two more: [List Views](#list-views), [Actions](#actions). -1. **New and Edit are the object's fields and `fieldGroups`, never a form - view**: they load no `form` or `formViews.create`, which parse. +1. **New and Edit are the object's fields and `fieldGroups`, never a `form` + item**: they load no `form` item, which parses. `showOnCreate: false` keeps a field off every create surface (refused - beside `required: true`): [Form Views](./rules/list-views.md#form-views). + beside `required: true`): [Forms](./rules/list-views.md#forms). 2. **A record entered with its line items is a parent field group naming the child** (`fieldGroups: [{ key: 'lines', label: 'Lines', relatedList: 'invoice_line' }]`), before any custom page; without it nothing changes: @@ -74,7 +74,7 @@ Two more: [List Views](#list-views), [Actions](#actions). | Authoring | In | Open first | |:--|:--|:--| | A list, board, calendar, gallery or gantt: columns, `filter`, quick filters, toolbar search, sorting, grouping | `src/views/*.view.ts` | [List Views](./rules/list-views.md) | -| New / Edit form (field groups, `showOnCreate`, line items, field rules); a named or public form | the object; `src/views/*.view.ts` | [Form Views](./rules/list-views.md#form-views) | +| New / Edit form (field groups, `showOnCreate`, line items, field rules); a public or action-opened form (`defineForm`, `forms:`) | the object; `*.form.ts` | [Forms](./rules/list-views.md#forms) | | An app and its navigation; who sees or opens it; object nav, a `filters` slice or an interface page | `src/apps/*.app.ts` | [Navigation](./rules/navigation.md) | | What a record page shows: related lists, a slotted or full page; how a record opens | the object | [Record Page](./rules/record-page.md) | | A button or operation: `locations`, visibility, dialog and toast copy, params, new tab, the body's `ctx`, refusing by code (`refusals`) | `src/actions/*.action.ts`, `*.actions.ts` | [Actions](./rules/actions.md) | @@ -133,7 +133,7 @@ reports success and changes nothing. Call the API, with the option `value`, never its label ([Actions](./rules/actions.md)): ```json -{ "name": "mark_done", "label": "Mark as done", "objectName": "task", +{ "name": "mark_done", "label": "Mark as done", "objectName": "task", "locations": ["record"], "type": "script", "body": { "language": "js", "capabilities": ["api.write"], "source": "await ctx.api.object('task').update({ id: ctx.recordId, status: 'done' });" } } ``` @@ -147,10 +147,9 @@ never its label ([Actions](./rules/actions.md)): | `modal` | Open the page named by `target`; a `body` runs only on `script` | | `flow` | Launch a screen/auto-launched flow by name; a multi-step operation is this, with a flow you also author | | `api` | Call a registered API endpoint | -| `form` | Open a FormView by name (routed to `/_console/forms/:name`) | -| `ask_ai` | Open the in-app assistant focused on the one record the action runs on; no `target`, never `ai.exposed: true` | +| `form` | Open the `form` item `target` names (`OBJECT.KEY`) on its own page | -Every type but `script` and `ask_ai` requires `target`. +Every type but `script` requires `target`. ## Report Types diff --git a/.claude/skills/objectstack-ui/evals/README.md b/.claude/skills/objectstack-ui/evals/README.md index 7c479af..ccee86d 100644 --- a/.claude/skills/objectstack-ui/evals/README.md +++ b/.claude/skills/objectstack-ui/evals/README.md @@ -25,7 +25,8 @@ view / page / dashboard / report metadata. - `views-apps-actions-pages.json` — `defineView` containers, `App.create` navigation, `defineAction` surfaces, record / interface pages, package docs, the New and Edit form built from the object (field groups, - `showOnCreate`, line items), a named form's section `columns`, a view added + `showOnCreate`, line items), a `form` item an action opens and its section + `columns`, a public `form` item on an address another form holds, a view added beside the list (and the empty board over a field added with it), a write button whose body writes, the view kind the request names, an AI-exposed delete gated by `ai.requiresConfirmation`, not `confirmText`. diff --git a/.claude/skills/objectstack-ui/evals/record-page.json b/.claude/skills/objectstack-ui/evals/record-page.json index aa8d259..d6dc3e3 100644 --- a/.claude/skills/objectstack-ui/evals/record-page.json +++ b/.claude/skills/objectstack-ui/evals/record-page.json @@ -45,7 +45,7 @@ { "id": 3, "prompt": "Our account record page is a custom `kind: 'full'` page with its own tab strip. Installed packages keep adding header actions to `account` (an 'Open in billing' link, for one), and none of them ever shows in the page header. Make the header show every action placed on the account's header, including ones a package adds later, without us listing ids. None of the project's files are in this directory: write the change in your answer.", - "expected_output": "Keep the `kind: 'full'` page and its tab strip, and set `placedActions: true` on its `page:header` node: `{ type: 'page:header', properties: { placedActions: true } }`. The header then draws every action of `account` whose `locations` include `record_header` or `record_more`, read live, so a package's action appears without a page edit. No `actions` id list beside it: an authored list is the whole set, and `placedActions: true` beside one is refused. Not a return to a `slotted` page and never a `slots.tabs`.", + "expected_output": "Keep the `kind: 'full'` page and its tab strip, and set `placedActions: true` on its `page:header` node: `{ type: 'page:header', properties: { placedActions: true } }`. The header then draws every action of `account` whose `locations` include `record` or `record_page`, read live, so a package's action appears without a page edit. No `actions` id list beside it: an authored list is the whole set, and `placedActions: true` beside one is refused. Not a return to a `slotted` page and never a `slots.tabs`.", "files": [], "assertions": { "must_contain": [ diff --git a/.claude/skills/objectstack-ui/evals/views-apps-actions-pages.json b/.claude/skills/objectstack-ui/evals/views-apps-actions-pages.json index 160d7d4..8e22b42 100644 --- a/.claude/skills/objectstack-ui/evals/views-apps-actions-pages.json +++ b/.claude/skills/objectstack-ui/evals/views-apps-actions-pages.json @@ -4,11 +4,11 @@ { "id": 1, "prompt": "Create `src/views/support-case.view.ts`: a default grid (subject linking to the record, status, priority, owner, due date), a 'My Open Cases' list, a kanban by status, and a simple edit form with the case details in one section. None of the project's files are in this directory: write the file in your answer.", - "expected_output": "One `defineView({ list, listViews })` container — never a bare flat view object. `data: { provider: 'object', object: 'support_case' }`, `columns` with `link: true` on `subject`, the owner column is the injected `owner_id` (never an `assigned_to` field), a `listViews.my_open` entry with `filter` triples (`{ field: 'owner_id', operator: 'equals', value: '{current_user_id}' }`), a kanban entry with the required top-level `columns` plus `kanban: { groupByField: 'status' }` (no top-level `groupBy`). No `form` in the container: the edit form is built from the object, so the answer says its section is a `fieldGroups` entry of `support_case` (an internal `form` parses and is not loaded).", + "expected_output": "One `defineView({ list, listViews })` container — never a bare flat view object. `data: { provider: 'object', object: 'support_case' }`, `columns` with `link: true` on `subject`, the owner column is the injected `owner_id` (never an `assigned_to` field), a `listViews.my_open` entry with `filter` triples (`{ field: 'owner_id', operator: 'equals', value: '{current_user_id}' }`), a kanban entry with the required top-level `columns` plus `kanban: { groupByField: 'status' }` (no top-level `groupBy`). No form in the container and no `form` item: the edit form is built from the object, so the answer says its section is a `fieldGroups` entry of `support_case` (a `form` item is a public form or one an action opens; New and Edit load none).", "files": [], "assertions": { "must_contain": ["defineView", "provider: 'object'", "listViews", "groupByField", "link: true", "{current_user_id}", "owner_id"], - "must_not_contain": ["groupBy:", "conditionalRequired:", "'assigned_to'", "form: {"] + "must_not_contain": ["groupBy:", "conditionalRequired:", "'assigned_to'", "form: {", "defineForm("] } }, { @@ -24,10 +24,10 @@ { "id": 3, "prompt": "Add a Convert action on `lead` — only for qualified, not-yet-converted leads, from the record header and each list row, launching the `crm_lead_conversion` flow — and a bulk 'Add to campaign' that asks which campaign, for the selected rows.", - "expected_output": "Two `defineAction` items. Convert: `type: 'flow'`, `target: 'crm_lead_conversion'`, `locations: ['record_header', 'list_item']`, `visible: P`record.status == \"qualified\" && record.is_converted == false`` (bare CEL, never brace-wrapped), `confirmText`, `successMessage`, `refreshAfter: true`. Bulk: `type: 'script'`, `execution: 'perRecord'`, wired by the lead list view's `bulkActions: ['']`, a field-backed `params: [{ field: 'campaign_id', objectOverride: 'campaign', required: true }]`, and a `body` that runs once per ticked row and reads that row's id as `ctx.recordId`.", + "expected_output": "Two `defineAction` items. Convert: `type: 'flow'`, `target: 'crm_lead_conversion'`, `locations: ['record']`, `visible: P`record.status == \"qualified\" && record.is_converted == false`` (bare CEL, never brace-wrapped), `confirmText`, `successMessage`, `refreshAfter: true`. Bulk: `type: 'script'`, `execution: 'perRecord'`, wired by the lead list view's `bulkActions: ['']`, a field-backed `params: [{ field: 'campaign_id', objectOverride: 'campaign', required: true }]`, and a `body` that runs once per ticked row and reads that row's id as `ctx.recordId`.", "files": [], "assertions": { - "must_contain": ["defineAction", "locations", "record_header", "bulkActions", "visible", "successMessage", "ctx.recordId"], + "must_contain": ["defineAction", "locations", "'record'", "bulkActions", "visible", "successMessage", "ctx.recordId"], "must_not_contain": ["{record.", "input.selectedIds"] } }, @@ -54,7 +54,7 @@ { "id": 6, "prompt": "Invoice entry as a stepped form — header, then line items, then review — saving the invoice and its lines together.", - "expected_output": "No form view and no screen flow (nothing branches): the invoice's New form is built from the object, so header, then lines, then the rest is the order of `invoice`'s `fieldGroups`. Line items come from the DATA MODEL: a field group naming the `master_detail` child (`fieldGroups: [{ key: 'header', ... }, { key: 'lines', label: 'Lines', relatedList: 'invoice_line' }, ...]`), which draws the editable grid in the form and saves parent + children in one atomic `/api/v1/batch`; without the group the form has no lines, whatever `inlineEdit` says. The hand-over says the steps are sections of one form, not a wizard: a `formViews` wizard is not loaded by New or Edit, and a named form an action opens draws no line items. No custom page, and no 'Add line' button (the ghost row exists).", + "expected_output": "No form view and no screen flow (nothing branches): the invoice's New form is built from the object, so header, then lines, then the rest is the order of `invoice`'s `fieldGroups`. Line items come from the DATA MODEL: a field group naming the `master_detail` child (`fieldGroups: [{ key: 'header', ... }, { key: 'lines', label: 'Lines', relatedList: 'invoice_line' }, ...]`), which draws the editable grid in the form and saves parent + children in one atomic `/api/v1/batch`; without the group the form has no lines, whatever `inlineEdit` says. The hand-over says the steps are sections of one form, not a wizard: a wizard `form` item is not loaded by New or Edit, and a form an action opens draws no line items. No custom page, and no 'Add line' button (the ghost row exists).", "files": [], "assertions": { "must_contain": ["fieldGroups", "relatedList", "master_detail"], @@ -134,7 +134,7 @@ { "id": 14, "prompt": "Add a 'Mark as done' button on `task` records that sets `status` to Done (the option is labelled Done, its value is `done`).", - "expected_output": "A `defineAction`, not a view: `name`, `label: 'Mark as done'`, `objectName: 'task'`, `locations: ['record_header']`, `type: 'script'`, `body: { language: 'js', source: \"await ctx.api.object('task').update({ id: ctx.recordId, status: 'done' });\", capabilities: ['api.write'] }`, `refreshAfter: true`. The body CALLS the update with the option value: a body that returns `{ status: 'done' }` or assigns to `ctx.record` writes nothing, an `expression` body cannot write, and without `api.write` the sandbox refuses the call.", + "expected_output": "A `defineAction`, not a view: `name`, `label: 'Mark as done'`, `objectName: 'task'`, `locations: ['record']`, `type: 'script'`, `body: { language: 'js', source: \"await ctx.api.object('task').update({ id: ctx.recordId, status: 'done' });\", capabilities: ['api.write'] }`, `refreshAfter: true`. The body CALLS the update with the option value: a body that returns `{ status: 'done' }` or assigns to `ctx.record` writes nothing, an `expression` body cannot write, and without `api.write` the sandbox refuses the call.", "files": [], "assertions": { "must_contain": ["defineAction", "objectName: 'task'", "ctx.api.object('task').update", "ctx.recordId", "api.write", "status: 'done'"], @@ -184,7 +184,7 @@ { "id": 19, "prompt": "Shape the New and Edit form of `opportunity`: 42 fields in six sections (Basics, Amounts, Dates, Partner, Shipping, Internal Notes). Reps fill Basics and Amounts on every create and the other four rarely, and `loss_reason` is never known at create. The form opens in the New dialog, mostly on wide screens.", - "expected_output": "No form view: New and Edit are built from the object. Six `fieldGroups` entries on `opportunity` in that order, with `collapse: 'collapsed'` on the four rarely filled ones, and `showOnCreate: false` on `loss_reason`, which edit, the record page and lists still show (it must not be `required: true`: the pair is refused). Not a `form`, `formViews.default` or `formViews.create` (each parses and is not loaded), and no `modalSize` or `columns`: the dialog's size and column count are derived.", + "expected_output": "No form view: New and Edit are built from the object. Six `fieldGroups` entries on `opportunity` in that order, with `collapse: 'collapsed'` on the four rarely filled ones, and `showOnCreate: false` on `loss_reason`, which edit, the record page and lists still show (it must not be `required: true`: the pair is refused). Not a `form` item (it parses, and New and Edit load none), and no `modalSize` or `columns`: the dialog's size and column count are derived.", "files": [], "assertions": { "must_contain": ["fieldGroups", "collapse: 'collapsed'", "showOnCreate: false"], @@ -233,8 +233,8 @@ }, { "id": 24, - "prompt": "`crm_opportunity` has five record actions, all placed at `record_header`: `mark_won`, `mark_lost`, `clone`, `share`, `archive`. The team wants Mark Won, Mark Lost, Clone and Share as header buttons in that order, Archive under More, and on the list page Export as a button after the `mass_assign` toolbar action. Write the metadata that does this.", - "expected_output": "One key on the object, no page file and no edit to any action: `actionLayout: { record: { pinned: ['mark_won', 'mark_lost', 'clone'], more: ['share', 'archive'] }, list: { pinned: ['mass_assign', '$export'] } }`. The answer says an arm pins at most three buttons, so the fourth requested button, Share, leads `more` instead (a fourth name in `pinned` is refused). The `record` arm holds for the record page, the side preview and the phone action bar alike. `$export` is the list page's built-in, named only in the `list` arm's `pinned`; `mass_assign` must be placed at `list_toolbar` or `os validate` refuses the name. Not four names in `pinned`, not an `order` renumbering on each action (shared by every surface, and it names no buttons), not `$export` in `more`, and not a `definePage` header listing action ids.", + "prompt": "`crm_opportunity` has five record actions, all placed at `record_page`: `mark_won`, `mark_lost`, `clone`, `share`, `archive`. The team wants Mark Won, Mark Lost, Clone and Share as header buttons in that order, Archive under More, and on the list page Export as a button after the `mass_assign` toolbar action. Write the metadata that does this.", + "expected_output": "One key on the object, no page file and no edit to any action: `actionLayout: { record: { pinned: ['mark_won', 'mark_lost', 'clone'], more: ['share', 'archive'] }, list: { pinned: ['mass_assign', '$export'] } }`. The answer says an arm pins at most three buttons, so the fourth requested button, Share, leads `more` instead (a fourth name in `pinned` is refused). The `record` arm holds for the record page, the side preview and the phone action bar alike. `$export` is the list page's built-in, named only in the `list` arm's `pinned`; `mass_assign` must be placed at `list` or `os validate` refuses the name. Not four names in `pinned`, not an `order` renumbering on each action (shared by every surface, and it names no buttons), not `$export` in `more`, and not a `definePage` header listing action ids.", "files": [], "assertions": { "must_contain": ["actionLayout", "pinned", "more", "$export"], @@ -244,17 +244,18 @@ { "id": 25, "prompt": "`crm_account` declares the field groups `basic_info` and `contact_info`. A 'New Intake' button opens an intake form on its own page; the team wants each group two columns wide there, and asks for the same two columns in the ordinary New dialog. Write the metadata and say what each surface does.", - "expected_output": "A named form under `formViews` whose sections reference the groups and declare the count, `sections: [{ group: 'basic_info', columns: 2 }, { group: 'contact_info', columns: 2 }]`, opened by a `type: 'form'` action whose `target` names it. The answer says the form page reads each section's `columns` (1 to 4, one column on a phone), and that the New and Edit dialog is built from the object's `fieldGroups`, never from this form view, at a column count the platform derives and nobody authors. Not `columns` on the form view itself (the form page does not read it), not a `columns` key on a `fieldGroups` entry, not `modalSize`, and not an answer that two columns cannot be authored anywhere.", + "expected_output": "A `form` item in the stack's `forms:`, `defineForm({ name: 'crm_account.intake', object: 'crm_account', sections: [{ group: 'basic_info', columns: 2 }, { group: 'contact_info', columns: 2 }] })`: the name is `OBJECT.KEY` with the form's `object` as its prefix, and the body is at the top level (no `viewKind`, no `config`, and no `data`, which is refused: a form is bound with `object`). A `type: 'form'` action whose `target` is `crm_account.intake` opens it. The answer says the form page reads each section's `columns` (1 to 4, one column on a phone), and that the New and Edit dialog is built from the object's `fieldGroups`, never from a `form` item, at a column count the platform derives and nobody authors. Not a form authored inside a `defineView` container, not `columns` on the form itself (the form page does not read it), not a `columns` key on a `fieldGroups` entry, not `modalSize`, and not an answer that two columns cannot be authored anywhere.", "files": [], "assertions": { - "must_contain": ["formViews", "group: 'contact_info', columns: 2", "type: 'form'", "fieldGroups"], - "must_not_contain": ["modalSize:", "formViews.default"] + "must_contain": ["object: 'crm_account'", "'crm_account.", "group: 'contact_info', columns: 2", "type: 'form'", "fieldGroups"], + "must_contain_any": [["defineForm", "forms:"]], + "must_not_contain": ["modalSize:", "defineView(", "provider: 'object'"] } }, { "id": 26, "prompt": "Add a 'Delete Task' button on the `project_task` record page that deletes the task. Our in-app assistant must be able to run it too, but only after the user agrees, since a deleted task's time entries go with it.", - "expected_output": "One registered `defineAction` on `objectName: 'project_task'` with a placement (`locations: ['record_header']`), a body that deletes the current record (a `type: 'script'` `js` body calling `ctx.api.object('project_task').delete(...)` on `ctx.recordId`, with `capabilities: ['api.write']`), `confirmText` for the person clicking, and `ai: { exposed: true, description: '…', requiresConfirmation: true }`. `confirmText` is the click dialog's copy only and gates no AI call, so the assistant's run is held for the user's approval by `ai.requiresConfirmation: true`, not by `confirmText` or by a sentence in `ai.description` asking the model to confirm first.", + "expected_output": "One registered `defineAction` on `objectName: 'project_task'` with a placement (`locations: ['record_page']`), a body that deletes the current record (a `type: 'script'` `js` body calling `ctx.api.object('project_task').delete(...)` on `ctx.recordId`, with `capabilities: ['api.write']`), `confirmText` for the person clicking, and `ai: { exposed: true, description: '…', requiresConfirmation: true }`. `confirmText` is the click dialog's copy only and gates no AI call, so the assistant's run is held for the user's approval by `ai.requiresConfirmation: true`, not by `confirmText` or by a sentence in `ai.description` asking the model to confirm first.", "files": [], "assertions": { "must_contain": ["requiresConfirmation: true", "exposed: true", "confirmText", "project_task"], @@ -270,6 +271,17 @@ "must_contain": ["groupByField", "summary", "avg", "estimate_hours", "showFieldLabels: false", "hideEmptyFields: false"], "must_not_contain": ["showFieldLabels: true"] } + }, + { + "id": 28, + "prompt": "Publish a 'Contact us' web form on `crm_lead` that anonymous visitors fill in at `/forms/contact-us`: name, email and message. The retired form `crm_lead.old_contact` is switched off (`sharing.enabled: false`) and still declares `publicLink: 'contact-us'`. Write the metadata and say what `os validate` answers.", + "expected_output": "One `form` item in the stack's `forms:`: `defineForm({ name: 'crm_lead.contact_us', object: 'crm_lead', sections: [{ fields: ['name', 'email', 'message'] }], sharing: { enabled: true, allowAnonymous: true, publicLink: 'contact-us' } })`. The name is `OBJECT.KEY` with the form's `object` as its prefix, and the body is at the top level (no `data`: a form is bound with `object`). Visitors read it at `GET /api/v1/forms/contact-us` and submit to `POST /api/v1/forms/contact-us/submit`. The answer says `os validate` refuses the new form with `form-public-address-taken`, naming both forms: the retired form holds its address while its `publicLink` names it, switched on or off, so its link is cleared first (until then a save of the new form answers `409 FORM_ADDRESS_TAKEN`). Not a form authored inside a `defineView` container, not a second form left on the address, and not a claim that switching the old form off frees the address.", + "files": [], + "assertions": { + "must_contain": ["object: 'crm_lead'", "'crm_lead.", "enabled: true", "allowAnonymous: true", "publicLink"], + "must_contain_any": [["defineForm", "forms:"], ["form-public-address-taken", "FORM_ADDRESS_TAKEN", "holds its address"]], + "must_not_contain": ["defineView(", "provider: 'object'"] + } } ] } diff --git a/.claude/skills/objectstack-ui/references/react-blocks.md b/.claude/skills/objectstack-ui/references/react-blocks.md index 472d8e6..2a0abbf 100644 --- a/.claude/skills/objectstack-ui/references/react-blocks.md +++ b/.claude/skills/objectstack-ui/references/react-blocks.md @@ -25,6 +25,7 @@ Server-connected create/edit/view form for one object. Config props come from th | `readOnly` | `boolean` | binding | | Render every field read-only, whatever `mode` says. | | `drawerSide` | `'top' \| 'bottom' \| 'left' \| 'right'` | binding | | Edge the drawer container opens from, when the React `ObjectForm` block opens this form with formType 'drawer' | | `drawerWidth` | `string` | binding | | Size of the drawer container the React `ObjectForm` block opens with formType 'drawer', as a CSS length such as "480px": its width when drawerSide is left or right, its height when top or bottom. Unset, the drawer keeps its default size. | +| `modalSize` | `'sm' \| 'default' \| 'lg' \| 'xl' \| 'full'` | binding | | Size bucket of the block's modal container (formType 'modal'). Unset, the modal picks a size from the form's columns and field count. | | `modalCloseButton` | `boolean` | binding | | Show the close button of the block's modal container (formType 'modal'). | | `contentLayout` | `'simple' \| 'tabbed'` | binding | | How the modal presentation lays out sections; 'tabbed' needs more than one section to differ from 'simple'. | | `confirmOnDiscard` | `boolean` | binding | | Ask before discarding unsaved edits when a drawer/modal form is dismissed. Set false to close immediately. | @@ -46,7 +47,6 @@ Server-connected create/edit/view form for one object. Config props come from th | `layout` | `'vertical' \| 'horizontal'` | data | | Field layout direction — 'vertical' (the renderer default) or 'horizontal'. Multi-column is not a layout value: set `columns` | | `columns` | `integer` | data | | Number of columns for the form body | | `tabPosition` | `'top' \| 'bottom' \| 'left' \| 'right'` | data | | Tab strip position (tabbed forms) | -| `modalSize` | `'sm' \| 'default' \| 'lg' \| 'xl' \| 'full'` | data | | Size bucket of the dialog a caller opens this form in: the console's New / Edit dialog, or the modal container of the React `ObjectForm` block (formType 'modal… | | `sections` | `object[]` | data | | | | `subforms` | `object[]` | data | | Inline master-detail child collections | | `submitBehavior` | `object` | data | | Post-submit behavior. On the `redirect` arm, `url` is relative-only and interpolates only declared record fields as `{{record.field_name}}`, URL-escaped. | diff --git a/.claude/skills/objectstack-ui/rules/actions.md b/.claude/skills/objectstack-ui/rules/actions.md index 8354825..6af00ce 100644 --- a/.claude/skills/objectstack-ui/rules/actions.md +++ b/.claude/skills/objectstack-ui/rules/actions.md @@ -1,6 +1,5 @@ # Actions -Actions are user-triggered operations on an object or a view. Register them under `defineStack({ actions: [...] })`; the six types: [Action Types](../SKILL.md#action-types). @@ -17,23 +16,25 @@ in `language: 'js'` (an `expression` body has no I/O) with ## Where Actions Appear (`locations`) -| Value | Surface | +| Value | Acts on, and where | |:-----------------|:--------| -| `record_header` | Detail page header | -| `record_more` | Detail page overflow menu (⋯) | +| `list` | No record: the list page toolbar; one ticked row is its `recordId`, several are refused (no `_selectedIds`) | +| `record` | One record, the default: the record page and each list row | +| `record_page` | The record page only; `component: 'action:menu'` puts it in the ⋯ menu | +| `record_row` | Each list row only | | `record_related` | Related-list section in a record | | `record_section` | Body section/tab of a record | -| `list_item` | Per-row action in list views | -| `list_toolbar` | Toolbar button; one ticked row is its `recordId`, several are refused (no `_selectedIds`) | + +Until protocol 19: `list_toolbar` (now `list`), `list_item` (`record_row`), `record_header` / `record_more` (`record_page`). ## Button Order (`actionLayout`) The object's `actionLayout` arranges one scope per arm: `{ record: { pinned: ['crm_convert_lead'], more: ['crm_print_a3'] } }`. `pinned` (required; `[]` pins none) names at most 3 buttons, in order; every other action -goes to the ⋯ menu, those `more` names first. `record` takes `record_header` / -`record_more` actions wherever that header draws (record page, side preview, -phone bar, a row's ⋮ menu order); `list` takes `list_toolbar` actions and may +goes to the ⋯ menu, those `more` names first. `record` takes `record` / +`record_page` actions wherever that header draws (record page, side preview, +phone bar, a row's ⋮ menu order); `list` takes `list` actions and may pin `$import` / `$export` (pinned only). `os validate` refuses a name the arm's scope does not place, on the object or an extension of one the same stack defines. On an installed object only its paired `.custom` package's extension @@ -65,6 +66,7 @@ export const ReassignLeadAction = defineAction({ name: 'crm_reassign_lead', label: 'Reassign Lead', objectName: 'lead', + locations: ['record'], type: 'api', target: 'lead', disabled: P`record.status == "converted"`, @@ -90,6 +92,7 @@ export const ConvertLeadAction = defineAction({ name: 'crm_convert_lead', label: 'Convert Lead', objectName: 'lead', + locations: ['record'], icon: 'arrow-right-circle', type: 'flow', target: 'crm_lead_conversion', @@ -144,8 +147,8 @@ throws and checks are a hook's (objectstack-data → Lifecycle Hooks → Declare sentence is answered as `userMessage`, translated at `objects.._actions..refusals..message` (objectstack-i18n); the console's failure toast shows it unless the action sets `errorMessage`. For several reasons throw -`reasons: [{ reason, params? }, …]`, not `reason`: `userMessage` is one line per reason, closed -by the code's `message` (rules there). +`reasons: [{ reason, params? }, …]`, not `reason`: `userMessage` is one line per reason, then +the code's `message` (Declared refusals). ### Writing in the organization's language (`texts`) @@ -173,6 +176,7 @@ export const PrintA3Action = defineAction({ name: 'crm_print_a3', label: 'Print A3', objectName: 'lead', + locations: ['record_page'], type: 'url', target: '/print/a3?id=${ctx.recordId}', // interpolated at click openIn: 'new-tab', @@ -196,6 +200,7 @@ export const OpenInvoicePdfAction = defineAction({ name: 'crm_open_invoice_pdf', label: 'Open PDF', objectName: 'invoice', + locations: ['record'], type: 'script', target: 'crm_open_invoice_pdf', opensInNewTab: true, @@ -216,7 +221,7 @@ placeholder and widget come from the object metadata (`widget` only while the param keeps or restates the field's `type`; a param that overrides `type` names its own `widget`); `objectOverride` borrows a field of another object, and `defaultFromRow: true` -pre-fills from the selected row in `list_item`. +pre-fills from the list row it runs on (`record` / `record_row`). **An action that adds a child line sets its price.** `lookupAutofill` fills only the form and the grid, and a stored `expression` reads only its own row, so a @@ -232,6 +237,7 @@ export const AddInvoiceLineAction = defineAction({ name: 'crm_add_invoice_line', label: 'Add Line', objectName: 'invoice', + locations: ['record'], type: 'script', params: [ { field: 'product', objectOverride: 'invoice_line', required: true }, diff --git a/.claude/skills/objectstack-ui/rules/dashboards.md b/.claude/skills/objectstack-ui/rules/dashboards.md index c4f3d3d..d68c2f6 100644 --- a/.claude/skills/objectstack-ui/rules/dashboards.md +++ b/.claude/skills/objectstack-ui/rules/dashboards.md @@ -19,7 +19,7 @@ A widget's `type` is its **chart type** (`ChartTypeSchema`; defaults to `metric`) — there are no separate `list` / `calendar` / `custom` widget kinds: | Family | `type` values | -|:-------|:--------------| +|:--|:--| | Single value | `metric`, `kpi`, `gauge`, `solid-gauge`, `bullet` (all render the number today; gauge variants gain a dial when a gauge renderer lands) | | Comparison | `bar`, `horizontal-bar`, `column` | | Trend | `line`, `area` | @@ -60,9 +60,7 @@ const widget: DashboardWidget = { ``` **The real decision is not "inline vs dataset" — it is "can a dataset express -this?"** The shape is already fixed (always a dataset), so what you decide is -whether the *data need fits the dataset envelope*, and if not, which lower layer to -escalate to. Decide on **expressibility**; reuse/governance is Level B. +this?"** Decide on **expressibility**; reuse/governance is Level B. **Level A — the dataset envelope:** @@ -152,21 +150,21 @@ export const SalesDashboard: Dashboard = { label: 'Sales Performance', columns: 12, gap: 4, - refreshIntervalSeconds: 180, // auto-refresh cadence + refreshIntervalSeconds: 180, // auto-refresh cadence header: { showTitle: true, actions: [ - { label: 'New Opportunity', icon: 'Plus', actionType: 'modal', actionUrl: 'crm_create_opportunity' }, - { label: 'Forecast', icon: 'TrendingUp', actionType: 'url', actionUrl: '/reports/forecast' }, - { label: 'Export', icon: 'Download', actionType: 'script', actionUrl: 'crm_export_dashboard_pdf' }, + { label: 'New Opportunity', icon: 'Plus', actionType: 'modal', actionUrl: 'crm_create_opportunity' }, + { label: 'Forecast', icon: 'TrendingUp', actionType: 'url', actionUrl: '/reports/forecast' }, + { label: 'Export', icon: 'Download', actionType: 'script', actionUrl: 'crm_export_dashboard_pdf' }, ], }, // Date-range scrubber bound to a field on the underlying objects: dateRange: { field: 'close_date', defaultRange: 'this_quarter', allowCustomRange: true }, - // Filters applied to ALL widgets: + // Filters applied to ALL widgets globalFilters: [ { field: 'owner', label: 'Sales Rep', type: 'lookup', scope: 'dashboard', optionsFrom: { object: 'user', valueField: 'id', labelField: 'name' } }, @@ -179,11 +177,10 @@ export const SalesDashboard: Dashboard = { dataset: 'crm_opportunity_metrics', values: ['total_amount'], filter: { stage: { $nin: ['closed_won', 'closed_lost'] } }, layout: { x: 0, y: 0, w: 3, h: 2 }, - colorVariant: 'success', // the accent only + colorVariant: 'success', // the accent only compareTo: { kind: 'previousPeriod' }, }, - // Chart widget with comparison overlay. { id: 'revenue_vs_last_year', type: 'line', title: 'Revenue — This Year vs Last', @@ -227,23 +224,14 @@ const widgets: DashboardWidget[] = [ ### Period-over-period — `compareTo` -Set `compareTo` on any data-bound widget to add a second query against a -shifted time window. - -`compareTo` is `{ kind, dimension? }`. +`compareTo: { kind, dimension? }` on any data-bound widget adds a second +query against a shifted time window. | Key | Value | Behaviour | |:--|:--|:--| | `kind` | `'previousPeriod'` | The equal-length window immediately before the resolved one. | | `kind` | `'previousYear'` | The same window shifted back one calendar year. | -| `dimension` | dimension name, **optional** | Which time dimension's window to shift. Omit it when the selection dates exactly one — the executor resolves it. With zero or several it errors, naming the candidates; it never guesses. | - -The two bare `compareTo:` lines are a fragment, so `check:skill-examples` skips them. - -```typescript -compareTo: { kind: 'previousPeriod' } // one dated dimension -compareTo: { kind: 'previousYear', dimension: 'close_date' } // several — say which -``` +| `dimension` | dimension name, **optional** | Which time dimension's window to shift. Omit it when the selection dates exactly one — the executor resolves it. With zero or several it errors, naming the candidates; it never guesses: `{ kind: 'previousYear', dimension: 'close_date' }`. | * **Metric widgets** — a delta arrow plus a trend label from the kind (`vs previous period`). Its colour follows `polarity` (the measure's; an inline @@ -258,8 +246,14 @@ compareTo: { kind: 'previousYear', dimension: 'close_date' } // several — * **Requirements** — a comparison needs a **dated window** to shift. When the selection carries no time dimension with a date range (no resolvable date macro in the widget `filter`, no dashboard `dateRange`), the executor says so - rather than rendering a silently empty comparison column. The shifted query + rather than render an empty comparison column. The shifted query reuses the original `filter` shape and replaces only the date-bound clauses. +* **Date key** — the window travels to the dataset query as a time dimension + named after the date-range field (`dateRange.field`, default `created_at`), + so the dataset must declare a date dimension with that name; else the query + is refused `400 INVALID_FIELD`, naming the remedy. For a related-record date + path, declare a date dimension over it (`field: 'account.signed_at'`) + under any name. No author-time check catches it yet. ```typescript @@ -304,6 +298,13 @@ defineDataset({ // language (matched, never translated; one word names one member), and a // one-sentence business `description`, never a prompt. Neither warns: // `dataset-member-no-vocabulary`. +// A word with two readings (`overdue`) the AI must ask about, not pick: +// make it a synonym of a measure in EACH of two datasets (asked whenever +// the asker can read both). In one dataset a repeated synonym is refused: +// put the word inside each reading's label or synonym (`overdue invoices`, +// `overdue tasks`); it then equals neither and the platform MAY offer both +// as candidates to ask about. Not guaranteed: an exact match on a +// readable member suppresses them. // A money measure may set `currency` (ISO 4217, e.g. `'USD'`). Chain: // measure `currency` → the field's `defaultCurrency` (`fixed` only) → // tenant `localization.currency`; omit it for counts. A @@ -338,8 +339,6 @@ const signedByMonth: DashboardWidget = { id: 'signed_by_month', type: 'line', "spent_sum / 616000". * **Combines with `compareTo`** — the comparison query is issued with the same granularity, so the muted overlay aligns bucket-for-bucket. -* **Rule of thumb** — `day` for ≤30d windows, `week` for ~90d, `month` for - 6–12 months, `quarter` for multi-year, `year` for retention / compliance. ### Widget `options` — the five declared keys @@ -372,13 +371,12 @@ behind it; **drill-to-record** opens one record. * **`table` / `pivot` widgets drill through.** Clicking an aggregated table row or pivot cell opens a side drawer listing the underlying records. The dataset preserves each grouped row's raw group keys, so the drawer filters to the - *exact* records (no label→id guessing). Automatic — no per-widget config. + *exact* records. Automatic — no per-widget config. * **The drilled record list drills to record.** Any row in that drawer opens the - single record's detail, completing the **group → records → record** chain. + single record's detail. * **Escape hatch — "Open in list →".** The drawer header offers a link to the object's *full* list page (sort / bulk-select / export / shareable URL), - scoped by the same drill filter. The in-place drawer is the default (peek - without losing the dashboard). Today a relationship-path dimension + scoped by the same drill filter. Today a relationship-path dimension (`account.industry`) gets the drawer only, no link. * **`metric` / `chart` widgets are not click-drillable** in the dataset form (they render the aggregate only; `compareTo` still applies). Surface the detail @@ -403,9 +401,9 @@ export const PipelineCoverageReport = defineReport({ label: 'Pipeline Coverage (Quarter)', type: 'matrix', dataset: 'crm_opportunity_metrics', - rows: ['forecast_category'], // down axis - columns: ['close_date'], // across axis — matrix pivots rows × columns - values: ['amount_sum'], // measures placed in the cells + rows: ['forecast_category'], // down axis + columns: ['close_date'], // across axis — matrix pivots rows × columns + values: ['amount_sum'], // measures placed in the cells runtimeFilter: { stage: { $ne: 'closed_lost' } }, // Period: ONE `type: 'date'` dataset dimension, not a dashboard-style raw `field`. dateRange: { dimension: 'close_date', defaultRange: 'this_year' }, @@ -454,18 +452,18 @@ import { defineCube } from '@objectstack/spec/data'; export const opportunityCube = defineCube({ name: 'crm_opportunity', title: 'Opportunities', - sql: 'opportunity', // underlying object name (snake_case) + sql: 'opportunity', // underlying object name (snake_case) public: true, measures: { - count: { label: 'Count', type: 'count', sql: '*' }, - amount: { label: 'Total Amount', type: 'sum', sql: 'amount', format: 'currency' }, + count: { label: 'Count', type: 'count', sql: '*' }, + amount: { label: 'Total Amount', type: 'sum', sql: 'amount', format: 'currency' }, }, dimensions: { - stage: { label: 'Stage', type: 'string', sql: 'stage' }, - close_date: { label: 'Close', type: 'time', sql: 'close_date', + stage: { label: 'Stage', type: 'string', sql: 'stage' }, + close_date: { label: 'Close', type: 'time', sql: 'close_date', granularities: ['day', 'week', 'month', 'quarter', 'year'] }, account_industry: { label: 'Industry', type: 'string', sql: 'account.industry' }, - owner: { label: 'Owner', type: 'string', sql: 'owner' }, + owner: { label: 'Owner', type: 'string', sql: 'owner' }, }, }); ``` diff --git a/.claude/skills/objectstack-ui/rules/list-views.md b/.claude/skills/objectstack-ui/rules/list-views.md index 0fffa9e..2e11a57 100644 --- a/.claude/skills/objectstack-ui/rules/list-views.md +++ b/.claude/skills/objectstack-ui/rules/list-views.md @@ -5,14 +5,14 @@ - [End-User Quick Filters](#end-user-quick-filters-userfilters-adr-0047) · [Toolbar Search](#toolbar-search-searchablefields-adr-0061) - [Configuring Kanban Views](#configuring-kanban-views) - [Configuring Gantt Views](#configuring-gantt-views) -- [Form Views](#form-views) · [Master-Detail Forms](#master-detail-forms-parent--child-line-items) +- [Forms](#forms) · [Master-Detail Forms](#master-detail-forms-parent--child-line-items) ## Configuring a List View ### The `defineView` container (`*.view.ts` file shape) Views ship **inside a `defineView` container** — one per object, aggregating -the default `list`, named `listViews` and named `formViews`. The loader +the default `list` and named `listViews`. The loader expands it into `.` view items that power the view switcher. @@ -27,9 +27,6 @@ export const CaseViews = defineView({ open: { label: 'Open', type: 'grid', data, columns: ['subject', 'status'], filter: [{ field: 'status', operator: 'equals', value: 'open' }] }, }, - formViews: { // named: a `form` action targets `support_case.triage` - triage: { type: 'simple', data, sections: [{ group: 'case_detail' }] }, - }, }); ``` @@ -99,7 +96,7 @@ matches when **any** of its rules does — still ANDed with the elements beside ```typescript filter: [ - { or: [ // open, OR urgent … + { or: [ // open, OR urgent … { field: 'status', operator: 'equals', value: 'open' }, { field: 'priority', operator: 'equals', value: 'urgent' }, ] }, @@ -203,22 +200,7 @@ ingress gate refuses any entry outside the allowed set before the engine runs. Both diagnostics are **errors**: `os validate` fails the build. -To remove the search box, toggle the affordance instead: - - -```typescript -import { defineView } from '@objectstack/spec'; - -const data = { provider: 'object' as const, object: 'support_case' }; - -export const AuditViews = defineView({ - list: { - label: 'Audit Log', type: 'grid', data, - columns: ['case_number', 'status'], - userActions: { search: false }, - }, -}); -``` +To remove the search box instead: `userActions: { search: false }` on the list. **Searching by a related record's title:** mirror it into a **stored** field and narrow to that (objectstack-data → Search Fields). @@ -264,11 +246,11 @@ const board: ListView = { data: { provider: 'object', object: 'project_task' }, columns: ['title', 'owner_id', 'priority'], kanban: { - groupByField: 'status', // a select field + groupByField: 'status', lanes: ['todo', 'in_progress', 'review'], summary: { type: 'sum', field: 'estimate_hours' }, // each lane's foot statistic - showFieldLabels: false, // optional, default true: cards name each field - hideEmptyFields: false, // optional, default true: cards drop an empty field + showFieldLabels: false, // optional, default true: cards name each field + hideEmptyFields: false, // optional, default true: cards drop an empty field columns: ['title', 'owner_id', 'priority'], // fields shown on each card cardFooter: { comments: true, attachments: true }, // optional foot counts }, @@ -276,13 +258,15 @@ const board: ListView = { }; ``` +> Group by a single-valued `select`, boolean or lookup: a text, number or date +> field or a multi-valued one warns `list-view-kanban-group-field-uncategorical`. + > `lanes` chooses the lanes and their order, not the records: a record whose > value is unlisted lands in `Uncategorized`, so filter the view to keep records > off the board. Omit it to draw every option in its own order; a value that is > not one of the field's inline options, or listed twice, fails `os validate`. -> `summary`, `showFieldLabels` and `hideEmptyFields` are optional. `summary.type`: -> `none`, `count`, or `sum` / `avg` / `min` / `max` of a `field`, computed by the +> `summary.type`: `none`, `count`, or `sum` / `avg` / `min` / `max` of a `field`, computed by the > query over every record of the lane, lanes over a lookup field included. Omit > `summary` to keep the older `summarizeField`'s sum, or no statistic without it. > `cardFooter` takes those two members only: `comments` counts the record's open @@ -344,35 +328,54 @@ group, **no resize handles**. Leaf tasks resize unless `locked: true`. --- -## Form Views +## Forms -**An object's New and Edit forms are not form views.** The dialogs, the -full-page form (`editMode: 'page'`) and a create or edit an action opens are -built from the object: its fields, sectioned by `fieldGroups` in array order, -following each field's own rules. Authored there: +**An object's New and Edit forms are not `form` items.** The dialogs, the +full-page form (`editMode: 'page'`) and an action's create or edit are +built from the object's fields, sectioned by `fieldGroups` in array order, +following each field's rules (`visibleWhen`, `readonlyWhen`, +`requiredWhen`: objectstack-data → Conditional Field Rules). Authored there: -- `collapse: 'collapsed'` on a `fieldGroups` entry folds a rarely filled - section. -- `showOnCreate: false` on a field leaves it off every create surface; edit, +- `collapse: 'collapsed'` on a `fieldGroups` entry folds a rarely filled section. +- `showOnCreate: false` leaves a field off every create surface; edit, the record page and lists keep it. Beside `required: true` it is refused, whatever its `defaultValue`: keep it on create, or make it `requiredWhen`. -- Dialog size and column count are derived, never authored: +- Dialog size and columns are derived, never authored: [Record Presentation](./navigation.md#record-presentation--surface-width--columns-are-auto-derived). -A container's `form`, `formViews.default` and `formViews.create` still parse -and steer no create or edit form; `os validate` warns -`form-view-internal-not-loaded` unless a `type: 'form'` action's literal -`target` names it: it loads as a named form. These load: +**A form is a `form` item in the stack's `forms:`** (`defineForm`, +`*.form.ts`); `views:` holds lists only. Something opens it: a +`sharing.publicLink` (a public form), or an action of `type: 'form'` whose +`target` is its name. With neither, `os validate` warns `form-consumer-less`. -**A named form** is a `formViews` entry under any other key, registered as -`OBJECT.key`; an action of `type: 'form'` whose `target` is that name opens it -on its own page (`/forms/:name`). Its `type` is `simple` (stacked sections, the -default), `tabbed` (a tab per section) or `wizard` (a step per section, each -listing `fields`, never `{ group }`). It draws no child line items. + +```typescript +import { defineForm } from '@objectstack/spec'; + +export const WebToLead = defineForm({ + name: 'crm_lead.web_to_lead', // OBJECT.KEY: the prefix equals `object` + object: 'crm_lead', + sections: [{ group: 'contact_info', columns: 2 }], + // public: GET /api/v1/forms/contact-us, POST …/submit + sharing: { enabled: true, allowAnonymous: true, publicLink: 'contact-us' }, +}); +``` -**A public form** is a form view with -`sharing: { enabled: true, allowAnonymous: true, publicLink: 'slug' }`: -Web-to-Lead at `GET/POST /api/v1/forms/:slug`. +- The body is at the top level. `viewKind`, `config` and `data` are refused: + a form is bound with `object`. +- `type`: `simple` (stacked, the default), `tabbed` (a tab per + section) or `wizard` (a step per section, each listing `fields`, never + `{ group }`). A form draws no child lines. +- A form left open on a public address another form holds is refused, naming + both (`form-public-address-taken`; a save answers `409 FORM_ADDRESS_TAKEN`). + A form holds its address while `publicLink` names it, switched on or off: + clear the retired form's link. +- Translate under `forms.NAME`: `.label`, `.title`, `.description`, + `.submitBehavior.*`, `.sections.SECTION.*`; a section with no key there + reads `objects.OBJECT._sections.SECTION`. +- ⛔ Never author a form inside a view (a container's `form:` or `formViews`, + a `viewKind: 'form'` item). Move one an action opens, or with a `publicLink` + or `overrides`, to `forms:`; delete only the rest: New and Edit never loaded it. ## Master-Detail Forms (parent + child line items) @@ -384,8 +387,7 @@ custom page. Prefer, in order: MODEL, the parent declares `fieldGroups: [{ key: 'lines', label: 'Lines', relatedList: 'invoice_line' }]`. Its standard New/Edit forms (modal, drawer, full-page) then draw the children there and save parent + children - in one atomic `/api/v1/batch`. Without the group nothing changes: the child - is a tab and the form has no lines. A parent or child + in one atomic `/api/v1/batch`. A parent or child declaring `enable.apiMethods` must list `'bulk'`, or that save is refused `405 OBJECT_API_METHOD_NOT_ALLOWED`. `inlineEdit` only picks how rows are edited, `'grid'` / `'form'` or left out: @@ -403,10 +405,3 @@ authored on this side: a trailing **ghost** row always exists, so never add an untouched one is never persisted; a record-header action that inserts a priced line is [Actions](./actions.md)); `autofill: false` opts one column out of the typeahead copy; and that page block's `taxRateField` overrides which parent field drives the totals. - -## Field Conditional Rules in Forms - -Conditions that belong to a field's lifecycle — `visibleWhen`, `readonlyWhen`, -`requiredWhen` — are declared on the **DATA MODEL field**, not in the form view; -ObjectUI forms consume them. Their semantics and server behaviour: -[objectstack-data → Conditional Field Rules](../../objectstack-data/SKILL.md#conditional-field-rules). diff --git a/.claude/skills/objectstack-ui/rules/navigation.md b/.claude/skills/objectstack-ui/rules/navigation.md index c5cfc83..a429ad5 100644 --- a/.claude/skills/objectstack-ui/rules/navigation.md +++ b/.claude/skills/objectstack-ui/rules/navigation.md @@ -161,7 +161,7 @@ export const TaskWorkbenchPage = definePage({ ## Record Presentation — surface, width & columns are auto-derived -An object's New / Edit / detail is built from its `fieldGroups`, never a form view: +An object's New / Edit / detail is built from its `fieldGroups`, never a `form` item: you do **not** author its surface, overlay width or column count, all derived from the client's screen. **Write the data (fields, `fieldGroups`); let the platform lay it out.** @@ -178,10 +178,10 @@ it out.** - **Column count.** On those forms, not authored: the grid follows its **real rendered width**, 1 column in a narrow drawer to 4 on a wide page. On a named or public form, authored per section: `{ group: 'contact_info', columns: 2 }` - (1–4; 1 on a phone). A form view's own `columns` is not read by the form page + (1–4; 1 on a phone). A form's own `columns` is not read by the form page today. - **`sections` are the escape hatch — reach for them last.** New and Edit - never read them ([Form Views](./list-views.md#form-views)); a named or + never read them ([Forms](./list-views.md#forms)); a named or public form and a page's `record:details` or form block do. The ladder: (1) **derive** — declare `fieldGroups`, author no `sections`; (2) **reference** — a section names a declared group, `{ group: 'contact_info' }`, diff --git a/.claude/skills/objectstack-ui/rules/record-page.md b/.claude/skills/objectstack-ui/rules/record-page.md index 38d66ee..ec48c87 100644 --- a/.claude/skills/objectstack-ui/rules/record-page.md +++ b/.claude/skills/objectstack-ui/rules/record-page.md @@ -37,7 +37,7 @@ refused by name. `isDefault: true` makes it the object's default record page. that looks nothing like the default (a chart tab, a bespoke strip) is `kind: 'full'`: `regions` drawn as authored ([Pages](./pages.md)). A phone and the drawer draw the standard page (steps 1–3); no key keeps a full page there, only a page named in the URL (a print page) draws everywhere. The standard page -draws no `record_section` action: one that must show there also lists `record_more`. +draws no `record_section` action: one that must show there also lists `record_page`. **5 · On an object's list the name opens the page, its hover icon the drawer.** `navigation.mode` is deprecated there: `drawer`, `page`, `new_window` change diff --git a/.claude/skills/objectstack-upgrade/SKILL.md b/.claude/skills/objectstack-upgrade/SKILL.md index adee7c0..12ed4b4 100644 --- a/.claude/skills/objectstack-upgrade/SKILL.md +++ b/.claude/skills/objectstack-upgrade/SKILL.md @@ -16,7 +16,7 @@ license: Apache-2.0 compatibility: Requires `@objectstack/spec` and `@objectstack/cli` at the TARGET major; the chain replays from the spec's `MIGRATION_SUPPORT_FLOOR`. No network access required. metadata: author: objectstack-ai - version: "19.0.0-next.2" + version: "19.0.0-next.3" domain: process tags: upgrade, migration, protocol, major, retired-keys, tombstone, conversions, validate, report --- @@ -25,42 +25,52 @@ metadata: > **preflight → mechanical chain → semantic residue → acceptance report** -## ⛔ The boundary — read this before the first command - -**Never hand-write a rewrite the chain already applies.** If a key was renamed, -the conversion table knows the rename; running the chain attributes each rewrite -to a hop and proves the result is schema-valid. A hand-edit does neither, and it -silently diverges the moment the chain gains an entry. - -**Never add a tolerant read to make old metadata load.** No `??` alias, no -"accept both spellings" branch, no coercion in the project's own code. A key was -retired because nothing enforced it or because exactly one spelling survives; -re-admitting the old one at the consumer is how the defect the retirement closed -comes back inside the customer's repo, where no gate can see it. - -**Never resolve a residue item by guessing the owner's intent.** The residue -exists precisely because it is a business decision. The rule for when you decide -alone and when you ask is in [Layer 2](#decide-alone-or-ask) — it is the most -important paragraph in this skill. - -**Never report "upgraded" without the acceptance artifacts.** `validate` green -plus the report is the machine criterion. Absent either, the status is -*in progress*, whatever the diff looks like. - -**One `conversionId` per commit**, where the project's review culture allows it. -The id is the commit's subject line and its justification. - ---- +## ⛔ The boundary + +- **Never hand-write a rewrite the chain already applies.** The conversion table + knows the rename; the chain attributes each rewrite to a hop and proves the + result schema-valid. A hand-edit does neither, and silently diverges the + moment the chain gains an entry. +- **Never add a tolerant read to make old metadata load**: no `??` alias, no + "accept both spellings" branch, no coercion in the project's own code. It + brings the defect the retirement closed back inside the customer's repo, where + no gate can see it. +- **Never resolve a residue item by guessing the owner's intent** — it is a + business decision. [Decide alone, or ask](#decide-alone-or-ask) is this + skill's most important paragraph. +- **Never report "upgraded" without the acceptance artifacts.** `validate` green + plus the report is the machine criterion; absent either, the status is + *in progress*. +- **One `conversionId` per commit**, where the project's review culture allows + it: the id is the commit's subject line and its justification. + +## First checks + +1. **`--from` is the major the metadata was authored against, not the one + installed.** Read `manifest.engines.protocol`, a range, and take its floor: + `'^17'` → `--from 17`, `'>=15 <18'` → `--from 15`, never the upper bound. + Else read the lockfile's history. If the two disagree, ask — ⛔ never default + to the lower one. +2. **Keep a control**: `os validate` on the un-upgraded source, in + `.upgrade/`. A rule finding already in it is pre-existing, not upgrade residue. +3. **Read the prescriptions from the install, never from memory**: the chain's + `--json` result, and the `spec-changes.json`, tombstone `[REMOVED] …` text + and `CHANGELOG.md` inside `@objectstack/spec`. ⛔ Every count you report is a + reading of *this* install. +4. **Re-install the skills.** A lock entry reading `sourceType: github` (from + `skills add`) is skipped by the sync, exit 0, and the agent keeps reading the + old major's skill text. ## Quickstart ```bash -# 0 · preflight — what major is this project on, what major is installed? +# 0 · preflight — the authored major, the installed one grep -rn "protocol" objectstack.config.ts package.json | head node -p "require('@objectstack/spec/package.json').version" -# 1 · mechanical — replay the chain (writes only --out; --write also rewrites the sites it can prove) -os validate > .upgrade/validate-before.txt 2>&1 || true # the control, kept +# 1 · mechanical — replay the chain (trap 1) +mkdir -p .upgrade +os validate > .upgrade/validate-before.txt 2>&1 || true # the control, kept os migrate meta --from 16 --step os migrate meta --from 16 --json > .upgrade/migrate.json os migrate meta --from 16 --out .upgrade/migrated.stack.json @@ -69,413 +79,81 @@ os migrate meta --from 16 --out .upgrade/migrated.stack.json node -e "console.log(require('fs').readFileSync(require.resolve('@objectstack/spec/package.json').replace('package.json','spec-changes.json'),'utf8'))" > .upgrade/spec-changes.json # 3 · acceptance — all four, not three -os validate # green (compare against validate-before.txt) -tsc --noEmit # tombstones type the retired keys as `never` -os migrate meta --from 16 --to 18 --json # `applied` [] and no `replayedNothing` (see §3.3) -# → write .upgrade/REPORT.md (template in §3.4) -``` - ---- - -## 0 · Preflight - -### Establish the FROM major — do not guess it - -`--from` is the protocol major the metadata was **authored** against, not the -one installed. Three sources, in order of authority: - -1. **`manifest.engines.protocol`** in the stack config — the declared answer, - checked by the boot handshake. It is a **range**, not a version: every - scaffold and example writes the caret form (`engines: { protocol: '^19' }`), - and an exact `'16.0.0'` is only a range of one. Take the major it *targets* — - the floor: `'^17'` → `--from 17`, `'>=15 <18'` → `--from 15`, never the - upper bound. -2. **The last `@objectstack/spec` major the project ever installed** — read the - lockfile history (`git log -p pnpm-lock.yaml | grep -m5 '@objectstack/spec'`) - when the manifest is absent or stale. -3. **Ask.** A manifest that says 16 on a project last touched two years ago is a - claim, not a measurement. If (1) and (2) disagree, settle it — ⛔ never - default to the lower one: a default flip ([3.3](#33-validate)) stamps its - constraint onto a source already past that major. - -Arriving several majors late is the designed-for case: `os migrate meta --from 16` -replays every step in order, with no requirement to upgrade one major at a time — -down to the chain's support floor, 16 today. - -### Make the work reviewable before you change anything - -```bash -git checkout -b upgrade/protocol-17 -mkdir -p .upgrade -``` - -The `.upgrade/` directory is the deliverable's workspace: the machine outputs -(`migrate.json`, `migrated.stack.json`, `spec-changes.json`, `retired-names.txt`) -and the human output (`REPORT.md`). Keeping them in the repo for the review, and -deleting them on merge, is the usual arrangement — decide it with the owner. - -### Re-install the skills from the moved catalog - -A 17.x project's skills came from `skills add`; their `skills-lock.json` entries -read `sourceType: github`, so the sync skips them (exit 0) and the agent keeps -reading 17.x skill text. Remove them (a missing name is skipped; -`objectstack-pm-dispatch` is not in the 18 catalog, only an older install has it), add -`@objectstack/skills` at the installed spec's version with the manager that -installed the project, copy it: - -```bash -npx skills remove objectstack-ai objectstack-api objectstack-automation \ - objectstack-data objectstack-formula objectstack-i18n objectstack-platform \ - objectstack-pm-dispatch objectstack-query objectstack-ui objectstack-upgrade objectui -y -pnpm add -D "@objectstack/skills@$(node -p "require('@objectstack/spec/package.json').version")" -# npm: npm install --save-dev "@objectstack/skills@…" · yarn: yarn add -D "@objectstack/skills@…" -npx skills@1.7.2 experimental_sync --agent claude-code --copy -y -``` - ---- - -## 1 · Mechanical layer — invoke the chain - -### What `os migrate meta` actually does - -```bash -os migrate meta --from 16 # replay 16 → current -os migrate meta --from 16 --step # per-hop checkpoint (bisect a failure) -os migrate meta --from 16 --to 17 # stop at a specific major -os migrate meta --from 16 --json # machine-readable result -os migrate meta --from 16 --out migrated.json # write the canonicalized stack -os migrate meta --from 16 --write # rewrite the proven sites in place -os migrate meta --from 16 apps/crm/objectstack.config.ts # pick the stack explicitly +os validate # green (compare against validate-before.txt) +tsc --noEmit # tombstones type the retired keys as `never` +os migrate meta --from 16 --to 18 --json # `applied` [] and no `replayedNothing` (trap 2) +# → write .upgrade/REPORT.md (template: §3.4) ``` -It loads the stack config, normalizes it **without** applying the load-time -conversion pass, replays each major's conversions as a chain hop, and then -parses the result against the current schema to prove the output is valid. What -it prints: - -- **`Applied N mechanical change(s)`** — one line per rewritten site, as - `path: from → to (conversionId)`. This is the diff, already attributed. -- **`N manual change(s) require your judgment`** — the chain's semantic entries - for the majors you crossed, each with a `why` and a `verify` line. These are - Layer 2's input, not a warning to dismiss. -- **`Migrated stack is schema-valid`** — or the warning that it is not yet, - which means a residue item is still blocking the parse. - -### ⚠ The one fact that surprises every operator - -**By default `os migrate meta` rewrites no source file.** It lists the -mechanical edits and writes only the `--out` JSON snapshot. `--write` rewrites -in place each edit it can trace to one literal in one project file, lists every -other with the reason it was not written, never writes a semantic change, and -if re-running the chain over the written files disagrees, restores every file -and exits 1. - -### Stored rows: rehydration replays what the release carries - -A deployment's `sys_metadata` rows are the other subject. At read time the -metadata loader and the ObjectQL plugin pass each stored row through -`applyConversionsToStoredItem`, which replays every conversion the release still -carries, **including entries retired from the load path**. 18.3 drops those -retired at or below 16.x, so a row still in such a shape is no longer rewritten. - -Rehydration is a read-time projection: the rows on disk keep their old shape, -and you never hand-edit `sys_metadata`. ⛔ Run the stored pass before you move -(on 18.2 or earlier for such a row) — read-only by default: - - ```bash - os migrate meta --stored # preview, writes nothing - os migrate meta --stored --type view --type object # narrow the pass - os migrate meta --stored --apply --yes # rewrite the rows - ``` - - ⛔ **`--yes` is not optional for you.** Without it `--apply` asks for - confirmation, and in any non-TTY — every agent session — it refuses instead, - exiting 1 with `confirmation_required`. - - `--stored` takes no `--from`: a stored row carries its own history, so the - pass replays the whole chain. - -### Data migrations are not metadata migrations - -When the chain crosses into a major carrying per-deployment data gates, the run -ends by naming each one, what staying un-run costs, and that `--apply` is the -only writing mode. Read that output rather than re-deriving it. What it cannot -tell you is whether they have *run*: that happens against each deployment's own -database, and nothing in the metadata upgrade observes it. - -⛔ **Carry every gate the run printed into the report as `pending`, by name.** A -gate nobody was told about is served by nobody. - ---- - -## 2 · Semantic residue — the part that is yours - -A conversion can rename a key, drop a dead one, or lift a value onto its -declared block. It cannot make a decision. Everything it cannot do lands here. - -### 2.1 Harvest the instruction sources — all of them ship - -The prescriptions are not on a docs site you have to be online for. They ship -inside the installed package. **Measured** against the published -`@objectstack/spec` file list: - -| Source | Where, in a consumer project | Carries | -|:--|:--|:--| -| **Chain result** | `os migrate meta --from N --json` → `.specChanges` | The conversions + semantic entries for exactly the majors you cross. **Start here** — it is computed from the installed spec, so it can never be stale. | -| **D4 projection** | `node_modules/@objectstack/spec/spec-changes.json` | The same data for every major, offline: `perMajor[].converted` and `perMajor[].migrated`. | -| **Tombstone prescriptions** | `node_modules/@objectstack/spec/json-schema/**` and `src/**/*.zod.ts` | Every retired key's `[REMOVED] …` fix-it text, greppable. | -| **FROM → TO tables** | `node_modules/@objectstack/spec/CHANGELOG.md` | The per-retirement narrative, including the "what to write instead" table. This is why the package ships its changelog. | -| **The error itself** | Your parse / `tsc` output | The same prescription string, delivered at the moment you hit it. | - -```bash -# every tombstone prescription the installed spec carries, deduped (`| wc -l` sizes it) -grep -rho '\[REMOVED\][^"]*' node_modules/@objectstack/spec/json-schema/ | sort -u - -# protocol version, support floor, and this crossing's conversion / semantic counts -node -e " - const p = require.resolve('@objectstack/spec/package.json'); - const j = require(p.replace('package.json','spec-changes.json')); - const to = parseInt(j.protocolVersion, 10); - const e = j.perMajor.find(x => x.to === to); - console.log(j.protocolVersion, 'floor', j.supportFloor, '| →', to + ':', - e.converted.length, 'converted,', e.migrated.length, 'semantic'); -" - -# the FROM → TO table for one retired key -grep -n -B4 -A20 'transform' node_modules/@objectstack/spec/CHANGELOG.md | less -``` - -⛔ **Never carry a remembered count or a pinned table into the report.** Every -number here is a reading of *this* install; measure it at the start of the -upgrade and again in the report. - -> **Not reachable from a consumer project**, so do not send anyone there: the -> conversion and migration registries (`src/conversions/registry.ts`, -> `src/migrations/registry.ts`) and the platform repo's generated upgrade guide -> are **not** in the published package — only `src/**/*.zod.ts` is. - -### 2.2 The three residue classes - -**R1 · Intent choice — a key was retired with no single lossless target.** -The conversion drops the key (so the project parses) and, where it matters, -emits a notice naming the site. What the key was *for* still has to go -somewhere, and where is a business statement. - -**R2 · Custom code calling a retired API.** The chain's semantic entries name -these: a service slot that no longer exists, an engine method that was removed, -a context field that was renamed. Metadata parses fine; the project's own -TypeScript is what breaks — or worse, keeps compiling while reading `undefined`. - -**R3 · Prose that still teaches the old shape.** READMEs, comments, ADRs, seed -fixtures, and the project's own AI conventions file. Nothing fails, and the next -agent to read the repo re-authors the retired shape from it. - -**[2.3 A worked R1 — the retired field-mapping `transform`](./references/examples-upgrade.md#23-a-worked-r1--the-retired-field-mapping-transform)** - - - -### 2.4 Decide alone, or ask the owner - -**Decide it yourself when all three hold:** - -1. **The prescription names exactly one target.** The tombstone or conversion - summary gives a single FROM → TO, with the value unchanged. -2. **The evidence is in the project.** A grep in the repo settles it — the skill - that already owns the tool, the import that already exists, the field the - predicate already references. -3. **Being wrong fails a gate.** A mistaken choice breaks `tsc` or `validate` - rather than changing behaviour quietly. - -**Ask the owner when any one of these holds:** - -1. **Two or more real targets, and the choice is a business statement** — the - `transform` case above. -2. **The change is observable without a test failing** — security posture - (an authentication default), row visibility (an access predicate), retry - counts, retention. A wrong call here ships silently and is discovered by an - auditor. -3. **Capability has to be re-declared somewhere new**, so choosing wrong - *removes* a capability instead of breaking a build. Agent tooling that has to - move inside a specific skill is the canonical shape. -4. **The source is dead or undocumented in their repo** — nothing to decide - from. Say so; do not invent a rationale. - -**How to ask.** One message, per item, carrying: the site (file and path), the -prescription verbatim, the options with what each costs, your recommendation and -why, and what you will verify once they choose. Never a bare "how should I -handle `transform`?" — that hands the reading work back to the person with the -least context about the diff. - -**While you wait, do not stall the upgrade.** Park the item in the report as -`AWAITING DECISION`, keep the mechanical layer complete, and keep going. A -project can be schema-valid with open residue items; it just is not *done*. - -### 2.5 Working an R2 — retired APIs in the project's own code - -The chain's semantic entries are the search list. For each one, the surface it -names is a string you grep for in the project's own source: - -```bash -# from the chain's own output — the surfaces it says it cannot fix for you -os migrate meta --from 16 --json | node -e " - let s=''; process.stdin.on('data',d=>s+=d).on('end',()=>{ - for (const t of JSON.parse(s).todos) console.log(t.surface); - })" -# then, for each surface, search the project (not node_modules) -grep -rn "" src/ app/ --include='*.ts' --include='*.tsx' -``` - -One trap that has cost real upgrades a lap: **a rename is not always the fix.** -If the old read was itself wrong, renaming it migrates the defect rather than -the code. Read the semantic entry's `reason` before applying its `replacement`. - -### 2.6 Working an R3 — the prose sweep - -Run it last, once the shapes are settled, and run it over the whole repo: - -```bash -# every retired key name the installed spec knows, as a search list -grep -rho '\[REMOVED\] `[^`]*`' node_modules/@objectstack/spec/json-schema/ \ - | sed 's/.*`\(.*\)`.*/\1/' | sort -u > .upgrade/retired-names.txt -``` - -Then sweep the project's `*.md`, comments, seed fixtures, and its AI conventions -file. The conventions file matters most: it is what the next agent loads before -it writes anything, so a retired shape left there re-enters the codebase on the -next feature, long after the upgrade closed. - ---- - -## 3 · Acceptance — what "upgraded" means - -Four artifacts. Three are machine-checked; the fourth is the one a human reads. - -### 3.1 Typed - -```bash -tsc --noEmit -``` - -A retired key is not merely absent from the schema — it is declared as a -tombstone whose input type is `never`. Assigning anything to it fails to -compile, at the authoring site, before anything runs. A green `tsc` is therefore -positive evidence that no retired key survives in typed sources. - -### 3.2 Parse-gated - -The same tombstone rejects at parse time, and the rejection carries the -prescription rather than a generic "unrecognized key". This is the channel that -catches metadata `tsc` cannot see: JSON files, database rows, anything built at -runtime. You do not have to do anything to enable it — but you **do** have to -prove it is live for this project, because a schema that silently strips is -indistinguishable from one that accepts. See -[the reverse check](#reverse-check). - -### 3.3 Validate - -```bash -os validate # green is the criterion -os validate --strict # warnings become errors — agree with the owner whether this is the bar -``` - -`os validate` runs two passes: the protocol schema (where tombstones reject) and -the author-time rule set. Read the two separately — a rule finding about a -missing sharing model or an options-less choice field is a **pre-existing** -project-quality issue, not upgrade residue. Establish which is which by running -`os validate` **once before you start**, on the un-upgraded source, and keeping -that output as the control. - -> ### ⚠ A green `validate` does NOT mean the chain has nothing left to do -> -> Some conversions are **migration-chain-only**: the loader deliberately does -> not apply them and no tombstone rejects the old shape, because the change is a -> default flip rather than a rename — auto-applying it would stamp a constraint -> onto sources that deliberately omit it. This build ships none (every -> conversion it carries is tombstoned, so the parse refuses the old shape too), -> but a later one can, and the chain, not the parse, is what knows. -> -> A project carrying only such a shape validates **green** while the chain still -> has work. So `validate` green is necessary and not sufficient, and the -> criterion that closes the gap is a replay of the whole range you ported: -> -> ```bash -> os migrate meta --from --to --json -> # `applied` must be [] and `replayedNothing` absent -> ``` -> -> `--from ` proves nothing: `--to` defaults to the highest major -> this build carries a step for, so the range is empty — no step runs, `applied` -> is `[]` whatever the metadata holds, and the JSON says so with -> `replayedNothing` (its `widestRange` is `null` there: no wider range exists -> from that `--from`) — or it holds only the next major's step. `todos` is -> semantic residue, Layer 2's business, not a failure. - -**[3.4 The report — the human half](./references/examples-upgrade.md#34-the-report--the-human-half)** - - - -### 3.5 Prove the gate is real, do not assume it - -Make the parse gate fire once before you report it as evidence: take a value the -chain *would* have converted, put it back after migrating, and parse it. - -```bash -# a stack that still carries a retired key, fed straight to the schema -os validate .upgrade/residue-probe.config.mjs -``` - -Write the probe as a **plain data literal** — ⛔ no `define*` call. `os validate` -loads the config without authored-source mode, and every `define*` helper is a -`Schema.parse()`, so a probe written the way a real config is written throws -*inside the load* and never reaches the gate you are trying to prove. - -Predict the outcome **before** you run it, then record which one you actually -got — "it passed" is a different fact in every row: - -| Outcome | What it means | Your acceptance evidence | -|:--|:--|:--| -| Rejected, error carries the fix-it text | A tombstoned key. Not "unrecognized key", not a deprecation label — the prescription *is* the error. | The refusal itself, quoted. | -| Accepted, and the chain rewrites it | A conversion with a live load-path acceptance window. | The chain's diff — not the parse gate. | -| Accepted, and `validate` stays green | A migration-chain-only conversion ([3.3](#33-validate)). | Only the acceptance replay sees this class. | - -### 3.6 Stored rows: assert them, do not believe them - -The four artifacts above cover the authored sources. For a **deployment**, the -stored pass is itself the assertion — run it read-only and branch on the exit -code: - -```bash -os migrate meta --stored --json # 0 = every row canonical, 1 = work left -``` - -That is what makes "this deployment is on protocol N" a CI check — valid only -on the release you are leaving: one that dropped a row's conversions no longer -recognises it and answers `0`. Nothing gates on it having run. - ---- - -**[The v17-canonical shapes, compiled](./references/examples-upgrade.md#the-v17-canonical-shapes-compiled)** - -## Failure modes - -| Symptom | What it actually is | Fix | -|:--|:--|:--| -| `migrate meta` reports changes, but the files are unchanged | Working as designed — the default run only lists. | Pass `--write`, or port the printed edits by hand; then replay the ported range to confirm 0 changes. | -| The acceptance replay still applies changes | The port is incomplete, or a source builds metadata at runtime from a shape the chain never saw. | Diff against `--out`; grep for the `conversionId`'s surface in code that constructs metadata dynamically. | -| `validate` green, but a feature silently stopped working | An R2 residue item: code reading a renamed key now reads `undefined`. | Exercise the path for real. A green parse says nothing about a `??` chain in the project's own code. | -| `validate` reports findings that have nothing to do with retired keys | The author-time rule pass, not the schema pass. | Diff against the pre-upgrade `validate` control. Pre-existing findings are not this upgrade's scope. | -| A retired key round-trips without error | The schema carrying it is not strict and the key is being stripped, or the key still has a live load-path window. | Determine which — the two need different acceptance evidence. See [the reverse check](#reverse-check). | -| `--apply` refused / stored-only flag rejected | `--apply`, `--yes`, `--force`, `--type`, `--database-url` mean something only with `--stored`. | Add `--stored`, or drop the flag; the authored-source chain writes only `--out` and, with `--write`, the sources. | -| `MigrationFloorError` | `--from` is older than the chain's support floor. | Upgrade to the floor by an older route first; the floor is a release-policy boundary, not an oversight. | - -Scripting the run instead of reading it? Every `--json` failure above carries a -stable `error` code to branch on — `stored_only_flag`, `missing_from_major`, -`unsupported_from_major`, `confirmation_required`, `database_busy` — and the -prose row is the same fact for a human. +## Traps + +1. **By default `os migrate meta` rewrites no source file.** It prints each edit + as `path: from → to (conversionId)` and writes only `--out`. `--write` + rewrites an edit it can trace to one literal in one project file, lists every + other with the reason, and never writes a semantic change. Port the printed + edits by hand, or pass `--write` and port those it only lists; then replay + (trap 2). +2. **A green `validate` does not mean the chain has nothing left.** A + migration-chain-only conversion (a default flip) has no tombstone, so the old + shape validates. Replay the range you ported, + `os migrate meta --from --to --json`: + `applied` must be `[]` and `replayedNothing` absent. `--from ` + names an empty range and proves nothing. +3. **Stored `sys_metadata` rows are rewritten only at read**, by + `applyConversionsToStoredItem`, and only while the installed release carries + their conversions: 18.3 drops those retired at or below 16.x. ⛔ Before you + move (on 18.2 or earlier for such a row) run `os migrate meta --stored`, a + preview, then `os migrate meta --stored --apply --yes` — without `--yes` any + non-TTY is refused, `confirmation_required` — until + `os migrate meta --stored --json` exits 0. A release that dropped the + conversions answers 0 whatever the row holds. Never hand-edit `sys_metadata`. +4. **Data migrations are not metadata migrations.** The run names each + per-deployment gate; nothing in the upgrade observes whether it ran. ⛔ Carry + every gate it printed into the report as `pending`, by name. +5. **R2, code on a retired API, can keep compiling while it reads `undefined`.** + Grep the project's source for each `todos[].surface` of the `--json` result, + and read the entry's `reason` before its `replacement`: if the old read was + wrong, a rename migrates the defect. +6. **R3, prose that still teaches the old shape, fails nothing**: the next agent + re-authors it from a README, a comment, a seed fixture or the AI conventions + file. Sweep the whole repo last. +7. **Prove the parse gate once, with a plain data literal** — ⛔ no `define*` + call, which throws inside the load and never reaches the gate. A retired key + that still parses is stripped or in a load-path window: find which. + +## Decide alone, or ask + +**R1, an intent choice**: a key retired with no single lossless target. The +conversion drops it so the project parses; where its purpose goes is a business +statement. + +**Decide yourself when all three hold:** the prescription names exactly one +FROM → TO with the value unchanged; a grep in the project settles the evidence; +being wrong breaks `tsc` or `validate` rather than changing behaviour quietly. + +**Ask the owner when any one holds:** two or more real targets; the change is +observable with no test failing (an authentication default, row visibility, +retry counts, retention); a capability must be re-declared somewhere new, so a +wrong choice removes it; the source is dead or undocumented — say so, do not +invent a rationale. + +Ask in one message per item: the site, the prescription verbatim, the options +and what each costs, your recommendation, what you will verify. Park it in the +report as `AWAITING DECISION` and keep the mechanical layer moving. + +## Where to go + +| Section | For | +|:--|:--| +| [0 · Preflight](./references/examples-upgrade.md#0--preflight) | the FROM major's sources, `.upgrade/`, the skills re-install | +| [1 · Mechanical layer](./references/examples-upgrade.md#1--mechanical-layer) | what a run does and prints, stored rows, data gates | +| [2 · Semantic residue](./references/examples-upgrade.md#2--semantic-residue) | where the prescriptions ship, a worked R1 (`transform`), the R2 and R3 searches | +| [3 · Acceptance](./references/examples-upgrade.md#3--acceptance) | the four artifacts, the `REPORT.md` template, the reverse check's outcomes | +| [Failure modes](./references/examples-upgrade.md#failure-modes) | symptom → cause → fix, the `--json` error codes | +| [The v17-canonical shapes](./references/examples-upgrade.md#the-v17-canonical-shapes-compiled) | the examples after the upgrade, type-checked | ## Cross-skill routing -- Authoring the corrected metadata — load the domain skill for the shape you are - fixing (**data**, **ui**, **automation**, **ai**, **api**, **i18n**); each one - routes on to **formula** for any CEL you rewrite. -- Runtime, plugin, and CLI questions the upgrade turns up — load **platform**. +Authoring the corrected metadata: load the domain skill for the shape you fix +(**data**, **ui**, **automation**, **ai**, **api**, **i18n**); each routes on to +**formula** for any CEL you rewrite. Runtime, plugin and CLI questions: **platform**. diff --git a/.claude/skills/objectstack-upgrade/references/examples-upgrade.md b/.claude/skills/objectstack-upgrade/references/examples-upgrade.md index fbd8005..f440442 100644 --- a/.claude/skills/objectstack-upgrade/references/examples-upgrade.md +++ b/.claude/skills/objectstack-upgrade/references/examples-upgrade.md @@ -1,4 +1,162 @@ -# Upgrade — worked examples and templates (moved verbatim from SKILL.md) +# Upgrade — the layers in detail, worked examples and templates + +What `SKILL.md` does not hold, in the order of a run. + +## 0 · Preflight + +### Establish the FROM major — do not guess it + +Three sources, in order of authority: + +1. **`manifest.engines.protocol`** in the stack config — the declared answer, + checked by the boot handshake. Every scaffold and example writes the caret + form (`engines: { protocol: '^19' }`), and an exact `'16.0.0'` is only a + range of one. +2. **The last `@objectstack/spec` major the project ever installed** — read the + lockfile history (`git log -p pnpm-lock.yaml | grep -m5 '@objectstack/spec'`) + when the manifest is absent or stale. +3. **Ask.** A manifest that says 16 on a project last touched two years ago is a + claim, not a measurement. The lower major is never the default because a + default flip ([3.3](#33-validate)) stamps its constraint onto a source + already past that major. + +Arriving several majors late is the designed-for case: `os migrate meta --from 16` +replays every step in order, with no requirement to upgrade one major at a time — +down to the chain's support floor, 16 today. + +### Make the work reviewable before you change anything + +```bash +git checkout -b upgrade/protocol-17 +mkdir -p .upgrade +``` + +The `.upgrade/` directory is the deliverable's workspace: the machine outputs +(`migrate.json`, `migrated.stack.json`, `spec-changes.json`, `retired-names.txt`) +and the human output (`REPORT.md`). Keeping them in the repo for the review, and +deleting them on merge, is the usual arrangement — decide it with the owner. + +### Re-install the skills from the moved catalog + +A 17.x project's skills came from `skills add`; their `skills-lock.json` +entries are the ones the sync skips. Remove them (a missing name is +skipped; `objectstack-pm-dispatch` is not in the 18 catalog, only an older +install has it), add `@objectstack/skills` at the installed spec's version with +the manager that installed the project, copy it: + +```bash +npx skills remove objectstack-ai objectstack-api objectstack-automation \ + objectstack-data objectstack-formula objectstack-i18n objectstack-platform \ + objectstack-pm-dispatch objectstack-query objectstack-ui objectstack-upgrade objectui -y +pnpm add -D "@objectstack/skills@$(node -p "require('@objectstack/spec/package.json').version")" +# npm: npm install --save-dev "@objectstack/skills@…" · yarn: yarn add -D "@objectstack/skills@…" +npx skills@1.7.2 experimental_sync --agent claude-code --copy -y +``` + +## 1 · Mechanical layer + +### What `os migrate meta` actually does + +`os migrate meta --help` lists every flag and form; the Quickstart shows the +ones a run needs. + +It loads the stack config, normalizes it **without** applying the load-time +conversion pass, replays each major's conversions as a chain hop, and then +parses the result against the current schema to prove the output is valid. What +it prints: + +- **`Applied N mechanical change(s)`** — one line per rewritten site. This is + the diff, already attributed. +- **`N manual change(s) require your judgment`** — the chain's semantic entries + for the majors you crossed, each with a `why` and a `verify` line. These are + Layer 2's input, not a warning to dismiss. +- **`Migrated stack is schema-valid`** — or the warning that it is not yet, + which means a residue item is still blocking the parse. + +`--write` checks itself: if re-running the chain over the written files +disagrees, it restores every file and exits 1. + +### Stored rows: rehydration replays what the release carries + +A deployment's `sys_metadata` rows are the other subject. At read time the +metadata loader and the ObjectQL plugin pass each stored row through +`applyConversionsToStoredItem`, which replays every conversion the release still +carries, **including entries retired from the load path**. + +Rehydration is a read-time projection: the rows on disk keep their old shape. +The stored pass is read-only by default: + +```bash +os migrate meta --stored # preview, writes nothing +os migrate meta --stored --type view --type object # narrow the pass +os migrate meta --stored --apply --yes # rewrite the rows +``` + +`--stored` takes no `--from`: a stored row carries its own history, so the +pass replays the whole chain. + +### Data migrations are not metadata migrations + +When the chain crosses into a major carrying per-deployment data gates, the run +ends by naming each one, what staying un-run costs, and that `--apply` is the +only writing mode. Read that output rather than re-deriving it. The gates run +against each deployment's own database. A gate nobody was told about is served +by nobody. + +## 2 · Semantic residue + +A conversion can rename a key, drop a dead one, or lift a value onto its +declared block. It cannot make a decision. Everything it cannot do lands here. + +### 2.1 Harvest the instruction sources — all of them ship + +The prescriptions are not on a docs site you have to be online for. They ship +inside the installed package. **Measured** against the published +`@objectstack/spec` file list: + +| Source | Where, in a consumer project | Carries | +|:--|:--|:--| +| **Chain result** | `os migrate meta --from N --json` → `.specChanges` | The conversions + semantic entries for exactly the majors you cross. **Start here** — it is computed from the installed spec, so it can never be stale. | +| **D4 projection** | `node_modules/@objectstack/spec/spec-changes.json` | The same data for every major, offline: `perMajor[].converted` and `perMajor[].migrated`. | +| **Tombstone prescriptions** | `node_modules/@objectstack/spec/json-schema/**` and `src/**/*.zod.ts` | Every retired key's `[REMOVED] …` fix-it text, greppable. | +| **FROM → TO tables** | `node_modules/@objectstack/spec/CHANGELOG.md` | The per-retirement narrative, including the "what to write instead" table. This is why the package ships its changelog. | +| **The error itself** | Your parse / `tsc` output | The same prescription string, delivered at the moment you hit it. | + +```bash +# every tombstone prescription the installed spec carries, deduped (`| wc -l` sizes it) +grep -rho '\[REMOVED\][^"]*' node_modules/@objectstack/spec/json-schema/ | sort -u + +# protocol version, support floor, and this crossing's conversion / semantic counts +node -e " + const p = require.resolve('@objectstack/spec/package.json'); + const j = require(p.replace('package.json','spec-changes.json')); + const to = parseInt(j.protocolVersion, 10); + const e = j.perMajor.find(x => x.to === to); + console.log(j.protocolVersion, 'floor', j.supportFloor, '| →', to + ':', + e.converted.length, 'converted,', e.migrated.length, 'semantic'); +" + +# the FROM → TO table for one retired key +grep -n -B4 -A20 'transform' node_modules/@objectstack/spec/CHANGELOG.md | less +``` + +Measure each number at the start of the upgrade and again in the report; a +pinned table is not a reading. + +> **Not reachable from a consumer project**, so do not send anyone there: the +> conversion and migration registries (`src/conversions/registry.ts`, +> `src/migrations/registry.ts`) and the platform repo's generated upgrade guide +> are **not** in the published package — only `src/**/*.zod.ts` is. + +### 2.2 The residue classes + +**R1 · Intent choice.** Where it matters, the conversion that drops the key +also emits a notice naming the site. + +**R2 · Custom code calling a retired API.** The chain's semantic entries name +these: a service slot that no longer exists, an engine method that was removed, +a context field that was renamed. Metadata parses fine; the project's own +TypeScript is what breaks. ### 2.3 A worked R1 — the retired field-mapping `transform` @@ -34,6 +192,106 @@ ever passed through this mapping. Where the data really comes from, and whether it is right, only the owner can answer — exactly the kind of finding the report exists to surface. +### 2.4 Decide alone, or ask the owner + +The rule is in `SKILL.md`. What each condition looks like: + +- **One target**: the tombstone or conversion summary gives a single FROM → TO. +- **Evidence in the project**: the skill that already owns the tool, the import + that already exists, the field the predicate already references. +- **Two or more real targets**: the `transform` case above. +- **Observable without a test failing**: security posture, row visibility + (an access predicate). A wrong call here ships silently and is discovered by + an auditor. +- **Capability re-declared somewhere new**: agent tooling that has to move + inside a specific skill is the canonical shape. + +**How to ask.** Never a bare "how should I handle `transform`?" — that hands +the reading work back to the person with the least context about the diff. + +**While you wait, do not stall the upgrade.** A project can be schema-valid +with open residue items; it just is not *done*. + +### 2.5 Working an R2 — retired APIs in the project's own code + +The chain's semantic entries are the search list. For each one, the surface it +names is a string you grep for in the project's own source: + +```bash +# from the chain's own output — the surfaces it says it cannot fix for you +os migrate meta --from 16 --json | node -e " + let s=''; process.stdin.on('data',d=>s+=d).on('end',()=>{ + for (const t of JSON.parse(s).todos) console.log(t.surface); + })" +# then, for each surface, search the project (not node_modules) +grep -rn "" src/ app/ --include='*.ts' --include='*.tsx' +``` + +A key was retired because nothing enforced it or because exactly one spelling +survives, so the fix in that code is never a tolerant read of the old one. + +### 2.6 Working an R3 — the prose sweep + +Run it once the shapes are settled: + +```bash +# every retired key name the installed spec knows, as a search list +grep -rho '\[REMOVED\] `[^`]*`' node_modules/@objectstack/spec/json-schema/ \ + | sed 's/.*`\(.*\)`.*/\1/' | sort -u > .upgrade/retired-names.txt +``` + +Then sweep the project's `*.md` (READMEs, ADRs), comments, seed fixtures, and +its AI conventions file. The conventions file matters most: it is what the next agent loads before +it writes anything, so a retired shape left there re-enters the codebase on the +next feature, long after the upgrade closed. + +## 3 · Acceptance + +Four artifacts. Three are machine-checked; the fourth is the one a human reads. + +### 3.1 Typed + +A retired key is not merely absent from the schema — it is declared as a +tombstone whose input type is `never`. Assigning anything to it fails to +compile, at the authoring site, before anything runs. A green `tsc --noEmit` is +therefore positive evidence that no retired key survives in typed sources. + +### 3.2 Parse-gated + +The same tombstone rejects at parse time, and the rejection carries the +prescription rather than a generic "unrecognized key". This is the channel that +catches metadata `tsc` cannot see: JSON files, database rows, anything built at +runtime. You do not have to do anything to enable it — but you **do** have to +prove it is live for this project, because a schema that silently strips is +indistinguishable from one that accepts. See +[the reverse check](#reverse-check). + +### 3.3 Validate + +```bash +os validate # green is the criterion +os validate --strict # warnings become errors — agree with the owner whether this is the bar +``` + +`os validate` runs two passes: the protocol schema (where tombstones reject) and +the author-time rule set. Read the two separately — a rule finding about a +missing sharing model or an options-less choice field is a project-quality +issue the control already shows. + +Some conversions are **migration-chain-only**: the loader deliberately does not +apply them and no tombstone rejects the old shape, because the change is a +default flip rather than a rename — auto-applying it would stamp a constraint +onto sources that deliberately omit it. This build ships none (every conversion +it carries is tombstoned, so the parse refuses the old shape too), but a later +one can, and the chain, not the parse, is what knows. + +Why `--from ` proves nothing: `--to` defaults to the highest major +this build carries a step for, so the range is empty — no step runs, `applied` +is `[]` whatever the metadata holds, and the JSON says so with +`replayedNothing` (its `widestRange` is `null` there: no wider range exists +from that `--from`) — or it holds only the next major's step. `todos` is +semantic residue, Layer 2's business, not a failure. + ### 3.4 The report — the human half The upgrade is not finished by a passing command; it is finished by a document a @@ -83,6 +341,44 @@ _N sites, M conversions. Ported into sources from `os migrate meta --out`._ - — no occurrences. ``` + + +### 3.5 Prove the gate is real, do not assume it + +Make the parse gate fire once before you report it as evidence: take a value the +chain *would* have converted, put it back after migrating, and parse it. + +```bash +# a stack that still carries a retired key, fed straight to the schema +os validate .upgrade/residue-probe.config.mjs +``` + +The probe is a plain data literal because `os validate` loads the config +without authored-source mode, and every `define*` helper is a `Schema.parse()`: +a probe written the way a real config is written throws *inside the load*. + +Predict the outcome **before** you run it, then record which one you actually +got — "it passed" is a different fact in every row: + +| Outcome | What it means | Your acceptance evidence | +|:--|:--|:--| +| Rejected, error carries the fix-it text | A tombstoned key. Not "unrecognized key", not a deprecation label — the prescription *is* the error. | The refusal itself, quoted. | +| Accepted, and the chain rewrites it | A conversion with a live load-path acceptance window. | The chain's diff — not the parse gate. | +| Accepted, and `validate` stays green | A migration-chain-only conversion ([3.3](#33-validate)). | Only the acceptance replay sees this class. | + +### 3.6 Stored rows: assert them, do not believe them + +The four artifacts above cover the authored sources. For a **deployment**, the +stored pass is itself the assertion — run it read-only and branch on the exit +code: + +```bash +os migrate meta --stored --json # 0 = every row canonical, 1 = work left +``` + +That is what makes "this deployment is on protocol N" a CI check, valid only on +the release you are leaving. Nothing gates on it having run. + ## The v17-canonical shapes, compiled What the protocol-16 shapes in this skill's examples look like after the @@ -117,3 +413,18 @@ export const SupportBot = defineAgent({ skills: ['crm_case_management'], }); ``` + +## Failure modes + +| Symptom | What it actually is | Fix | +|:--|:--|:--| +| The acceptance replay still applies changes | The port is incomplete, or a source builds metadata at runtime from a shape the chain never saw. | Diff against `--out`; grep for the `conversionId`'s surface in code that constructs metadata dynamically. | +| `validate` green, but a feature silently stopped working | An R2 residue item: code reading a renamed key now reads `undefined`. | Exercise the path for real. A green parse says nothing about a `??` chain in the project's own code. | +| A retired key round-trips without error | The schema carrying it is not strict and the key is being stripped, or the key still has a live load-path window. | Determine which — the two need different acceptance evidence. See [the reverse check](#reverse-check). | +| `--apply` refused / stored-only flag rejected | `--apply`, `--yes`, `--force`, `--type`, `--database-url` mean something only with `--stored`. | Add `--stored`, or drop the flag; the authored-source chain writes only `--out` and, with `--write`, the sources. | +| `MigrationFloorError` | `--from` is older than the chain's support floor. | Upgrade to the floor by an older route first; the floor is a release-policy boundary, not an oversight. | + +Scripting the run instead of reading it? Every `--json` failure above carries a +stable `error` code to branch on — `stored_only_flag`, `missing_from_major`, +`unsupported_from_major`, `confirmation_required`, `database_busy` — and the +prose row is the same fact for a human. diff --git a/.claude/skills/objectui/SKILL.md b/.claude/skills/objectui/SKILL.md index 140e09e..9abeba6 100644 --- a/.claude/skills/objectui/SKILL.md +++ b/.claude/skills/objectui/SKILL.md @@ -5,7 +5,7 @@ license: Apache-2.0 compatibility: Requires @objectstack/spec 19.x; each @object-ui/* package declares its exact @objectstack/spec range in its own manifest. metadata: author: objectstack-ai - version: "19.0.0-next.2" + version: "19.0.0-next.3" domain: ui tags: sdui, schema-renderer, json-ui, react, shadcn, tailwind, plugin, expression user-invocable: false diff --git a/Dockerfile b/Dockerfile index 6fb8e77..5d804d4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -31,7 +31,7 @@ RUN npx os build # → dist/objectstack.json # Pinned at scaffold time to the @objectstack/cli version this project # resolved, so the runtime runs the same CLI that built your artifact. # Move both together when you upgrade — see docker/README.md tag table. -FROM ghcr.io/objectstack-ai/objectstack:19.0.0-next.2 +FROM ghcr.io/objectstack-ai/objectstack:19.0.0-next.3 COPY --from=build --chown=node:node /app/dist/objectstack.json /srv/app/objectstack.json # OS_DATABASE_URL, OS_AUTH_SECRET, and OS_SECRET_KEY are injected at runtime — diff --git a/deploy/objectos-ee/README.md b/deploy/objectos-ee/README.md index b67efbb..fb27d9a 100644 --- a/deploy/objectos-ee/README.md +++ b/deploy/objectos-ee/README.md @@ -9,7 +9,7 @@ pnpm install pnpm build # 产出 dist/objectstack.json ``` -企业版镜像的版本要与 `package.json` 里 `@objectstack/*` 的版本一致(当前 19.0.0-next.2)。 +企业版镜像的版本要与 `package.json` 里 `@objectstack/*` 的版本一致(当前 19.0.0-next.3)。 ## 运行 @@ -23,7 +23,7 @@ pnpm build # 产出 dist/objectstack.json -v "$PWD/dist:/srv/brightrule/dist:ro" \ -e OS_COMPOSED_ARTIFACT_URL=file:///srv/brightrule/dist/objectstack.json \ -e OS_CLOUD_URL=off \ - ghcr.io/objectstack-ai/objectos-ee:19.0.0-next.2 + ghcr.io/objectstack-ai/objectos-ee:19.0.0-next.3 ``` 离线交付时用 `docker save` 打包企业版镜像,`dist/` 单独拷过去。明规更新时只需替换 `dist/` 并重启容器。 diff --git a/docs/policy-admin.md b/docs/policy-admin.md index 66090da..2eb0945 100644 --- a/docs/policy-admin.md +++ b/docs/policy-admin.md @@ -73,7 +73,7 @@ AI 诊断一份制度时提出的一条建议,主从挂在制度下(`sharing 诊断要做的是:读制度正文(和附件、相关制度)、调用模型按维度找问题、按批次写入 AI 建议,超长制度还要分段。平台的沙箱脚本(动作体、钩子体)**不能调用 AI**,所以这件事做不成本卡的按钮体。可选的路: 1. 代码插件里的**注册函数**:按钮调用注册函数,函数里调用模型、写建议。只能在**自建企业版**部署里用(云环境不加载应用代码插件)。 -2. 等平台的「**问 AI**」动作(`ask_ai`):在动作里直接把制度交给平台的 AI,按约定的输出写入建议。 +2. ~~等平台的「**问 AI**」动作(`ask_ai`)~~:这个动作类型已在 @objectstack 19.0.0-next.3 退役(ADR-0160 D7),只剩页头的「问 AI」入口,这条路不再有。 选哪条、诊断维度(第 2 节类别)、提示词和超长制度的处理,在新卡里定。按钮、权限和存放建议的子表本卡已就位,接上即可。 diff --git a/objectstack.config.ts b/objectstack.config.ts index 24d3fa6..3df5a49 100644 --- a/objectstack.config.ts +++ b/objectstack.config.ts @@ -60,7 +60,7 @@ export default defineStack({ 'automation', 'triggers', // 'record-context' serves get_record_context, which reads the context pack - // behind 「问这份制度」 (src/ai-contexts, ADR-0160). + // behind the record page's 「问 AI」 (src/ai-contexts, ADR-0160). 'record-context', ], diff --git a/package.json b/package.json index a700adf..2d607db 100644 --- a/package.json +++ b/package.json @@ -21,19 +21,19 @@ "eval:drive": "tsx scripts/eval/drive.ts" }, "dependencies": { - "@objectstack/connector-mcp": "19.0.0-next.2", - "@objectstack/connector-openapi": "19.0.0-next.2", - "@objectstack/connector-rest": "19.0.0-next.2", - "@objectstack/core": "19.0.0-next.2", - "@objectstack/plugin-hono-server": "19.0.0-next.2", - "@objectstack/runtime": "19.0.0-next.2", - "@objectstack/spec": "19.0.0-next.2" + "@objectstack/connector-mcp": "19.0.0-next.3", + "@objectstack/connector-openapi": "19.0.0-next.3", + "@objectstack/connector-rest": "19.0.0-next.3", + "@objectstack/core": "19.0.0-next.3", + "@objectstack/plugin-hono-server": "19.0.0-next.3", + "@objectstack/runtime": "19.0.0-next.3", + "@objectstack/spec": "19.0.0-next.3" }, "devDependencies": { - "@objectstack/cli": "19.0.0-next.2", - "@objectstack/mcp": "19.0.0-next.2", - "@objectstack/skills": "19.0.0-next.2", - "@objectstack/verify": "19.0.0-next.2", + "@objectstack/cli": "19.0.0-next.3", + "@objectstack/mcp": "19.0.0-next.3", + "@objectstack/skills": "19.0.0-next.3", + "@objectstack/verify": "19.0.0-next.3", "@types/node": "^22.20.5", "tsx": "4.23.15", "typescript": "^5.3.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 91ddac4..47cd6a6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9,39 +9,39 @@ importers: .: dependencies: '@objectstack/connector-mcp': - specifier: 19.0.0-next.2 - version: 19.0.0-next.2(zod@4.6.7) + specifier: 19.0.0-next.3 + version: 19.0.0-next.3(zod@4.6.7) '@objectstack/connector-openapi': - specifier: 19.0.0-next.2 - version: 19.0.0-next.2 + specifier: 19.0.0-next.3 + version: 19.0.0-next.3 '@objectstack/connector-rest': - specifier: 19.0.0-next.2 - version: 19.0.0-next.2 + specifier: 19.0.0-next.3 + version: 19.0.0-next.3 '@objectstack/core': - specifier: 19.0.0-next.2 - version: 19.0.0-next.2 + specifier: 19.0.0-next.3 + version: 19.0.0-next.3 '@objectstack/plugin-hono-server': - specifier: 19.0.0-next.2 - version: 19.0.0-next.2 + specifier: 19.0.0-next.3 + version: 19.0.0-next.3 '@objectstack/runtime': - specifier: 19.0.0-next.2 - version: 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + specifier: 19.0.0-next.3 + version: 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) '@objectstack/spec': - specifier: 19.0.0-next.2 - version: 19.0.0-next.2 + specifier: 19.0.0-next.3 + version: 19.0.0-next.3 devDependencies: '@objectstack/cli': - specifier: 19.0.0-next.2 - version: 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + specifier: 19.0.0-next.3 + version: 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) '@objectstack/mcp': - specifier: 19.0.0-next.2 - version: 19.0.0-next.2 + specifier: 19.0.0-next.3 + version: 19.0.0-next.3 '@objectstack/skills': - specifier: 19.0.0-next.2 - version: 19.0.0-next.2 + specifier: 19.0.0-next.3 + version: 19.0.0-next.3 '@objectstack/verify': - specifier: 19.0.0-next.2 - version: 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(@objectstack/driver-mongodb@19.0.0-next.2)(@objectstack/driver-sqlite-wasm@19.0.0-next.2(pg@8.23.1))(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + specifier: 19.0.0-next.3 + version: 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(@objectstack/driver-mongodb@19.0.0-next.3)(@objectstack/driver-sqlite-wasm@19.0.0-next.3(pg@8.23.1))(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) '@types/node': specifier: ^22.20.5 version: 22.20.5 @@ -469,62 +469,62 @@ packages: '@nodable/entities@3.1.0': resolution: {integrity: sha512-LsS/DjHr+uDM647Gru/cA8+J3a3HfhttwCKLyuoyN7yXTFCxKBtSgMQBvrW9yNPa2/zDRUNuGPaH5QUFoa4arQ==} - '@objectstack/account@19.0.0-next.2': - resolution: {integrity: sha512-4LK188coL//w1HoQN7TI6qykL6wHId5LKK/sJHvmkhurmiRBH0GMGgGbHuxhtq9lv/Ex810aH6F+fNAKY8dbhQ==} + '@objectstack/account@19.0.0-next.3': + resolution: {integrity: sha512-cfYLwNIzNEnH/wKIvwu77tjZxv9JU0ZTe1Vl1r08d08/sA3q0r+NVLriitxZWjMC+Y6qAx15cEpqPe1ggcEo4g==} engines: {node: '>=22.0.0'} - '@objectstack/cli@19.0.0-next.2': - resolution: {integrity: sha512-mn/+/xW7/dxYy2gspm8qYZfnnmtiz9YpcN3JueoKetqEPHW7ptPQHlDLmrgD5N+qhAoS6Ql4gf9tZplefII+cA==} + '@objectstack/cli@19.0.0-next.3': + resolution: {integrity: sha512-h+Sj+FUq+/Pnz28O1Tu2F43GwvwN1lrOw1j18lcSll350oGQkmFhnBotf2hI09GpsWA9/U+DbU7Tet7xAhLORg==} engines: {node: '>=22.0.0'} hasBin: true peerDependencies: - '@objectstack/driver-turso': ^19.0.0-next.2 + '@objectstack/driver-turso': ^19.0.0-next.3 peerDependenciesMeta: '@objectstack/driver-turso': optional: true - '@objectstack/client@19.0.0-next.2': - resolution: {integrity: sha512-RPK3IG4l79huyPP2PtqDSsS4y7A5+mL3MPsMVBAsCfD0d1Ac/MJwm+aDahAcRAql/vK6hprMWbjrie+JKY5stA==} + '@objectstack/client@19.0.0-next.3': + resolution: {integrity: sha512-8fOZXhMAKvZPaUkIAIML0NR/PQsItsA38zQt9ltUtCL62+YbQiKVZ7n01Pik5nwIVje+VFVIsQHkdNwuZY6r1w==} engines: {node: '>=22.0.0'} - '@objectstack/cloud-connection@19.0.0-next.2': - resolution: {integrity: sha512-3TMqWe3iby/5Sz9+9oLfghyKLobmp4QLSFbb8k+/6jWeqiTyZBwVUupy1HJTa+a2NhchOeJaIPc3jX1jAGgS8A==} + '@objectstack/cloud-connection@19.0.0-next.3': + resolution: {integrity: sha512-CSD4px5ErBgkR1403kN96HjlaBIdO+U0t39aGHifpu/qP5rsNARfmBHVaTXTXEtLxwkLu5A395FX9hwZCKqexA==} engines: {node: '>=22.0.0'} - '@objectstack/connector-imap@19.0.0-next.2': - resolution: {integrity: sha512-3Zx49a9phNGdvk9PYvW+sLedGAzSmrJ7rA1Ox4BB7acytzbwdH+NMGQCgIxiQX9i2w6C34H8X+ME5gKS/hQWww==} + '@objectstack/connector-imap@19.0.0-next.3': + resolution: {integrity: sha512-1xMPJDIfpn0SEXmxU9zyCAxBDQoFQ3TdnRQo/SBVtJtnXdFDGpzew2VnTk8NsPWu9zpFF9PWeJjOVKhLHe/rTA==} engines: {node: '>=22.0.0'} - '@objectstack/connector-mcp@19.0.0-next.2': - resolution: {integrity: sha512-NbTmOeUbqNu9rrGECY2zli/dDzDsKbOyZPZyzqtXisuKHfA8fLcUZiu98Uo42ciWyntK0zNoKDvJRCugqjpq2w==} + '@objectstack/connector-mcp@19.0.0-next.3': + resolution: {integrity: sha512-Ybs9twU+gRWvIvalKAqYIA5pCEiz7qKguHiaC514rQ2FLLChu9cPmEJInN0JxmptWCmcGUC0U+9hP0SGyVWwSg==} engines: {node: '>=22.0.0'} - '@objectstack/connector-openapi@19.0.0-next.2': - resolution: {integrity: sha512-LHbte8lk3SmPJpmkk3O1nbi0h1Pjh00q98iB/GBmheyjBwQVeqFzHaT7xO25by+x4AiiXwRWTKxSIJz4XT5DwQ==} + '@objectstack/connector-openapi@19.0.0-next.3': + resolution: {integrity: sha512-nC3ZUYiguWn1IzO38U1SreQWXVSl/BpU8ImVesxg+EyQQ8cWDD5nsjgkw0wZblhfuq27N5Xrs5KyEJUtgJVdGQ==} engines: {node: '>=22.0.0'} - '@objectstack/connector-rest@19.0.0-next.2': - resolution: {integrity: sha512-JAQV9vJe+zQHFgJ2SbVf+jGYn4p/Xls+r1ysyUkM1MB1H7F24+nITBQIBnd1eNHLbjbppIwTQXv71eTa+O02BA==} + '@objectstack/connector-rest@19.0.0-next.3': + resolution: {integrity: sha512-TolUj4Ss6LsGQ2nvVN8Cafk8CESu/o00Bcpf82pe341VNhBx3rD2pPUBQsLpPGnmoQS8ISQs+WnTS7BxW7Hx7g==} engines: {node: '>=22.0.0'} - '@objectstack/console@19.0.0-next.2': - resolution: {integrity: sha512-2horHrRj3EA8VQULAeBLgSjIXBElHi5vgmz7cU9i5eoWjB8YkE1xPotl53aXwWiOoPiQ1IFMTSRSFcw1LVzEOQ==} + '@objectstack/console@19.0.0-next.3': + resolution: {integrity: sha512-E6IBhj7uaCn5PyUd4lV5lwzMTeB8/Vn6X9xKo4ynmgtCw3mSu8IB1hVXmmaqjHQqQIysLFXGrCeYWfjYMfiTtw==} engines: {node: '>=22.0.0'} - '@objectstack/core@19.0.0-next.2': - resolution: {integrity: sha512-o7fRj2NPSyJHiN5uPKT4m0MeI/Fs55l2Se3wlhaxRHIlw2wN63I9A6milaJMwH3u5nHknrJIfGHQIllC3y8PSQ==} + '@objectstack/core@19.0.0-next.3': + resolution: {integrity: sha512-VsiO7L+o4o/mtFsN8+tOUcm5hcGswsiAN0FMuDRoZcDFiqkn6g2yKbBleKTqhUi2LBrCq8ggHFi2/+DwHkHKZg==} engines: {node: '>=22.0.0'} - '@objectstack/driver-memory@19.0.0-next.2': - resolution: {integrity: sha512-JzBtwlOI1nbspB1hDS0liYiNC+nxau0sme+DshJAJAPH+uHtpTpE9Tp3A38pA0UzbsvwEpoPPxR1SqFp5uC7TQ==} + '@objectstack/driver-memory@19.0.0-next.3': + resolution: {integrity: sha512-tViPYsReTFcnGbRMCMB/3hHGinLWMA5oTvA50LG3uHgr92PLdO1ZPRDDcvN0AET14Z3c6ECmxnEihA6UAry83Q==} engines: {node: '>=22.0.0'} - '@objectstack/driver-mongodb@19.0.0-next.2': - resolution: {integrity: sha512-qWMHIwgM1WBU43h6JQ4BCXUf9r4GFHS4ZP6T9aAoHHjj27fE/5xXFnWuOIAILu3ZhwClie6AnaxKatTZA5RtuA==} + '@objectstack/driver-mongodb@19.0.0-next.3': + resolution: {integrity: sha512-50UnQctKG+QSOQ0RnWe8d80KuKpgRmNsd4lgCaie5/6ATD5G6s9cZ+9AVysYDngeZ0aPK/PcfFOEfyAQ+KFmbw==} engines: {node: '>=22.0.0'} - '@objectstack/driver-sql@19.0.0-next.2': - resolution: {integrity: sha512-TR5NdcPbuurzaONY9GwqaU3ArlSmIgBwxbcxExHoSSv//4IFVsjLH5euT5lAub375PS/+/ahLhTkNEE6SBrUoQ==} + '@objectstack/driver-sql@19.0.0-next.3': + resolution: {integrity: sha512-0UG7OOObYQL8P8HH6UMPB2DEutG9tGJoRHYgmmPKG8sHAxrfvh4sQx+5sotENSqvhEHV/4ysDX+OgdZM5rwGHw==} engines: {node: '>=22.0.0'} peerDependencies: mysql2: ^3.0.0 @@ -541,138 +541,138 @@ packages: tedious: optional: true - '@objectstack/driver-sqlite-wasm@19.0.0-next.2': - resolution: {integrity: sha512-0Fm9ezgbyeaS8NCPckTh5RKXE8bJiQ0IrnW/Rn4bT/WHtv+erDPNlEGIKNFoxyMs6C+ABXCk1sI2x+ScWUj+tw==} + '@objectstack/driver-sqlite-wasm@19.0.0-next.3': + resolution: {integrity: sha512-e6Nlpd7XMxlwQPSGb9qsMVemK1kF/MfVHNkSjjlWM/B9AQB2phEIkcR0V8ESj38mflhqolQ5mhmNzRaOV+007w==} engines: {node: '>=22.0.0'} - '@objectstack/embedder-openai@19.0.0-next.2': - resolution: {integrity: sha512-Z1k0KM7B/bYXB59BaXwyssOpVXp4Ssnf4Jc5cw+xR8MMUmqiEbskshnzwlcI+x1iDKY7/R5qZf3pbu/8TWmqVA==} + '@objectstack/embedder-openai@19.0.0-next.3': + resolution: {integrity: sha512-+0eoBwrhJxPu5LInZK5bvAxRT15e36BLc7VfOntdq5hQaKgu5MXP9Yz/+h8q+4ys1Rs/o8Q4mLXnxCpuO00Bfg==} engines: {node: '>=22.0.0'} - '@objectstack/formula@19.0.0-next.2': - resolution: {integrity: sha512-Pm75kwNdkiJiX+XZYBeN0W8lpDbQjIR8vPUKnjte0zp9kkn7jWCUDnw4m4CrXR4q50556MuXFLVUyi1vbIH74w==} + '@objectstack/formula@19.0.0-next.3': + resolution: {integrity: sha512-0KJpekM8YT46tqR0sdFFs7FvccYVpim9AoF3uxn8Ou5IKEPcjRGKzTHROyK/BdYMIcHBgCSOSwgfL8FITb23yA==} engines: {node: '>=22.0.0'} - '@objectstack/knowledge-pgvector@19.0.0-next.2': - resolution: {integrity: sha512-KinYOq7AmFy9I4GeZ5HDJcfMLtcS36Hw+XiUkEaS0WsntjBsD7AJlwGayfnh+OxTtpu/Om5swpB3/XIUD8Yr/g==} + '@objectstack/knowledge-pgvector@19.0.0-next.3': + resolution: {integrity: sha512-9UBI/gLVpD4/2lFPP6QSfANHTC7DVlFgtxQJ+49IypbgpM/0pn6PjResCItuB2ERXkjgSgxs195zl1srwpujkw==} engines: {node: '>=22.0.0'} - '@objectstack/knowledge-turso@19.0.0-next.2': - resolution: {integrity: sha512-ZozRm2qL1ixMZDFoQq8PCEoZxq6G5y8IC93Fbtr54mcQU2zlKiogbPl0vlkMb23/8oB5sBDJdGnxFg+7NBFh+A==} + '@objectstack/knowledge-turso@19.0.0-next.3': + resolution: {integrity: sha512-OB/3TvDpXg+2Swn6K5e9ZqFAC43MQfPnX8gDpd66e46s7kqa0yK2WADDoF5Ll9BVokqRzEB2ZqsPGP/myrmitw==} engines: {node: '>=22.0.0'} - '@objectstack/lint@19.0.0-next.2': - resolution: {integrity: sha512-lNkGRH7yk8p+uUAPldXGjreaRueyfHJw1P/4PY6Au4HKe4/S3OXnzYJObbnRP6TKvXddDjDTwuJPe0w94xmBeQ==} + '@objectstack/lint@19.0.0-next.3': + resolution: {integrity: sha512-Di4hl9Clx8QoIGqPtYTnK+11sLMbPq1I1OKOeMm+Zl2dpSt93dgeBpnM/Mr650kndP7GhCzAlBKIOMPQmgYSfQ==} engines: {node: '>=22.0.0'} - '@objectstack/mcp@19.0.0-next.2': - resolution: {integrity: sha512-0BQxy6bL2rybPnubeERwD077wqsGuUSUTTI2QxxL694eMY+OSDzrKaZGOkeTCvJ8znqvEj2rgVJyAGL2ZHuLrw==} + '@objectstack/mcp@19.0.0-next.3': + resolution: {integrity: sha512-5yIfprhoX9e+FOre+kz2KHQa5MtCV9Lq+EsdTGVhdQJ90vFxtQRbbDTofheHXEKq5Q70RTA+Fe4ns3HH091fNA==} engines: {node: '>=22.0.0'} - '@objectstack/metadata-core@19.0.0-next.2': - resolution: {integrity: sha512-vYZl0ODksSuhq3DQ0ukkv+JRt0nUFX2oiRZ1VACZ3r6uvCPMDMLcqHAoY3Zn2BCsqJvFOg8GIhKEjK00th1hpQ==} + '@objectstack/metadata-core@19.0.0-next.3': + resolution: {integrity: sha512-JSaip/c5Y66RFV/IKkixtaEzik+/m+iS4rmivMgBnqLebaUd/JWfYAMGjO7g88XKXhP3+Rt3yeEDpZ5EMpgcVw==} engines: {node: '>=22.0.0'} - '@objectstack/metadata-fs@19.0.0-next.2': - resolution: {integrity: sha512-xSHsZBGUlZqEns+WEHhuCQUDxJwW00Tedmi8Uew2lvqsqEzqboiioagcpfBBwVJ+6qOO5MbIJsNKqSbKNSmE1A==} + '@objectstack/metadata-fs@19.0.0-next.3': + resolution: {integrity: sha512-o78JFfAB3xCIHyAuiUD1jpmlWl0MthTrZe8Qnrc0lOwWzFwmJYuG4asU6ARI8kPGTahFwryANe0eBQ+SSALEoA==} engines: {node: '>=22.0.0'} - '@objectstack/metadata-protocol@19.0.0-next.2': - resolution: {integrity: sha512-A2l+TvyQUtyWC6BzNgSL2yFCtncA35ENlxDwlZ1pn2zbfJky7D3vsXQCI2X516R/zkd7iCzSDdk1fJSQ7nrH0g==} + '@objectstack/metadata-protocol@19.0.0-next.3': + resolution: {integrity: sha512-TRYkkCrrarzjRROsEPkiVVzeuBe7+pwmf80vmbvoZScIxa8fQ9oN+EJFQYuJFhfWoqfGbfx5m70el6Cf1NBUIg==} engines: {node: '>=22.0.0'} - '@objectstack/metadata@19.0.0-next.2': - resolution: {integrity: sha512-9VC6yi+RK4+ICIBB4Vxj/hN8qkJzbcoELt2LdfBOwVlbPiEKvqlI5j27pc1q1nufWJwKcELRsHYX6HZiRy+DVg==} + '@objectstack/metadata@19.0.0-next.3': + resolution: {integrity: sha512-/zepChWPoXx1do9vVfzxqS++ROBH5vlsjSAXt+98tPmN3pUnhHSMAGgrm0TLFmACCx2UHrxyW133WkRxJzhLDw==} engines: {node: '>=22.0.0'} - '@objectstack/objectql@19.0.0-next.2': - resolution: {integrity: sha512-Z7sbttLRRa3uIVXhvEc45KnDClty91LiH6VXHWgN6eoNjdojSgNLU0XMsbNo+WpoOzTcSrBk+MJmxn72ouj6Eg==} + '@objectstack/objectql@19.0.0-next.3': + resolution: {integrity: sha512-ESJugBUcm8wUQnzEsoxGppA9y2lUmtbji6lRpqt5rBUoWd2sGIqjPGeJcyIhLEZHEvnOaWCk6qcnLXh7cdvCJQ==} engines: {node: '>=22.0.0'} - '@objectstack/observability@19.0.0-next.2': - resolution: {integrity: sha512-z8ERuVVQMWR6iH5kztqJdDEpsXzhI6MujCjhU/pN6irBj+avr5TuVpVRITcmR02Yh8r9ztGRI+8S019dY76cAQ==} + '@objectstack/observability@19.0.0-next.3': + resolution: {integrity: sha512-USPNqyScEK3fuA70tYBP0PTqK+7J/Itsv79qA1poKlYErU5nrAxOjC8B2SuKkWTTw+NMbeZWp6tPCTjNtD6eGA==} engines: {node: '>=22.0.0'} - '@objectstack/platform-objects@19.0.0-next.2': - resolution: {integrity: sha512-wyTeLbmNrXCoNNjW6lwEqPGy/Ul39tyUP//mDbKeNMw1MIFWz5KST+SNqShoMvSyhh1us7s4Qw6OGzoCrt/+Mw==} + '@objectstack/platform-objects@19.0.0-next.3': + resolution: {integrity: sha512-mos/i0W5yaTTsqVld0bUbwlCYAWYo882GR3VfFJXtjoTsMPhxqQToMCDtQLMAVzbHCtbsRBQmbnokncLgWrWeA==} engines: {node: '>=22.0.0'} - '@objectstack/plugin-approvals@19.0.0-next.2': - resolution: {integrity: sha512-XPQveBeNi5fEYyoB+PPkrsECq2QInCv0KN4Wq6WhGMgoOfYy8BlemB6kExl324/al4WA4i8dYiAoyxBhz/CnpQ==} + '@objectstack/plugin-approvals@19.0.0-next.3': + resolution: {integrity: sha512-hVNcjr8nsFeY7oiD7AKn9AkCQGCa2VrEPbSZxIg0yHdfZZLTppzEqZf3M5rNiVpUfSAgNWUYZ+9WsvVXNgVtQg==} engines: {node: '>=22.0.0'} - '@objectstack/plugin-audit@19.0.0-next.2': - resolution: {integrity: sha512-5vdUubLqMia6IfoZgdlQm1fasA8H9RJwzmJGLxFhJhhx5nNlbKKt+bAE12AU5GEnG7/pHnfvzvj8kqDzKQtwNw==} + '@objectstack/plugin-audit@19.0.0-next.3': + resolution: {integrity: sha512-XAUjt+YwzVBc/NK6yK1oUsPiRvfUOkYBQexJ3wRG+ev8BRDHxXqE90/cgpL9bhp5rGMxz7XG+Nx5WfrEcyWLvA==} engines: {node: '>=22.0.0'} - '@objectstack/plugin-auth@19.0.0-next.2': - resolution: {integrity: sha512-WsA9l5+h0gL1uNnUpsRPTTIVyYF4j2jIhnz6mUX0lZPOu26INHpkoX2kdOcsrWjjqVV1PmEz+Eom6JhELdP8Uw==} + '@objectstack/plugin-auth@19.0.0-next.3': + resolution: {integrity: sha512-fsTlIMjij4fyY3plFMBTrMSSD4Ddt9nHZGhwivrW46vgYeMEeXbYsjiU6wZSIvtWcSpVQm431jegBWJV9Cktrw==} engines: {node: '>=22.0.0'} - '@objectstack/plugin-email@19.0.0-next.2': - resolution: {integrity: sha512-S0ZQoS326ZjlllJplzcK9BJiwlS3znACSwZjEORr/kyEYoAGFlXvRK8uEw/7U9gOBLyF65UYZagadZEPXB7n6w==} + '@objectstack/plugin-email@19.0.0-next.3': + resolution: {integrity: sha512-11g8u9Z5eoldtJ78CxUk/J70cdD2bZ+8joGkkrxpICoM+6+YCxJyuJh+MSM4GHIa7/cjA39N5OrdJVfVbffu5A==} engines: {node: '>=22.0.0'} - '@objectstack/plugin-hono-server@19.0.0-next.2': - resolution: {integrity: sha512-ypRjikXN25QB2GHumoWnPQdrS+HuHib8cOWKD11EgKC6Kb63K8TSHdZ3rqlVzoDqmAz7K/B9ihDOULazTTyBFA==} + '@objectstack/plugin-hono-server@19.0.0-next.3': + resolution: {integrity: sha512-EUJHlazyqgNOYvppnoOX33w8aXWl3LuX00ekps9h8A51xHjsY8mBkQ1xlhMKZyVuEGxK81vDz1fLfIHX+KiwMw==} engines: {node: '>=22.0.0'} - '@objectstack/plugin-pinyin-search@19.0.0-next.2': - resolution: {integrity: sha512-yYrchxtGv8jr1GMyR6OmbQhupOLA+03hcHXxXbubR+NXxmV9b6y0Cof/aUDkMYESkfUwcE6D5IfjUCDpiiojJg==} + '@objectstack/plugin-pinyin-search@19.0.0-next.3': + resolution: {integrity: sha512-ks9wTHNn6aDWw3fYKdOGgT0otmU/v1m4EURMVm3qGKRu3LyGdQopgMqRK6ZoHQ5EZIu9mtVl7dkktfaN4pGPEA==} engines: {node: '>=22.0.0'} - '@objectstack/plugin-security@19.0.0-next.2': - resolution: {integrity: sha512-/t5wJmcvQTnGvBPFXxtaE0Ip+FdhilxC7xW6GppHmKdl64HaKDZyGj9HEll2Xc0tkRgSPdBExrgl3KW8kiAshA==} + '@objectstack/plugin-security@19.0.0-next.3': + resolution: {integrity: sha512-faTyjlzmgWUemi+b74kQG9tjoMlTAEP6EMiWCgx3DHwpuiMWVmmwqA7EVx3UusOHHg7iK1Z8bx2dBY6wkWbQ2Q==} engines: {node: '>=22.0.0'} - '@objectstack/plugin-sharing@19.0.0-next.2': - resolution: {integrity: sha512-oni36pdvg5FflpzWrmtxiCQrmrAmGEtAHdZdZaIJo40mwcoDRy9SN5w3M885OEIUKdq69LgwYnU8/vgA0QVs2w==} + '@objectstack/plugin-sharing@19.0.0-next.3': + resolution: {integrity: sha512-/s1mWMUWJrnTVtweg/+MQajy8OM5Mv413scdsKiLJqX5gGgME0aaIyAzTaMe0p5uJmufABtfy3Ht84WKTqcslw==} engines: {node: '>=22.0.0'} - '@objectstack/plugin-webhooks@19.0.0-next.2': - resolution: {integrity: sha512-v6zaU2OuC8c3HiXiIjVNX6W4ckI+BcWQQhjXLvUwVNoaNAKMGloxy5c13NGQEVOQ5yvG/OkLr1hSaKHXNOsfGQ==} + '@objectstack/plugin-webhooks@19.0.0-next.3': + resolution: {integrity: sha512-xY/qVqeaWsZmBa05Xb1mLgrD1BXGxpOpJm4+UbHa6HconnO3Siqj72z9HWxl2uFC6ThxgS0idq58BJwFWg0WPw==} engines: {node: '>=22.0.0'} - '@objectstack/rest@19.0.0-next.2': - resolution: {integrity: sha512-LK5bVllpWLbq1CxuSdKnwQEKhX9tMgHglUv8vwWNZlcASC1h6yl7Pxdm7ARbKKZcqq3VK9fewQjJVRCmUDQUnA==} + '@objectstack/rest@19.0.0-next.3': + resolution: {integrity: sha512-1WScFefZG52ZCUBogBuIcqD5uQ2yxv4TPbDvmA2JWa0h/ToYy73qyKs1Z4Kr5gXszEdIcUAsLIvSWNPd+sku4g==} engines: {node: '>=22.0.0'} - '@objectstack/runtime@19.0.0-next.2': - resolution: {integrity: sha512-Q9sgw5qo2fas+QFq8cBSWU930GkwL3FhJPEK11XqQGF2i3fFS/UKhI2gaSahjkUtnKm1Baf6O4utB3EHSn1Z5Q==} + '@objectstack/runtime@19.0.0-next.3': + resolution: {integrity: sha512-EW9tqwml3lnSMbAkLRhQVkDjRr1HAb59yRUepki+tJjMNhooQKJBTSWTh/XWcrFo3B7I8/oB3uEs3QCGJXtbhw==} engines: {node: '>=22.0.0'} peerDependencies: - '@objectstack/driver-turso': ^19.0.0-next.2 + '@objectstack/driver-turso': ^19.0.0-next.3 peerDependenciesMeta: '@objectstack/driver-turso': optional: true - '@objectstack/sdui-parser@19.0.0-next.2': - resolution: {integrity: sha512-70msEs4o4QaQb88GtZcBkDKuDP2HwDVSSl1sZhIymquuydW8krEXz7L4KrY6PapcPRwEgIAJnW+88bTuQr1/CQ==} + '@objectstack/sdui-parser@19.0.0-next.3': + resolution: {integrity: sha512-qof/UqFeGu+4vrQ7mrL/LxZQgTq56UAFXDBTFVnv53QHQHNiDzbSNtwicQ+BUA+VT0Jx0UEc9pQ08lalatWk/g==} engines: {node: '>=22.0.0'} - '@objectstack/service-analytics@19.0.0-next.2': - resolution: {integrity: sha512-EOORbBOrUClSIpC76QwCaG9BHxbtGpHDwKXRdVNPipMoHl01qa6XRDz2UpSbMb0t8oUv7+7C65PUqNwh35VOmA==} + '@objectstack/service-analytics@19.0.0-next.3': + resolution: {integrity: sha512-O8kUJjgjYqNjlYj3Uiips/VhAdQlatFxx+aBinCLUZsPJg3/4AEHQl9ZGkFlmfYwZsyf7gOVg8PNYxWKIFFJWw==} engines: {node: '>=22.0.0'} - '@objectstack/service-automation@19.0.0-next.2': - resolution: {integrity: sha512-38ScyQjnPMlOVKmjO7HEIEQlYx4MCJOqhesvrEVcR76PpBsV8JxtrGin65G/vy1DpG+LL7WZZ0H19UJgCpUP8w==} + '@objectstack/service-automation@19.0.0-next.3': + resolution: {integrity: sha512-H8anG098AYd/60WY6UC3RaSD3mM06V9SqqU6dAMjUVdG9ahhvByjALWVU100LUEvxYqOhjd89jl8HUoY8CHIPQ==} engines: {node: '>=22.0.0'} - '@objectstack/service-cache@19.0.0-next.2': - resolution: {integrity: sha512-27lFt4IuetcnqaKuaXaW0FnKj6CflTwvNAn5ExrqIy6AjBM+D14i9YHO0DnPsqeS7XLYibApgfif/93R3T/46g==} + '@objectstack/service-cache@19.0.0-next.3': + resolution: {integrity: sha512-jeaFOLwUq8WB8VUxLd5cXGlCZ9Jl38Rk3JgywRamE81O2/m3zTjVN1YWsGtCN2/+epjG7v8kTG4SU3SI1izRHg==} engines: {node: '>=22.0.0'} - '@objectstack/service-cluster@19.0.0-next.2': - resolution: {integrity: sha512-RA8JeuhpgIy1401ZSXkJ88BqZwc22oAvEeDycbAaaTXGvGCU/Szc+/ySNTcpPv+s+fv+nH4Re5Qi78MRAwLUyw==} + '@objectstack/service-cluster@19.0.0-next.3': + resolution: {integrity: sha512-2sfJepSZ8zBJmBn+N1Wv33zvz+GKRaroULzpNn0b9JcVGPM6U3kb5rYE418DQ3Ry8oB8g39raHEDipS5Tti7ng==} engines: {node: '>=22.0.0'} - '@objectstack/service-datasource@19.0.0-next.2': - resolution: {integrity: sha512-tMte51q0MBSSNaM+/9kReB9PEmHhP7z7DtmdlQmwHaNb1IrvIrgTkIxkSDPsuMwpEjUA+SSqZ3ve0MihOFSISA==} + '@objectstack/service-datasource@19.0.0-next.3': + resolution: {integrity: sha512-qOmpwsKQkpEvpUumhHfatxzi3+PGUNk/RVnCFVtrzz26ApFz5Rl+p5QTojJIAa34Z9+yWnivYO1jkg9clENfWw==} engines: {node: '>=22.0.0'} peerDependencies: - '@objectstack/driver-mongodb': ^19.0.0-next.2 - '@objectstack/driver-sqlite-wasm': ^19.0.0-next.2 - '@objectstack/driver-turso': ^19.0.0-next.2 + '@objectstack/driver-mongodb': ^19.0.0-next.3 + '@objectstack/driver-sqlite-wasm': ^19.0.0-next.3 + '@objectstack/driver-turso': ^19.0.0-next.3 peerDependenciesMeta: '@objectstack/driver-mongodb': optional: true @@ -681,56 +681,56 @@ packages: '@objectstack/driver-turso': optional: true - '@objectstack/service-i18n@19.0.0-next.2': - resolution: {integrity: sha512-bH/QUriE9y2xO9Uz40VXKEP+RNN361qjup2R4RIPam8dbTSgsN7NgmvGV7CB8wodEiUWAaKBArKFMJr8aV7IzA==} + '@objectstack/service-i18n@19.0.0-next.3': + resolution: {integrity: sha512-8iQ9ljz2FTShJ6Sk4VqbJHeQiAuo6jp8GhikUjY+3GR2HvN8sBXTXwf4+C+mxsPnmI0dvLXoF2DRpyLSXSwBsw==} engines: {node: '>=22.0.0'} - '@objectstack/service-job@19.0.0-next.2': - resolution: {integrity: sha512-GaosMvaiQnL1YaetwJKmQWSq10I1p7zX8fwYRc0Ti0LclFY34KQqDlhNMZBZMaQ40wZL4/KvbcUSKYwSS8WU+A==} + '@objectstack/service-job@19.0.0-next.3': + resolution: {integrity: sha512-hSZbPYpl1OEjs1zPGxxTPtFeG6Homv+C4pO8EVq/vm8z2iJ9Nz3YV8qoxWF8qmkaL3e1OYF9kKSJxfPnAB+jRA==} engines: {node: '>=22.0.0'} - '@objectstack/service-knowledge@19.0.0-next.2': - resolution: {integrity: sha512-NloU0mlI7DF7dFIm1orCviEM3tCbfM7vn+/vJ7fQmj4jex5ISBosLdZtCHM3K3oiOnb9PcCcn3TdXVRFYpea6g==} + '@objectstack/service-knowledge@19.0.0-next.3': + resolution: {integrity: sha512-QcaPxN4UM9wW4Lq6USD2mjJaWOdTfZb7DeHgBFuFL+Sr96pDRmF8o0nJmwb6/yOjqeoCguWQBBOVjoXqd+6jHA==} engines: {node: '>=22.0.0'} - '@objectstack/service-mailbox@19.0.0-next.2': - resolution: {integrity: sha512-fjjjQdyOojujwT/fWNI91nwICa3yTSqeSOaSUeGlxqQMoOgmdh1q3uuQH3OChYcGZxr6nwQr3744MqmPba/eUw==} + '@objectstack/service-mailbox@19.0.0-next.3': + resolution: {integrity: sha512-cAFnJFwJTZs0BX/eCzLipMo6+/y3dKosKZ9TrEU0gu2qXHw84E2hk+ojvVy2v3awtd/0xXEPaurs9TDCJh1fpQ==} engines: {node: '>=22.0.0'} - '@objectstack/service-messaging@19.0.0-next.2': - resolution: {integrity: sha512-6+bhCjMSKzGScn2MUrG7T5tphgq0IRamUxLCzraLagCMomu7Ho85fmyHM63RBEqw9ADwyu6mmI+IH+X/HNfUew==} + '@objectstack/service-messaging@19.0.0-next.3': + resolution: {integrity: sha512-JQ23c21FS1WqDVVv5seF7N1bbQUCCpyfjF8MLYGdjXYlj1SVgkh8FnBNXrjFl33t1jBU5N3ZKlbP4Jtb0EyfTw==} engines: {node: '>=22.0.0'} - '@objectstack/service-package@19.0.0-next.2': - resolution: {integrity: sha512-v7/PB8GcOotHgjjmv9RvZp6i1Af4uDzBaqeWOiIDDWRRn12gcWITF+MK90zJH5nsn3QIpwPwwax9F8ibdK01QQ==} + '@objectstack/service-package@19.0.0-next.3': + resolution: {integrity: sha512-VJTWcW/VCPSdMvDB7BAc+xTCkU1TUtbtJlDyDjZW18hmx6lDLANYKpU8y3ZnMIJWp2FMtSl7TPH2EbjiR+37XA==} engines: {node: '>=22.0.0'} - '@objectstack/service-push@19.0.0-next.2': - resolution: {integrity: sha512-Z0B77t1ZGcastsaevNpciWaF+OVtYqP2Buhn0pLSMWY23YSn8j4YaqCJDBqYDvePCcGGHWyw4EONX9ANCS63xA==} + '@objectstack/service-push@19.0.0-next.3': + resolution: {integrity: sha512-QCuLHFa+M+7BQVcYNrwo/OYDSOX39JXaFGTnifneo4nwRCbhLpFZiyTZlSE2Z8vzcvw4fGQa9t//9qJbpZhI1A==} engines: {node: '>=22.0.0'} - '@objectstack/service-queue@19.0.0-next.2': - resolution: {integrity: sha512-f2BtLxBWm1Xm5ULC0i9MOOeBaaoxlEo3IpyqDqqgn7PdQFtU4Q8sGkFaiMCzo38+4lYPyWuduKHvFguaeYpPtQ==} + '@objectstack/service-queue@19.0.0-next.3': + resolution: {integrity: sha512-LYgnzpLRHP9lqiUEPFfShjLouz7lzlqnu8zl6xnJOb8jOEtlpKbJjE9DNe3JUyLtCkd2AL8kakVV5SrEDSirig==} engines: {node: '>=22.0.0'} - '@objectstack/service-realtime@19.0.0-next.2': - resolution: {integrity: sha512-h4VuAZ6D/GkdHRbk2/FMAT/Ht+gASfkr5CneUODy1g1qK651YPFmlJt/BG8Fv1Xlzc7V/DQ++NeAcMxHtPQ/BA==} + '@objectstack/service-realtime@19.0.0-next.3': + resolution: {integrity: sha512-14rYEylj31TKVdkwMSXC/AqgW9ArBY4qV9UtKiErxbRQzWzJyG1F7WgZDSHdbwlgneL/jSkEtA01e4v+uH0e6g==} engines: {node: '>=22.0.0'} - '@objectstack/service-record-context@19.0.0-next.2': - resolution: {integrity: sha512-06nHFhEEpU2dkpy8P4OHrz57aZnSyYDctSwnZGMYs0zU6AyZT2zBLu1OCVRl0KC8HdRwD/MDTmco004W+ckgIg==} + '@objectstack/service-record-context@19.0.0-next.3': + resolution: {integrity: sha512-zqW5xeQWhb1X7Uc557qDsIIbDa0T/3u+g3LW89Vu3ftqLXVy8ZpTlfXagWFqcjBLgfw/JqxfGvMHmtrPDLixEw==} engines: {node: '>=22.0.0'} - '@objectstack/service-settings@19.0.0-next.2': - resolution: {integrity: sha512-ph+JSvsY36eHCDKMY1SZ7wv4SqlR5nrJekZYqgwSLJTzMxOJ8iWGGrPg+VbCloAC1GRpV5tKBHCgJ1wv0USpiQ==} + '@objectstack/service-settings@19.0.0-next.3': + resolution: {integrity: sha512-Ub0eapOQrA59jy+WWu9/j/e7ydSlnMDEMqLYFRo7cI2e8Sq9vPvz5AdO1QZAQM0IJenA93Y8W+/PBvEx0rUUVA==} engines: {node: '>=22.0.0'} - '@objectstack/service-sms@19.0.0-next.2': - resolution: {integrity: sha512-EOboqZBJMmt7Yawcf/31ZLxug1RU7qfCTsnP/CcDwpsdJABzD7phodADzP+V5mTz6RQvlGdCOZajh62azyMsWg==} + '@objectstack/service-sms@19.0.0-next.3': + resolution: {integrity: sha512-09F3PrevCbct2DoktmUbbyXCMYdnLSWPJSR4Sufo7PiU0jekAL2ftBA3wStEqH4ddZJpxHZasKtI6HGKXL18sQ==} engines: {node: '>=22.0.0'} - '@objectstack/service-storage@19.0.0-next.2': - resolution: {integrity: sha512-vpZKlULcybjlzwfg5W5FoCfSQul1tQdUFHxwbhxQT6i8MSbN2Q2enj6gBudxKV9zYDCpjRV1+GMWZH/aXLDvsA==} + '@objectstack/service-storage@19.0.0-next.3': + resolution: {integrity: sha512-9alZX6WvW7M+f8BP2+/umrAwHiOp02LSAbbtEzp2u4rdtAszfVjKRgaQ8vXyZVtdFH5CaavaAgogstywtv1HmA==} engines: {node: '>=22.0.0'} peerDependencies: '@aws-sdk/client-s3': ^3.0.0 @@ -741,16 +741,16 @@ packages: '@aws-sdk/s3-request-presigner': optional: true - '@objectstack/setup@19.0.0-next.2': - resolution: {integrity: sha512-augIrrFXcYzJc71wgIwYxLqwPQ2eVahK1BwRmvqdTAwmO6m9nkuP4zpSugWsCMJUWyKI9dCvthmbwqPLg4rI2A==} + '@objectstack/setup@19.0.0-next.3': + resolution: {integrity: sha512-kcNPf/gxbME4jA2K26vKfoNErswghPjSNZU+TD+36R4uwlI2JZo/tSsvogWgopMhCscbILcdzMQnaHub39JOnA==} engines: {node: '>=22.0.0'} - '@objectstack/skills@19.0.0-next.2': - resolution: {integrity: sha512-kJs1vnX5XSy2TtiX8aFLepwxYUHMo5ABbvchxCHBpyiBzDTjwsE387iW0ObBZEhaLBj9ovabtQ0MFmEs8XJHxQ==} + '@objectstack/skills@19.0.0-next.3': + resolution: {integrity: sha512-By/gv/MwJ1i/4v5Ci3q8adH9XwLTEQTYJ2/MnWykuYgmqS14uy/OzHoHmT2gDBBPqm0Znkab4YuyQ9KBVtHGyA==} engines: {node: '>=22.0.0'} - '@objectstack/spec@19.0.0-next.2': - resolution: {integrity: sha512-AGDwbw+D75Km3l6J0HwBmE2Q7eMryEPM5ryHLthzbVtn2ChqM/0TnxEWp3zdSw4pkl8zZAmwvw3c24ajlmgOew==} + '@objectstack/spec@19.0.0-next.3': + resolution: {integrity: sha512-CYg1Hto1tIKDu+GiuuXb/jTEDyJRkVhNOGBfu3nbOieU5G0IhT6CPtB3IMC35Oy/Hk6jnzquBm1OO34DDdC4Vg==} engines: {node: '>=22.0.0'} peerDependencies: ai: ^7.0.0 @@ -758,24 +758,24 @@ packages: ai: optional: true - '@objectstack/trigger-api@19.0.0-next.2': - resolution: {integrity: sha512-i9dt/nGSmf1P0rz23XaWx/O5htBM/Qf97jw6nNWJbHTfXd1/G2qzpMBZOnfBnUFTL7kodqYU/cvkzku/BsNlpQ==} + '@objectstack/trigger-api@19.0.0-next.3': + resolution: {integrity: sha512-x8FRJvwLfTXrRzQGRtgm+JVzO6Q54EVoMRw54Sv1JttZnAxjlzQ/n0x1IHko/dJC/VEOZbOHSbL+99H80ZJuow==} engines: {node: '>=22.0.0'} - '@objectstack/trigger-record-change@19.0.0-next.2': - resolution: {integrity: sha512-GuR3NaCJCiLeUD9mST4xcJvYdTqSaH7bGLkNCZwehVPL9T6McXKjvDAGlJ7CdpuCu+cM1lBmplFcCiLzWjCxYw==} + '@objectstack/trigger-record-change@19.0.0-next.3': + resolution: {integrity: sha512-NGZDwKfo+bdk18kl1xkZF/2IZit8+F/fqBdCwK8FUJElIiBBXqiA5JNI39bmoJdatwcKDOVuiVXIYSAB+QvxVg==} engines: {node: '>=22.0.0'} - '@objectstack/trigger-schedule@19.0.0-next.2': - resolution: {integrity: sha512-bVI9lcMdBUwAiQw6YFGReGxz8d9qmO62/sGsJPj8OfH72gTAl0PmV/yrHhJwaoSdXXM7mTf2JETXJldYIur+Og==} + '@objectstack/trigger-schedule@19.0.0-next.3': + resolution: {integrity: sha512-A82Qtrb85tDj+GAirqjBlFBFAs9VsGpC734ALU3zxZa0EXF2Upphv2vlpQs/+HrjBQ2rpGo/88L7pVIX7jC4qw==} engines: {node: '>=22.0.0'} - '@objectstack/types@19.0.0-next.2': - resolution: {integrity: sha512-dob5RVOW/uEeBT4jyoBA/MCpB8QprpTJNsIxZg+9ChQRMfO1inLsZKbIpaKZCijKul7JSQd0EeWasikuVJ/8MQ==} + '@objectstack/types@19.0.0-next.3': + resolution: {integrity: sha512-4sBAmVSKFqtTR4dn6eksMycP7bbs/uX4cTRG+q++DIlRTRK/5dpbGfBfMYnIaeEC9f4QGGe8tddaA9mQ+01uZA==} engines: {node: '>=22.0.0'} - '@objectstack/verify@19.0.0-next.2': - resolution: {integrity: sha512-GWBCEKnnkVh/M2QF69i6K0EPaKXgRhNOuyrH3nH7IMiz3uNpGlPwocZ0REiXNpKjtlbz1Di+EAzdmTl9OSZNig==} + '@objectstack/verify@19.0.0-next.3': + resolution: {integrity: sha512-A1BfE+eyuoxRi55ig9pPA9OJttdNz6Lij9+zCqPJfPtLpOV/L17EH/X3g7fTkMGKqXkuqtppNeMykPJXNJ8qcQ==} engines: {node: '>=22.0.0'} '@oclif/core@5.1.12': @@ -1268,8 +1268,8 @@ packages: resolution: {integrity: sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw==} engines: {node: '>= 10'} - create-objectstack@19.0.0-next.2: - resolution: {integrity: sha512-arypBey/fOHJ0kftVLRgUMLexUsMOEBR6nVbvxO/NOhsl3jXqg7bFwHe+vWEbgQa27mnqtPw0StgGJ7eaIxOjg==} + create-objectstack@19.0.0-next.3: + resolution: {integrity: sha512-786vt6ET0gnlb/t2JeoEOthpI3QI9Q5hkvXbl5CWmBrnfKBp/V5SJl9be9KkI7fO2D6lwJSR3HcV1ipBjnrq9g==} engines: {node: '>=22.0.0'} hasBin: true @@ -3172,73 +3172,73 @@ snapshots: '@nodable/entities@3.1.0': {} - '@objectstack/account@19.0.0-next.2': + '@objectstack/account@19.0.0-next.3': dependencies: - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/cli@19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1)))': - dependencies: - '@objectstack/account': 19.0.0-next.2 - '@objectstack/client': 19.0.0-next.2 - '@objectstack/cloud-connection': 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) - '@objectstack/console': 19.0.0-next.2 - '@objectstack/core': 19.0.0-next.2 - '@objectstack/driver-memory': 19.0.0-next.2 - '@objectstack/driver-mongodb': 19.0.0-next.2 - '@objectstack/driver-sql': 19.0.0-next.2(pg@8.23.1) - '@objectstack/driver-sqlite-wasm': 19.0.0-next.2(better-sqlite3@13.2.0)(pg@8.23.1) - '@objectstack/formula': 19.0.0-next.2 - '@objectstack/knowledge-pgvector': 19.0.0-next.2 - '@objectstack/lint': 19.0.0-next.2 - '@objectstack/mcp': 19.0.0-next.2 - '@objectstack/metadata': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/metadata-protocol': 19.0.0-next.2 - '@objectstack/objectql': 19.0.0-next.2 - '@objectstack/observability': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/plugin-approvals': 19.0.0-next.2 - '@objectstack/plugin-audit': 19.0.0-next.2 - '@objectstack/plugin-auth': 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) - '@objectstack/plugin-email': 19.0.0-next.2 - '@objectstack/plugin-hono-server': 19.0.0-next.2 - '@objectstack/plugin-pinyin-search': 19.0.0-next.2 - '@objectstack/plugin-security': 19.0.0-next.2 - '@objectstack/plugin-sharing': 19.0.0-next.2 - '@objectstack/plugin-webhooks': 19.0.0-next.2 - '@objectstack/rest': 19.0.0-next.2 - '@objectstack/runtime': 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) - '@objectstack/service-analytics': 19.0.0-next.2 - '@objectstack/service-automation': 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) - '@objectstack/service-cache': 19.0.0-next.2 - '@objectstack/service-datasource': 19.0.0-next.2(@objectstack/driver-mongodb@19.0.0-next.2)(@objectstack/driver-sqlite-wasm@19.0.0-next.2(pg@8.23.1))(pg@8.23.1) - '@objectstack/service-job': 19.0.0-next.2 - '@objectstack/service-knowledge': 19.0.0-next.2 - '@objectstack/service-mailbox': 19.0.0-next.2 - '@objectstack/service-messaging': 19.0.0-next.2 - '@objectstack/service-package': 19.0.0-next.2 - '@objectstack/service-push': 19.0.0-next.2 - '@objectstack/service-queue': 19.0.0-next.2 - '@objectstack/service-realtime': 19.0.0-next.2 - '@objectstack/service-record-context': 19.0.0-next.2 - '@objectstack/service-settings': 19.0.0-next.2 - '@objectstack/service-sms': 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) - '@objectstack/service-storage': 19.0.0-next.2 - '@objectstack/setup': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/trigger-api': 19.0.0-next.2 - '@objectstack/trigger-record-change': 19.0.0-next.2 - '@objectstack/trigger-schedule': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 - '@objectstack/verify': 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(@objectstack/driver-mongodb@19.0.0-next.2)(@objectstack/driver-sqlite-wasm@19.0.0-next.2(pg@8.23.1))(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + '@objectstack/cli@19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1)))': + dependencies: + '@objectstack/account': 19.0.0-next.3 + '@objectstack/client': 19.0.0-next.3 + '@objectstack/cloud-connection': 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + '@objectstack/console': 19.0.0-next.3 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/driver-memory': 19.0.0-next.3 + '@objectstack/driver-mongodb': 19.0.0-next.3 + '@objectstack/driver-sql': 19.0.0-next.3(pg@8.23.1) + '@objectstack/driver-sqlite-wasm': 19.0.0-next.3(better-sqlite3@13.2.0)(pg@8.23.1) + '@objectstack/formula': 19.0.0-next.3 + '@objectstack/knowledge-pgvector': 19.0.0-next.3 + '@objectstack/lint': 19.0.0-next.3 + '@objectstack/mcp': 19.0.0-next.3 + '@objectstack/metadata': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/metadata-protocol': 19.0.0-next.3 + '@objectstack/objectql': 19.0.0-next.3 + '@objectstack/observability': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/plugin-approvals': 19.0.0-next.3 + '@objectstack/plugin-audit': 19.0.0-next.3 + '@objectstack/plugin-auth': 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + '@objectstack/plugin-email': 19.0.0-next.3 + '@objectstack/plugin-hono-server': 19.0.0-next.3 + '@objectstack/plugin-pinyin-search': 19.0.0-next.3 + '@objectstack/plugin-security': 19.0.0-next.3 + '@objectstack/plugin-sharing': 19.0.0-next.3 + '@objectstack/plugin-webhooks': 19.0.0-next.3 + '@objectstack/rest': 19.0.0-next.3 + '@objectstack/runtime': 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + '@objectstack/service-analytics': 19.0.0-next.3 + '@objectstack/service-automation': 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + '@objectstack/service-cache': 19.0.0-next.3 + '@objectstack/service-datasource': 19.0.0-next.3(@objectstack/driver-mongodb@19.0.0-next.3)(@objectstack/driver-sqlite-wasm@19.0.0-next.3(pg@8.23.1))(pg@8.23.1) + '@objectstack/service-job': 19.0.0-next.3 + '@objectstack/service-knowledge': 19.0.0-next.3 + '@objectstack/service-mailbox': 19.0.0-next.3 + '@objectstack/service-messaging': 19.0.0-next.3 + '@objectstack/service-package': 19.0.0-next.3 + '@objectstack/service-push': 19.0.0-next.3 + '@objectstack/service-queue': 19.0.0-next.3 + '@objectstack/service-realtime': 19.0.0-next.3 + '@objectstack/service-record-context': 19.0.0-next.3 + '@objectstack/service-settings': 19.0.0-next.3 + '@objectstack/service-sms': 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + '@objectstack/service-storage': 19.0.0-next.3 + '@objectstack/setup': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/trigger-api': 19.0.0-next.3 + '@objectstack/trigger-record-change': 19.0.0-next.3 + '@objectstack/trigger-schedule': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 + '@objectstack/verify': 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(@objectstack/driver-mongodb@19.0.0-next.3)(@objectstack/driver-sqlite-wasm@19.0.0-next.3(pg@8.23.1))(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) '@oclif/core': 5.1.12 bundle-require: 5.1.0(esbuild@0.28.2) chalk: 6.0.1 chokidar: 5.0.0 - create-objectstack: 19.0.0-next.2 + create-objectstack: 19.0.0-next.3 dotenv-flow: 4.1.0 esbuild: 0.28.2 tsx: 4.23.15 @@ -3246,7 +3246,7 @@ snapshots: yaml: 2.9.1 zod: 4.6.7 optionalDependencies: - '@objectstack/knowledge-turso': 19.0.0-next.2 + '@objectstack/knowledge-turso': 19.0.0-next.3 better-sqlite3: 13.2.0 transitivePeerDependencies: - '@aws-sdk/client-s3' @@ -3296,25 +3296,25 @@ snapshots: - vitest - vue - '@objectstack/client@19.0.0-next.2': + '@objectstack/client@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/cloud-connection@19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1)))': - dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/metadata-protocol': 19.0.0-next.2 - '@objectstack/objectql': 19.0.0-next.2 - '@objectstack/observability': 19.0.0-next.2 - '@objectstack/rest': 19.0.0-next.2 - '@objectstack/runtime': 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) - '@objectstack/service-cluster': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/cloud-connection@19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1)))': + dependencies: + '@objectstack/core': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/metadata-protocol': 19.0.0-next.3 + '@objectstack/objectql': 19.0.0-next.3 + '@objectstack/observability': 19.0.0-next.3 + '@objectstack/rest': 19.0.0-next.3 + '@objectstack/runtime': 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + '@objectstack/service-cluster': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - '@aws-sdk/credential-providers' - '@better-auth/utils' @@ -3359,62 +3359,62 @@ snapshots: - vitest - vue - '@objectstack/connector-imap@19.0.0-next.2': {} + '@objectstack/connector-imap@19.0.0-next.3': {} - '@objectstack/connector-mcp@19.0.0-next.2(zod@4.6.7)': + '@objectstack/connector-mcp@19.0.0-next.3(zod@4.6.7)': dependencies: '@modelcontextprotocol/sdk': 1.32.2(zod@4.6.7) - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - '@cfworker/json-schema' - ai - supports-color - zod - '@objectstack/connector-openapi@19.0.0-next.2': + '@objectstack/connector-openapi@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/connector-rest@19.0.0-next.2': + '@objectstack/connector-rest@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/console@19.0.0-next.2': {} + '@objectstack/console@19.0.0-next.3': {} - '@objectstack/core@19.0.0-next.2': + '@objectstack/core@19.0.0-next.3': dependencies: - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 undici: 7.30.2 zod: 4.6.7 transitivePeerDependencies: - ai - '@objectstack/driver-memory@19.0.0-next.2': + '@objectstack/driver-memory@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 mingo: 7.2.7 transitivePeerDependencies: - ai - '@objectstack/driver-mongodb@19.0.0-next.2': + '@objectstack/driver-mongodb@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 mongodb: 7.9.1 nanoid: 6.0.2 transitivePeerDependencies: @@ -3427,12 +3427,12 @@ snapshots: - snappy - socks - '@objectstack/driver-sql@19.0.0-next.2(pg@8.23.1)': + '@objectstack/driver-sql@19.0.0-next.3(pg@8.23.1)': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/observability': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/observability': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 knex: 3.3.0(better-sqlite3@13.2.0)(pg@8.23.1) nanoid: 6.0.2 optionalDependencies: @@ -3447,11 +3447,11 @@ snapshots: - sqlite3 - supports-color - '@objectstack/driver-sqlite-wasm@19.0.0-next.2(better-sqlite3@13.2.0)(pg@8.23.1)': + '@objectstack/driver-sqlite-wasm@19.0.0-next.3(better-sqlite3@13.2.0)(pg@8.23.1)': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/driver-sql': 19.0.0-next.2(pg@8.23.1) - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/driver-sql': 19.0.0-next.3(pg@8.23.1) + '@objectstack/spec': 19.0.0-next.3 knex: 3.3.0(better-sqlite3@13.2.0)(pg@8.23.1) nanoid: 6.0.2 sql.js: 1.17.0 @@ -3469,45 +3469,45 @@ snapshots: - supports-color - tedious - '@objectstack/embedder-openai@19.0.0-next.2': + '@objectstack/embedder-openai@19.0.0-next.3': dependencies: - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/formula@19.0.0-next.2': + '@objectstack/formula@19.0.0-next.3': dependencies: '@marcbachmann/cel-js': 8.0.0 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/knowledge-pgvector@19.0.0-next.2': + '@objectstack/knowledge-pgvector@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 pg: 8.23.1 transitivePeerDependencies: - ai - pg-native - '@objectstack/knowledge-turso@19.0.0-next.2': + '@objectstack/knowledge-turso@19.0.0-next.3': dependencies: '@libsql/client': 0.18.0 - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - bufferutil - utf-8-validate optional: true - '@objectstack/lint@19.0.0-next.2': + '@objectstack/lint@19.0.0-next.3': dependencies: - '@objectstack/formula': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/sdui-parser': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/formula': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/sdui-parser': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 ajv: 8.20.0 ajv-formats: 3.0.1(ajv@8.20.0) sucrase: 3.35.1 @@ -3515,16 +3515,16 @@ snapshots: transitivePeerDependencies: - ai - '@objectstack/mcp@19.0.0-next.2': + '@objectstack/mcp@19.0.0-next.3': dependencies: '@modelcontextprotocol/sdk': 1.32.2(zod@4.6.7) - '@objectstack/core': 19.0.0-next.2 - '@objectstack/formula': 19.0.0-next.2 - '@objectstack/lint': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/rest': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/formula': 19.0.0-next.3 + '@objectstack/lint': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/rest': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 unpdf: 1.9.1 zod: 4.6.7 transitivePeerDependencies: @@ -3533,41 +3533,41 @@ snapshots: - ai - supports-color - '@objectstack/metadata-core@19.0.0-next.2': + '@objectstack/metadata-core@19.0.0-next.3': dependencies: - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/spec': 19.0.0-next.3 zod: 4.6.7 transitivePeerDependencies: - ai - '@objectstack/metadata-fs@19.0.0-next.2': + '@objectstack/metadata-fs@19.0.0-next.3': dependencies: - '@objectstack/metadata-core': 19.0.0-next.2 + '@objectstack/metadata-core': 19.0.0-next.3 chokidar: 5.0.0 transitivePeerDependencies: - ai - '@objectstack/metadata-protocol@19.0.0-next.2': + '@objectstack/metadata-protocol@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/formula': 19.0.0-next.2 - '@objectstack/lint': 19.0.0-next.2 - '@objectstack/metadata': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/sdui-parser': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/formula': 19.0.0-next.3 + '@objectstack/lint': 19.0.0-next.3 + '@objectstack/metadata': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/sdui-parser': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 zod: 4.6.7 transitivePeerDependencies: - ai - '@objectstack/metadata@19.0.0-next.2': + '@objectstack/metadata@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/metadata-fs': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/metadata-fs': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 chokidar: 5.0.0 glob: 14.0.6 js-yaml: 5.5.0 @@ -3575,71 +3575,71 @@ snapshots: transitivePeerDependencies: - ai - '@objectstack/objectql@19.0.0-next.2': + '@objectstack/objectql@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/formula': 19.0.0-next.2 - '@objectstack/metadata': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/metadata-protocol': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/formula': 19.0.0-next.3 + '@objectstack/metadata': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/metadata-protocol': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 ajv: 8.20.0 ajv-formats: 3.0.1(ajv@8.20.0) zod: 4.6.7 transitivePeerDependencies: - ai - '@objectstack/observability@19.0.0-next.2': + '@objectstack/observability@19.0.0-next.3': dependencies: - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/platform-objects@19.0.0-next.2': + '@objectstack/platform-objects@19.0.0-next.3': dependencies: - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/plugin-approvals@19.0.0-next.2': + '@objectstack/plugin-approvals@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/formula': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/formula': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/plugin-audit@19.0.0-next.2': + '@objectstack/plugin-audit@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/objectql': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/plugin-hono-server': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/objectql': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/plugin-hono-server': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/plugin-auth@19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1)))': + '@objectstack/plugin-auth@19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1)))': dependencies: '@better-auth/core': 1.7.12(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(jose@6.2.18)(kysely@0.29.9)(nanostores@1.5.5) '@better-auth/oauth-provider': 1.7.12(@better-auth/core@1.7.12(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(jose@6.2.18)(kysely@0.29.9)(nanostores@1.5.5))(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-auth@1.7.12(mongodb@7.9.1)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))))(better-call@1.4.4(zod@4.6.7)) '@better-auth/scim': 1.7.12(@better-auth/core@1.7.12(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(jose@6.2.18)(kysely@0.29.9)(nanostores@1.5.5))(@better-auth/utils@0.5.0)(better-auth@1.7.12(mongodb@7.9.1)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))))(better-call@1.4.4(zod@4.6.7)) '@better-auth/sso': 1.7.12(@better-auth/core@1.7.12(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(jose@6.2.18)(kysely@0.29.9)(nanostores@1.5.5))(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-auth@1.7.12(mongodb@7.9.1)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))))(better-call@1.4.4(zod@4.6.7)) '@noble/hashes': 2.4.0 - '@objectstack/core': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/plugin-hono-server': 19.0.0-next.2 - '@objectstack/rest': 19.0.0-next.2 - '@objectstack/service-messaging': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/plugin-hono-server': 19.0.0-next.3 + '@objectstack/rest': 19.0.0-next.3 + '@objectstack/service-messaging': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 better-auth: 1.7.12(mongodb@7.9.1)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) fast-xml-parser: 5.12.0 hono: 4.13.20 @@ -3671,113 +3671,113 @@ snapshots: - vitest - vue - '@objectstack/plugin-email@19.0.0-next.2': + '@objectstack/plugin-email@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/formula': 19.0.0-next.2 - '@objectstack/objectql': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/formula': 19.0.0-next.3 + '@objectstack/objectql': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 nodemailer: 10.6.1 transitivePeerDependencies: - ai - '@objectstack/plugin-hono-server@19.0.0-next.2': + '@objectstack/plugin-hono-server@19.0.0-next.3': dependencies: '@hono/node-server': 2.1.11(hono@4.13.20) - '@objectstack/core': 19.0.0-next.2 - '@objectstack/observability': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/observability': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 hono: 4.13.20 transitivePeerDependencies: - ai - '@objectstack/plugin-pinyin-search@19.0.0-next.2': + '@objectstack/plugin-pinyin-search@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/objectql': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/objectql': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 pinyin-pro: 3.29.5 transitivePeerDependencies: - ai - '@objectstack/plugin-security@19.0.0-next.2': + '@objectstack/plugin-security@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/formula': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/formula': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/plugin-sharing@19.0.0-next.2': + '@objectstack/plugin-sharing@19.0.0-next.3': dependencies: '@noble/hashes': 2.4.0 - '@objectstack/core': 19.0.0-next.2 - '@objectstack/formula': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/objectql': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/formula': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/objectql': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/plugin-webhooks@19.0.0-next.2': + '@objectstack/plugin-webhooks@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/objectql': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/service-messaging': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/objectql': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/service-messaging': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/rest@19.0.0-next.2': + '@objectstack/rest@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/metadata': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/observability': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/service-package': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/metadata': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/observability': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/service-package': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 exceljs: 4.4.0 zod: 4.6.7 transitivePeerDependencies: - ai - '@objectstack/runtime@19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1)))': - dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/driver-memory': 19.0.0-next.2 - '@objectstack/driver-sql': 19.0.0-next.2(pg@8.23.1) - '@objectstack/driver-sqlite-wasm': 19.0.0-next.2(better-sqlite3@13.2.0)(pg@8.23.1) - '@objectstack/formula': 19.0.0-next.2 - '@objectstack/lint': 19.0.0-next.2 - '@objectstack/metadata': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/metadata-protocol': 19.0.0-next.2 - '@objectstack/objectql': 19.0.0-next.2 - '@objectstack/observability': 19.0.0-next.2 - '@objectstack/plugin-auth': 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) - '@objectstack/plugin-security': 19.0.0-next.2 - '@objectstack/rest': 19.0.0-next.2 - '@objectstack/service-cluster': 19.0.0-next.2 - '@objectstack/service-datasource': 19.0.0-next.2(@objectstack/driver-mongodb@19.0.0-next.2)(@objectstack/driver-sqlite-wasm@19.0.0-next.2(pg@8.23.1))(pg@8.23.1) - '@objectstack/service-i18n': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/runtime@19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1)))': + dependencies: + '@objectstack/core': 19.0.0-next.3 + '@objectstack/driver-memory': 19.0.0-next.3 + '@objectstack/driver-sql': 19.0.0-next.3(pg@8.23.1) + '@objectstack/driver-sqlite-wasm': 19.0.0-next.3(better-sqlite3@13.2.0)(pg@8.23.1) + '@objectstack/formula': 19.0.0-next.3 + '@objectstack/lint': 19.0.0-next.3 + '@objectstack/metadata': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/metadata-protocol': 19.0.0-next.3 + '@objectstack/objectql': 19.0.0-next.3 + '@objectstack/observability': 19.0.0-next.3 + '@objectstack/plugin-auth': 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + '@objectstack/plugin-security': 19.0.0-next.3 + '@objectstack/rest': 19.0.0-next.3 + '@objectstack/service-cluster': 19.0.0-next.3 + '@objectstack/service-datasource': 19.0.0-next.3(@objectstack/driver-mongodb@19.0.0-next.3)(@objectstack/driver-sqlite-wasm@19.0.0-next.3(pg@8.23.1))(pg@8.23.1) + '@objectstack/service-i18n': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 quickjs-emscripten: 0.32.0 zod: 4.6.7 optionalDependencies: - '@objectstack/driver-mongodb': 19.0.0-next.2 + '@objectstack/driver-mongodb': 19.0.0-next.3 transitivePeerDependencies: - '@aws-sdk/credential-providers' - '@better-auth/utils' @@ -3821,27 +3821,27 @@ snapshots: - vitest - vue - '@objectstack/sdui-parser@19.0.0-next.2': {} + '@objectstack/sdui-parser@19.0.0-next.3': {} - '@objectstack/service-analytics@19.0.0-next.2': + '@objectstack/service-analytics@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/service-automation@19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1)))': - dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/formula': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/metadata-protocol': 19.0.0-next.2 - '@objectstack/objectql': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/plugin-auth': 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/service-automation@19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1)))': + dependencies: + '@objectstack/core': 19.0.0-next.3 + '@objectstack/formula': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/metadata-protocol': 19.0.0-next.3 + '@objectstack/objectql': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/plugin-auth': 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - '@better-auth/utils' - '@better-fetch/fetch' @@ -3869,34 +3869,34 @@ snapshots: - vitest - vue - '@objectstack/service-cache@19.0.0-next.2': + '@objectstack/service-cache@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/observability': 19.0.0-next.2 - '@objectstack/service-cluster': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/observability': 19.0.0-next.3 + '@objectstack/service-cluster': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/service-cluster@19.0.0-next.2': + '@objectstack/service-cluster@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/service-datasource@19.0.0-next.2(@objectstack/driver-mongodb@19.0.0-next.2)(@objectstack/driver-sqlite-wasm@19.0.0-next.2(pg@8.23.1))(pg@8.23.1)': + '@objectstack/service-datasource@19.0.0-next.3(@objectstack/driver-mongodb@19.0.0-next.3)(@objectstack/driver-sqlite-wasm@19.0.0-next.3(pg@8.23.1))(pg@8.23.1)': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/driver-memory': 19.0.0-next.2 - '@objectstack/driver-sql': 19.0.0-next.2(pg@8.23.1) - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/driver-memory': 19.0.0-next.3 + '@objectstack/driver-sql': 19.0.0-next.3(pg@8.23.1) + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 pg-connection-string: 2.14.1 optionalDependencies: - '@objectstack/driver-mongodb': 19.0.0-next.2 - '@objectstack/driver-sqlite-wasm': 19.0.0-next.2(better-sqlite3@13.2.0)(pg@8.23.1) + '@objectstack/driver-mongodb': 19.0.0-next.3 + '@objectstack/driver-sqlite-wasm': 19.0.0-next.3(better-sqlite3@13.2.0)(pg@8.23.1) transitivePeerDependencies: - ai - mariadb @@ -3910,107 +3910,108 @@ snapshots: - supports-color - tedious - '@objectstack/service-i18n@19.0.0-next.2': + '@objectstack/service-i18n@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/service-job@19.0.0-next.2': + '@objectstack/service-job@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 croner: 10.0.1 transitivePeerDependencies: - ai - '@objectstack/service-knowledge@19.0.0-next.2': + '@objectstack/service-knowledge@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/embedder-openai': 19.0.0-next.2 - '@objectstack/service-settings': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/embedder-openai': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/service-settings': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/service-mailbox@19.0.0-next.2': + '@objectstack/service-mailbox@19.0.0-next.3': dependencies: - '@objectstack/connector-imap': 19.0.0-next.2 - '@objectstack/core': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/connector-imap': 19.0.0-next.3 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 postal-mime: 4.2.1 transitivePeerDependencies: - ai - '@objectstack/service-messaging@19.0.0-next.2': + '@objectstack/service-messaging@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/service-package@19.0.0-next.2': + '@objectstack/service-package@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/service-push@19.0.0-next.2': + '@objectstack/service-push@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/service-queue@19.0.0-next.2': + '@objectstack/service-queue@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/service-realtime@19.0.0-next.2': + '@objectstack/service-realtime@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/service-record-context@19.0.0-next.2': + '@objectstack/service-record-context@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/service-settings@19.0.0-next.2': + '@objectstack/service-settings@19.0.0-next.3': dependencies: '@noble/ciphers': 2.4.0 - '@objectstack/core': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/service-sms@19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1)))': + '@objectstack/service-sms@19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1)))': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/plugin-auth': 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/plugin-auth': 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - '@better-auth/utils' - '@better-fetch/fetch' @@ -4038,104 +4039,104 @@ snapshots: - vitest - vue - '@objectstack/service-storage@19.0.0-next.2': + '@objectstack/service-storage@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/observability': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/plugin-hono-server': 19.0.0-next.2 - '@objectstack/service-cluster': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/observability': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/plugin-hono-server': 19.0.0-next.3 + '@objectstack/service-cluster': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/setup@19.0.0-next.2': + '@objectstack/setup@19.0.0-next.3': dependencies: - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/skills@19.0.0-next.2': {} + '@objectstack/skills@19.0.0-next.3': {} - '@objectstack/spec@19.0.0-next.2': + '@objectstack/spec@19.0.0-next.3': dependencies: pg-connection-string: 2.14.1 zod: 4.6.7 - '@objectstack/trigger-api@19.0.0-next.2': + '@objectstack/trigger-api@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/trigger-record-change@19.0.0-next.2': + '@objectstack/trigger-record-change@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/trigger-schedule@19.0.0-next.2': + '@objectstack/trigger-schedule@19.0.0-next.3': dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/metadata-core': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/core': 19.0.0-next.3 + '@objectstack/metadata-core': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 croner: 10.0.1 transitivePeerDependencies: - ai - '@objectstack/types@19.0.0-next.2': + '@objectstack/types@19.0.0-next.3': dependencies: - '@objectstack/spec': 19.0.0-next.2 + '@objectstack/spec': 19.0.0-next.3 transitivePeerDependencies: - ai - '@objectstack/verify@19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(@objectstack/driver-mongodb@19.0.0-next.2)(@objectstack/driver-sqlite-wasm@19.0.0-next.2(pg@8.23.1))(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1)))': - dependencies: - '@objectstack/core': 19.0.0-next.2 - '@objectstack/knowledge-pgvector': 19.0.0-next.2 - '@objectstack/mcp': 19.0.0-next.2 - '@objectstack/metadata': 19.0.0-next.2 - '@objectstack/objectql': 19.0.0-next.2 - '@objectstack/platform-objects': 19.0.0-next.2 - '@objectstack/plugin-approvals': 19.0.0-next.2 - '@objectstack/plugin-audit': 19.0.0-next.2 - '@objectstack/plugin-auth': 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) - '@objectstack/plugin-email': 19.0.0-next.2 - '@objectstack/plugin-hono-server': 19.0.0-next.2 - '@objectstack/plugin-pinyin-search': 19.0.0-next.2 - '@objectstack/plugin-security': 19.0.0-next.2 - '@objectstack/plugin-sharing': 19.0.0-next.2 - '@objectstack/plugin-webhooks': 19.0.0-next.2 - '@objectstack/rest': 19.0.0-next.2 - '@objectstack/runtime': 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) - '@objectstack/service-analytics': 19.0.0-next.2 - '@objectstack/service-automation': 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) - '@objectstack/service-cache': 19.0.0-next.2 - '@objectstack/service-datasource': 19.0.0-next.2(@objectstack/driver-mongodb@19.0.0-next.2)(@objectstack/driver-sqlite-wasm@19.0.0-next.2(pg@8.23.1))(pg@8.23.1) - '@objectstack/service-job': 19.0.0-next.2 - '@objectstack/service-knowledge': 19.0.0-next.2 - '@objectstack/service-mailbox': 19.0.0-next.2 - '@objectstack/service-messaging': 19.0.0-next.2 - '@objectstack/service-package': 19.0.0-next.2 - '@objectstack/service-push': 19.0.0-next.2 - '@objectstack/service-queue': 19.0.0-next.2 - '@objectstack/service-realtime': 19.0.0-next.2 - '@objectstack/service-record-context': 19.0.0-next.2 - '@objectstack/service-settings': 19.0.0-next.2 - '@objectstack/service-sms': 19.0.0-next.2(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) - '@objectstack/service-storage': 19.0.0-next.2 - '@objectstack/spec': 19.0.0-next.2 - '@objectstack/trigger-api': 19.0.0-next.2 - '@objectstack/trigger-record-change': 19.0.0-next.2 - '@objectstack/trigger-schedule': 19.0.0-next.2 - '@objectstack/types': 19.0.0-next.2 + '@objectstack/verify@19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(@objectstack/driver-mongodb@19.0.0-next.3)(@objectstack/driver-sqlite-wasm@19.0.0-next.3(pg@8.23.1))(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1)))': + dependencies: + '@objectstack/core': 19.0.0-next.3 + '@objectstack/knowledge-pgvector': 19.0.0-next.3 + '@objectstack/mcp': 19.0.0-next.3 + '@objectstack/metadata': 19.0.0-next.3 + '@objectstack/objectql': 19.0.0-next.3 + '@objectstack/platform-objects': 19.0.0-next.3 + '@objectstack/plugin-approvals': 19.0.0-next.3 + '@objectstack/plugin-audit': 19.0.0-next.3 + '@objectstack/plugin-auth': 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + '@objectstack/plugin-email': 19.0.0-next.3 + '@objectstack/plugin-hono-server': 19.0.0-next.3 + '@objectstack/plugin-pinyin-search': 19.0.0-next.3 + '@objectstack/plugin-security': 19.0.0-next.3 + '@objectstack/plugin-sharing': 19.0.0-next.3 + '@objectstack/plugin-webhooks': 19.0.0-next.3 + '@objectstack/rest': 19.0.0-next.3 + '@objectstack/runtime': 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(better-sqlite3@13.2.0)(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + '@objectstack/service-analytics': 19.0.0-next.3 + '@objectstack/service-automation': 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + '@objectstack/service-cache': 19.0.0-next.3 + '@objectstack/service-datasource': 19.0.0-next.3(@objectstack/driver-mongodb@19.0.0-next.3)(@objectstack/driver-sqlite-wasm@19.0.0-next.3(pg@8.23.1))(pg@8.23.1) + '@objectstack/service-job': 19.0.0-next.3 + '@objectstack/service-knowledge': 19.0.0-next.3 + '@objectstack/service-mailbox': 19.0.0-next.3 + '@objectstack/service-messaging': 19.0.0-next.3 + '@objectstack/service-package': 19.0.0-next.3 + '@objectstack/service-push': 19.0.0-next.3 + '@objectstack/service-queue': 19.0.0-next.3 + '@objectstack/service-realtime': 19.0.0-next.3 + '@objectstack/service-record-context': 19.0.0-next.3 + '@objectstack/service-settings': 19.0.0-next.3 + '@objectstack/service-sms': 19.0.0-next.3(@better-auth/utils@0.5.0)(@better-fetch/fetch@1.3.2)(better-call@1.4.4(zod@4.6.7))(kysely@0.29.9)(mongodb@7.9.1)(nanostores@1.5.5)(pg@8.23.1)(vitest@4.1.12(@types/node@22.20.5)(vite@8.3.8(@types/node@22.20.5)(esbuild@0.28.2)(tsx@4.23.15)(yaml@2.9.1))) + '@objectstack/service-storage': 19.0.0-next.3 + '@objectstack/spec': 19.0.0-next.3 + '@objectstack/trigger-api': 19.0.0-next.3 + '@objectstack/trigger-record-change': 19.0.0-next.3 + '@objectstack/trigger-schedule': 19.0.0-next.3 + '@objectstack/types': 19.0.0-next.3 optionalDependencies: - '@objectstack/knowledge-turso': 19.0.0-next.2 + '@objectstack/knowledge-turso': 19.0.0-next.3 transitivePeerDependencies: - '@aws-sdk/client-s3' - '@aws-sdk/credential-providers' @@ -4632,7 +4633,7 @@ snapshots: crc-32: 1.2.2 readable-stream: 3.6.2 - create-objectstack@19.0.0-next.2: + create-objectstack@19.0.0-next.3: dependencies: chalk: 6.0.1 commander: 15.1.0 diff --git a/scripts/eval/driver/ask.ts b/scripts/eval/driver/ask.ts index aba7ed0..62e134f 100644 --- a/scripts/eval/driver/ask.ts +++ b/scripts/eval/driver/ask.ts @@ -4,7 +4,7 @@ * - Earlier user turns (`context_turns`) go first, in the same conversation; * their answers are not graded and their tool calls are not counted. * - A pinned question (`pinned_policy`) sends the record as the - * conversation's focus, as 「问这份制度」 does in the console. + * conversation's focus, as the record page's 「问 AI」 does in the console. * - When the first answer is a clarifying question, the persona answers it * once (`clarify_reply`, else its `self_description`) and the second answer * is the one graded. A second clarifying question is not answered. diff --git a/scripts/eval/driver/mcp.ts b/scripts/eval/driver/mcp.ts index 6fc4dd7..b3217c5 100644 --- a/scripts/eval/driver/mcp.ts +++ b/scripts/eval/driver/mcp.ts @@ -116,7 +116,7 @@ export function parseRpcBody(text: string): { result?: unknown; error?: unknown /** The system prompt an MCP client gives its model: the server's instructions, the skill on the prompt arm, and the pinned record when there is one. */ export function systemPrompt(instructions: string, skill: string, focus: { object: string; id: string } | undefined, asker?: string): string { const pin = focus - ? `员工正在看一份制度,并在制度页点了「问这份制度」:对话已钉住这份制度,对象 ${focus.object},记录 id ${focus.id}。` + ? `员工正在看一份制度,并在制度页点了「问 AI」:对话已钉住这份制度,对象 ${focus.object},记录 id ${focus.id}。` : ''; return [instructions, skill, asker ?? '', pin].filter(Boolean).join('\n\n'); } diff --git a/skills-lock.json b/skills-lock.json index 5e1969a..eefbc03 100644 --- a/skills-lock.json +++ b/skills-lock.json @@ -5,99 +5,99 @@ "source": "@objectstack/skills", "sourceType": "node_modules", "skillPath": "dist/skills/objectstack-ai/SKILL.md", - "version": "19.0.0-next.2", - "computedHash": "1ba545788bdabb793ba8b674d5a9fcf762eaef3c75a8c107b98f71b63c6e138d" + "version": "19.0.0-next.3", + "computedHash": "772f9cfbb24ff8565a911d1a396a87650b14d5afb374ce6d52ccf96bda20b577" }, "objectstack-api": { "source": "@objectstack/skills", "sourceType": "node_modules", "skillPath": "dist/skills/objectstack-api/SKILL.md", - "version": "19.0.0-next.2", - "computedHash": "edb4cf1f18f14c2baf00c2be52145ccb673b43a073098b1dbf4cc868afd77eb9" + "version": "19.0.0-next.3", + "computedHash": "27b03e386bfabf76988bbdde2807ec0e546cd260995e32ad069c9b47b16192f3" }, "objectstack-ask": { "source": "@objectstack/skills", "sourceType": "node_modules", "skillPath": "dist/skills/objectstack-ask/SKILL.md", - "version": "19.0.0-next.2", - "computedHash": "4d1f72161dffba3bab65a7bc95246537fce6a56b90036c14631b82f4b46368c7" + "version": "19.0.0-next.3", + "computedHash": "0bf6ffb5812c4348aee0cf74d25aa620338979a3e4d92fa6e6f9d527245492db" }, "objectstack-automation": { "source": "@objectstack/skills", "sourceType": "node_modules", "skillPath": "dist/skills/objectstack-automation/SKILL.md", - "version": "19.0.0-next.2", - "computedHash": "66d9eca35be9e73920c32d21cbdaff30a4ce7c6be1746a33eee2bf6ba47bcd16" + "version": "19.0.0-next.3", + "computedHash": "a88e7620ac01298ba4388a236c663bfc7e1feedb0a88511d7de400ef6fb1a944" }, "objectstack-data": { "source": "@objectstack/skills", "sourceType": "node_modules", "skillPath": "dist/skills/objectstack-data/SKILL.md", - "version": "19.0.0-next.2", - "computedHash": "6e56eb9932561d93566b98d83522bd01a340312aa5bc31284719243acdaf8b37" + "version": "19.0.0-next.3", + "computedHash": "2a9cc8657669f9b25c110da00ff983fae5a2b95bab64324da2c5ddc360587690" }, "objectstack-formula": { "source": "@objectstack/skills", "sourceType": "node_modules", "skillPath": "dist/skills/objectstack-formula/SKILL.md", - "version": "19.0.0-next.2", - "computedHash": "7ae1265e78e7634ed4fd4ace827b1172040d2d17a226fbfd34eec67f0083e962" + "version": "19.0.0-next.3", + "computedHash": "ad4b0588d5743d481df0eeb0f70136892ad56f97e215d45ac5910fff86893c68" }, "objectstack-i18n": { "source": "@objectstack/skills", "sourceType": "node_modules", "skillPath": "dist/skills/objectstack-i18n/SKILL.md", - "version": "19.0.0-next.2", - "computedHash": "a096d3f83aaccbd0ae8684eb194085a4bce5b21edfbef049c2d2e71ffe603d3d" + "version": "19.0.0-next.3", + "computedHash": "699331c03bb4c61b6d98259c73e5332d06c77e74f8818f69f6cfd2ee0845c048" }, "objectstack-mcp-build": { "source": "@objectstack/skills", "sourceType": "node_modules", "skillPath": "dist/skills/objectstack-mcp-build/SKILL.md", - "version": "19.0.0-next.2", - "computedHash": "71080245cc8b233bb4db62d39969a19864ff4d39ce1b3e47d57115afa8191ac1" + "version": "19.0.0-next.3", + "computedHash": "61cf2332b5b9c1396ee6e436e5e75c823037bb92bd4225676bc973b2b4e8e0a0" }, "objectstack-platform": { "source": "@objectstack/skills", "sourceType": "node_modules", "skillPath": "dist/skills/objectstack-platform/SKILL.md", - "version": "19.0.0-next.2", - "computedHash": "5dcdd1d4dfdfd617c8c2bc2e2630c41ab7ee7db8617c01adb8d0dde3dc065f33" + "version": "19.0.0-next.3", + "computedHash": "7c536fe32ef596329f81af1f7b22f945d41e02cb1ecea77d1991b652e47a3557" }, "objectstack-project": { "source": "@objectstack/skills", "sourceType": "node_modules", "skillPath": "dist/skills/objectstack-project/SKILL.md", - "version": "19.0.0-next.2", - "computedHash": "1054188a035173bfa27f07e876ad4bcd5c0b5bbdcf17ac2677778e7184498c94" + "version": "19.0.0-next.3", + "computedHash": "e9fff940e8e0cd70706a0129d7bc588cc506e0ef8a80b47284b04594faeef5b3" }, "objectstack-query": { "source": "@objectstack/skills", "sourceType": "node_modules", "skillPath": "dist/skills/objectstack-query/SKILL.md", - "version": "19.0.0-next.2", - "computedHash": "7140a078c588bd2e44040c43de61e3f8df4dd7000c0107adfe6b32407b87bb45" + "version": "19.0.0-next.3", + "computedHash": "0fceb5f418fa83dd70779f8b251be49775786f0b4509e7c78281902155436dab" }, "objectstack-ui": { "source": "@objectstack/skills", "sourceType": "node_modules", "skillPath": "dist/skills/objectstack-ui/SKILL.md", - "version": "19.0.0-next.2", - "computedHash": "e5347bb3e673afad2d371357195aa64d99db989a01208482340dea9c7520992c" + "version": "19.0.0-next.3", + "computedHash": "d6634861f1b4defaedfbf700d0f5424d9e641fd24b8c426c5b39a085d00374ce" }, "objectstack-upgrade": { "source": "@objectstack/skills", "sourceType": "node_modules", "skillPath": "dist/skills/objectstack-upgrade/SKILL.md", - "version": "19.0.0-next.2", - "computedHash": "78837c7165897edae05c6580c1a70c6a48cc11369b6c004911aa25902adbcbda" + "version": "19.0.0-next.3", + "computedHash": "43826152c943b9c320eb31681643928349fc0a84ce090d1c03104a6cf668ec30" }, "objectui": { "source": "@objectstack/skills", "sourceType": "node_modules", "skillPath": "dist/skills/objectui/SKILL.md", - "version": "19.0.0-next.2", - "computedHash": "44503d305629686554ec883b353415bdb1a4279b6ca68d1e976de580f3c13750" + "version": "19.0.0-next.3", + "computedHash": "3b444812b48e5d4df7f86f36e72c3cb41d2702d068e536cb90df85ecfc00d4ff" } } } diff --git a/src/actions/ask-policy.action.ts b/src/actions/ask-policy.action.ts deleted file mode 100644 index 50c183a..0000000 --- a/src/actions/ask-policy.action.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { defineAction } from '@objectstack/spec/ui'; - -/** - * 问这份制度 — 在制度页标题栏和制度库每一行的菜单里,打开 AI 问询并钉住这份制度。 - * - * `ask_ai` 不在服务端执行,也不是 AI 工具:控制台把助手聚焦到当前记录,助手按 - * 资料包 brightrule_policy_reading(src/ai-contexts)读这份制度。没有站内助手的环境里 - * 这个按钮不显示。 - */ -export const AskPolicyAction = defineAction({ - name: 'brightrule_policy_ask', - label: '问这份制度', - icon: 'message-circle-question', - objectName: 'brightrule_policy', - type: 'ask_ai', - locations: ['record'], -}); diff --git a/src/actions/index.ts b/src/actions/index.ts index 5c00d13..997cf96 100644 --- a/src/actions/index.ts +++ b/src/actions/index.ts @@ -4,4 +4,3 @@ // and a action file this index does not export is never loaded. export {}; export { DiagnosePolicyAction } from './diagnose-policy.action.js'; -export { AskPolicyAction } from './ask-policy.action.js'; diff --git a/src/ai-contexts/policy.ai-context.ts b/src/ai-contexts/policy.ai-context.ts index 982f836..d3539d1 100644 --- a/src/ai-contexts/policy.ai-context.ts +++ b/src/ai-contexts/policy.ai-context.ts @@ -1,9 +1,9 @@ import type { AiContext } from '@objectstack/spec/ai'; /** - * 「问这份制度」读的资料包(ADR-0160 context pack)。 + * 在制度页问 AI 时读的资料包(ADR-0160 context pack)。 * - * 员工在制度页点「问这份制度」,助手就钉住这份制度,第一轮先按这个资料包读: + * 员工在制度页点页头的「问 AI」,助手就钉住这份制度,第一轮先按这个资料包读: * 制度的目录字段、正文 body_md,以及挂在它下面的制度附件。全部以提问人的身份读, * 读不到的字段和附件不会带上,资料包本身不放开任何权限。 */ diff --git a/src/apps/main.app.ts b/src/apps/main.app.ts index 0b36ccb..6466374 100644 --- a/src/apps/main.app.ts +++ b/src/apps/main.app.ts @@ -41,7 +41,7 @@ const mainApp: UI.App = { icon: 'message-circle-question', params: { title: '有制度上的问题,直接问', - subtitle: 'AI 只依据你能看到的已发布制度作答,答复分「结论、依据、出处」,出处可以点开原文。看某一份制度时,点制度页的「问这份制度」。', + subtitle: 'AI 只依据你能看到的已发布制度作答,答复分「结论、依据、出处」,出处可以点开原文。看某一份制度时,点制度页页头的「问 AI」。', placeholder: '例如:出差住宿每晚最多能报多少?', suggestions: [ '出差住宿每晚最多能报多少?', diff --git a/src/knowledge/policy-clause.knowledge-source.ts b/src/knowledge/policy-clause.knowledge-source.ts index 26950ad..7a8f39c 100644 --- a/src/knowledge/policy-clause.knowledge-source.ts +++ b/src/knowledge/policy-clause.knowledge-source.ts @@ -17,6 +17,10 @@ import { KnowledgeSourceSchema, type KnowledgeSource } from '@objectstack/spec/a * served and the skill falls back to the catalog route. * - `clause_hash` lets a search group identical clauses that several units * carry (`groupBy`); `owning_unit` lets it scope by the asker's unit chain. + * - `retrieval.mode: 'vector'`: search ranks clauses by meaning alone, not the + * store's default (hybrid on pgvector and Turso). Read on every search, so + * changing it rebuilds nothing; a store that does not run the mode refuses + * the source rather than searching another way. * * Egress: the first build sends every clause's text to the embedding provider. */ @@ -30,5 +34,6 @@ export const PolicyClauseKnowledgeSource: KnowledgeSource = KnowledgeSourceSchem content: ['content'], metadataFields: ['policy', 'owning_unit', 'clause_hash', 'kind', 'title'], split: { strategy: 'whole' }, + retrieval: { mode: 'vector' }, }, }); diff --git a/src/pages/policy-reading.page.ts b/src/pages/policy-reading.page.ts index 6552d31..e193821 100644 --- a/src/pages/policy-reading.page.ts +++ b/src/pages/policy-reading.page.ts @@ -5,7 +5,7 @@ import { definePage } from '@objectstack/spec/ui'; * * 平台默认的记录页把字段和相关列表左右各占一半,正文挤在左栏一大串字段下面。 * 这里改成整宽、以读正文为主: - * - 标题栏(含「问这份制度」「编辑」等按钮)下面一行要紧信息:文号、所属单位、 + * - 标题栏(含「问 AI」「编辑」等按钮)下面一行要紧信息:文号、所属单位、 * 分类、层级、生效日期; * - 页签默认打开「正文」,正文占整宽、单栏; * - 附件、全部字段(制度信息)、下级制度、制度意见各在一个页签里。 diff --git a/src/skills/policy-inquiry.skill.ts b/src/skills/policy-inquiry.skill.ts index a3ed4cb..cf81855 100644 --- a/src/skills/policy-inquiry.skill.ts +++ b/src/skills/policy-inquiry.skill.ts @@ -68,7 +68,7 @@ export const PolicyInquirySkill = defineSkill({ ## 确定读哪份制度(按顺序) -1. **已经指定了制度**:员工点名了制度,或对话上下文给出了正在看的制度记录(brightrule_policy 的记录 id;员工点了「问这份制度」时,资料包「制度正文」已读出它的字段、正文和附件),就只读这一份。资料包已经读出的正文不用再读一遍。 +1. **已经指定了制度**:员工点名了制度,或对话上下文给出了正在看的制度记录(brightrule_policy 的记录 id;员工点了「问 AI」时,资料包「制度正文」已读出它的字段、正文和附件),就只读这一份。资料包已经读出的正文不用再读一遍。 - 给了记录 id:按上一节读这条制度,确认 status = "published"。 - 只给了名称:query_records 对象 brightrule_policy,条件 title 包含名称中的关键词,找到后再读正文;找到多份同名或相近的,按 display_name 列出来请员工确认。 - 这份制度回答不了时,先说明「本制度中未找到相关规定」,再说明你另外查了哪份制度,引用时写清是哪份。