diff --git a/.changeset/31865-rate-chatbot-answers.md b/.changeset/31865-rate-chatbot-answers.md new file mode 100644 index 00000000000..1aa018cbf0f --- /dev/null +++ b/.changeset/31865-rate-chatbot-answers.md @@ -0,0 +1,17 @@ +--- +'@object-ui/plugin-chatbot': patch +'@object-ui/i18n': patch +--- + +feat(plugin-chatbot): a member rates an assistant answer with thumbs up / down and an optional note + +Clause-②: yes +Metadata-protocol: none + +`` draws a thumbs up / thumbs down pair on each finished assistant answer. A thumb opens a short form with an optional note (up to 500 characters); a thumbs-down first shows "A thumbs-down shares this question and your note with your organization's administrators", and nothing is sent until the member presses Send. The answer's stored rating draws pressed, and the member can change or remove it. The control calls the AI service's rating routes, `GET` / `POST` / `DELETE {base}/conversations/:id/turns/:turnId/feedback` (`answerFeedbackApiBase`, default `/api/v1/ai`), through the host's authenticated `apiFetch` when a `SchemaRendererProvider` is mounted. + +The control is off unless the host passes `rateAnswers`, and it is never drawn on a `readOnly` transcript (such as another member's shared conversation), without a `conversationId`, while an answer streams, or on an answer with no turn. A turn stored as several assistant messages draws one control, on its last message. + +Each message now carries `turnId`, the turn the rating routes address: a live answer takes the id of the user message that started its turn (the `turnId` the chat transport already sends), and a restored message takes the `turnId` its history carried. A host passing restored `initialMessages` to `useObjectChat` hands each message's `turnId` in; a restored message without one gets no control, never a guessed id. + +`@object-ui/i18n` adds the `chatbot.answerFeedback.*` labels in every locale. diff --git a/.changeset/31889-save-chatbot-answers.md b/.changeset/31889-save-chatbot-answers.md new file mode 100644 index 00000000000..18d0bea2d7c --- /dev/null +++ b/.changeset/31889-save-chatbot-answers.md @@ -0,0 +1,17 @@ +--- +'@object-ui/plugin-chatbot': patch +'@object-ui/i18n': patch +--- + +feat(plugin-chatbot): a member saves an answer as a question, their own view, or a report or dashboard widget draft, and runs saved questions again + +Clause-②: yes +Metadata-protocol: none + +`` draws a Save button on each finished assistant answer whose turn ran an object query (a data tool answered a `source` block). It opens a row of actions under the answer: "Save question", "Save as my view", "Save as report draft" and "Add as dashboard widget draft". Each one names the answer's turn and the tool call whose query it keeps (the turn's last object query): "Save question" calls `POST {base}/saved-questions` with `conversationId`, `turnId` and `toolCallId`, and the other three call `POST {base}/conversations/:id/turns/:turnId/artifact` with `kind` `view`, `report` or `widget` (`answerSaveApiBase`, default `/api/v1/ai`). Nothing is published from the chat: the report and widget results are drafts, and the row says so. When the server refuses draft authoring to the member (`report_authoring_requires_manage_metadata`), the chat says why and no longer offers the two draft actions; any other refusal shows the server's message. + +With `saveAnswers`, the composer also opens a "Saved questions" side panel: the member's saved questions, read each time it opens, each one run again (`POST {base}/saved-questions/:id/run`, the fresh result drawn under it) or deleted (`DELETE {base}/saved-questions/:id`). + +The actions are off unless the host passes `saveAnswers`, and are never drawn on a `readOnly` transcript, without a `conversationId`, while an answer streams, on an answer with no turn, or on a turn without an object-query `source` (a dataset answer's `provenance` is not one). The Console's AI chat switches them on. + +`@object-ui/i18n` adds the `chatbot.answerSave.*` and `chatbot.savedQuestions.*` labels in every locale. diff --git a/.changeset/32644-client-ai-answer-follow-ups.md b/.changeset/32644-client-ai-answer-follow-ups.md new file mode 100644 index 00000000000..78a75043150 --- /dev/null +++ b/.changeset/32644-client-ai-answer-follow-ups.md @@ -0,0 +1,16 @@ +--- +'@objectstack/client': patch +--- + +feat(client): `ai.savedQuestions` and `ai.answers`, the SDK methods for the AI answer follow-up routes + +Clause-②: yes +Metadata-protocol: none + +The client now calls the eight routes `@objectstack/spec/api` declares in `ai-answer.zod.ts`, typed from those spec shapes only: + +- `ai.savedQuestions.list()`, `create(request)`, `delete(id)` and `run(id)`: `GET`/`POST /api/v1/ai/saved-questions`, `DELETE /api/v1/ai/saved-questions/:id` and `POST /api/v1/ai/saved-questions/:id/run`. +- `ai.answers.createArtifact(conversationId, turnId, request)`: `POST /api/v1/ai/conversations/:id/turns/:turnId/artifact`, answering a list view, a report draft or a one-widget dashboard draft, discriminated by `kind`. +- `ai.answers.getFeedback`, `setFeedback` and `deleteFeedback(conversationId, turnId, …)`: `GET`/`POST`/`DELETE /api/v1/ai/conversations/:id/turns/:turnId/feedback`. + +Each method resolves to the route's `data` payload; the two deletes resolve `undefined` on the route's 204. A refusal throws the usual transport error, with the route's code on `err.code` and the status on `err.httpStatus`. The request and response types are re-exported from `@objectstack/client`. The routes are served by the AI service; check `discovery.services` first, as for the rest of `ai.*`. diff --git a/.changeset/34217-packaged-rules-disabled.md b/.changeset/34217-packaged-rules-disabled.md new file mode 100644 index 00000000000..e5d31dc4c89 --- /dev/null +++ b/.changeset/34217-packaged-rules-disabled.md @@ -0,0 +1,10 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql): a disabled package's validation rule no longer stands as the packaged rule of the object it extends + +Clause-②: no +Metadata-protocol: none + +`SchemaRegistry.getPackagedObjectBase` built the packaged rule set from every code extender of the object, a disabled package included, while the served object withholds a disabled package's extension. Where an enabled extender and a later, disabled one both ship a rule of one name, the base carried the disabled rule while the served object carried the enabled one, so the enabled rule's `message` read as rewritten by the tenant: `/meta` served it in the source language under every other locale, and a refused write quoted it untranslated. The base now leaves a disabled package's extensions out of its rules as it already did for its fields and tabs, so the enabled rule's message is translated again. Nothing to change in your metadata. diff --git a/.changeset/34261-env-draft-layered-404.md b/.changeset/34261-env-draft-layered-404.md new file mode 100644 index 00000000000..130ca552f3e --- /dev/null +++ b/.changeset/34261-env-draft-layered-404.md @@ -0,0 +1,21 @@ +--- +'@objectstack/rest': patch +'@objectstack/runtime': patch +--- + +fix(rest,runtime): the draft and layered `_env` reads of a name only disabled packages hold answer their own 404 + +Clause-②: no +Metadata-protocol: none + +`GET /meta/:type/_env/:name` already answered `404` for a name that only disabled packages hold. Three spellings of the same read still answered `409 RESOURCE_CONFLICT` and named the disabled package: `?state=draft`, `?preview=draft` and `?layers=true`, for a caller who may read pending drafts. Each now answers what the bare by-name read answers, on both transports (`RestServer` and the runtime dispatcher), and names no package: + +- `?state=draft` (any case): `404 NO_DRAFT` +- `?preview=draft`: `404 RESOURCE_NOT_FOUND` +- `?layers=true`: `404 RESOURCE_NOT_FOUND` + +A package-less draft stored under such a name is the disabled holder's customization, so it is withheld too. Once the holder is enabled again, each read refuses `409` and names it, as before. + +The door judges the read the caller actually gets. For a draft read, both the plain read and the draft read must withhold the name. Sometimes an enabled package holds a stored draft of the name that the plain read does not see, and the bare draft read serves that draft to an admitted builder. In that case `_env` keeps the `409` and never serves the draft. The layered view is judged by the plain read, because its chain withholds every layer whenever the plain read withholds a disabled holder's item. + +FROM → TO for a client: a `409` on these three reads of a disabled-only name becomes a `404` (`NO_DRAFT` for `?state=draft`). Both are refusals, so code that already handles a missing item needs no change. diff --git a/.changeset/34452-same-name-bare-reads.md b/.changeset/34452-same-name-bare-reads.md new file mode 100644 index 00000000000..89d5735f4cc --- /dev/null +++ b/.changeset/34452-same-name-bare-reads.md @@ -0,0 +1,19 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/spec': patch +--- + +fix(metadata-protocol)!: the reads that name no package give one answer per name: the environment's doc entry first, and a disabled holder read as absent + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a caller that reads a shared name without naming a package, shipped as `patch`: no key an author writes changes (`Metadata-protocol: none`). Three reads that named no package answered by registration or save order, or disagreed with the registry's own read of the same name; each now gives one answer. Naming the package (`?package=ID`, or `packageId` in process) reads that package's item exactly as before. + +- **A doc the environment stores beside one enabled package's doc of the same name** (#34452, ruling 6942962369). FROM `GET /api/v1/meta/doc/NAME`, `/layers` and `/published` serving the package's doc while the registry and the metadata facade served the environment's own entry, TO every read that names no package serving the environment's entry, as it already did beside two or more holders. `?package=ID` still reads the package's doc. Known deviation, tracked in #38659: the plain read naming no package serves the entry under a holder's envelope (`_packageId` that holder, `_provenance: package`, lock `full`), as it already did beside two or more holders. +- **The in-process layered read of a doc two or more enabled packages hold, with no environment entry** (#34190). FROM the layered read naming no package serving the layers of the package registered last, TO a `409 RESOURCE_CONFLICT` rejection naming each holder in `refusal.candidates`, as the item read and every HTTP door already answered. +- **A package-less row beside a disabled package's row and enabled packages' rows of a name no enabled package ships** (#34440). FROM the plain read and the execution read following save order, `/published` serving the package-less row, `/layers` refusing with the disabled package among the candidates, and one save order answering 404 (every bare door answered 404 when the disabled package held the name in code alone beside two or more enabled packages' rows), TO the answer the reads give without the disabled holder: two or more enabled holders refused `409 RESOURCE_CONFLICT` naming exactly them in `details.candidates`, one enabled holder served, in every save order and after a restart. `?package=` of the disabled package still answers 404. + +The fix for a caller that relied on the old answer: name the package it means. `os migrate meta --from 18` lists both entries. diff --git a/.changeset/34770-i18n-skill-router.md b/.changeset/34770-i18n-skill-router.md new file mode 100644 index 00000000000..0252857a143 --- /dev/null +++ b/.changeset/34770-i18n-skill-router.md @@ -0,0 +1,22 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): the objectstack-i18n entry file becomes a router + +Clause-②: no +Metadata-protocol: none + +`skills/objectstack-i18n/SKILL.md` goes from 25.3 KB to 9.0 KB (504 lines to 160). It now holds five things: three first checks (read the stack's `i18n` block and the contract before writing a key; which of `defaultLocale`, `sourceLocale`, `supportedLocales` and `fallbackLocale` is which; verify with `os i18n check` and `os validate`), one type-checked bundle with the `translation` metadata item beside it, the key map as one path listing, seven traps, and a table that says where to go for the rest. No rule's teaching changes. This skill has no hand-written reference file, so no text moved: what left the entry was cut, and this entry says what now answers it. + +**What the entry keeps.** The key map lists, as paths, the groups under `objects.{object}` (`fields`, `_views`, `_actions`, `_sections`, `_tabs`, `_relatedLists`, `_milestones`, `_validations`) and the top-level groups the old entry listed, with their keys. It is not the whole contract: it stops above the leaf keys of `bulkActions.{def}`, of `params.{param}`, of a dataset member and of a report block's `description`, and it does not list the top-level `forms` group (the old entry did not either). The routing table sends a key or shape the map does not show to the contract. Six notes under it carry the placements a path cannot show: `inlineTitle` and `relatedListTitle` are keys of the child object; `_views.{view}.title` is a form's own heading and a section's override says `helpText` where the field says `help`; `columns` is a sibling of `fields` (with the one worked example the map keeps) and `preflight` has no `title`; `_relatedLists.{list}` is on the parent; a report block is keyed by its `name` and a `books` group by its `key`; a flow step is keyed under `approvals`, `screens` or `nodes`. The seven traps, each one a bundle that parses and ships and then translates nothing or the wrong text: an option key is the stored `value`, never the label; `t()` fills double braces only and there is no ICU MessageFormat; `os i18n extract` writes `objects` and `globalActions` only unless you pass `--no-objects-only`; coverage is not freshness, so `os i18n extract … --check` is the second gate; a generated module is an `objects` subtree that needs wrapping, and `withSourceFallback` needs the `--source-hashes` companion as its fourth argument; text the server writes is in the organization's language; an app-authored refusal has no `en` floor. + +**What left, and what answers it now.** + +- The condition on each key (which declaration a key needs before it is accepted) and the retired and misspelled keys (`o`, `app`, `nav`, `dashboard`, `_globalOptions`, `_meta`, `validationMessages`, `settings`, `confirmMessage`, `sourceLanguage`, `authoringLocale`, `authoringLanguage`): the contract, `node_modules/@objectstack/spec/src/system/translation.zod.ts`. Its shapes are strict, a key with a condition says it in its `.describe()` text, and a refused key is answered with the key to write. `os validate` reports a key that names nothing the metadata declares as `translation-target-unknown`, an error. +- The `i18n` property table, the naming-convention table and the file-layout table: the contract and the bundle example. +- The flags of `os i18n check` and `os i18n extract` beyond the ones a run needs (`--include-platform`, `--show-keys`, `--fill`, `--default-locale`, `--no-metadata-forms`) and `os lint --i18n-strict`: each command's `--help`. +- The `II18nService` method list: `@objectstack/spec/contracts`. The locale resolution order: https://objectstack.ai/docs/protocol/kernel/i18n-standard. The coverage and diff shapes: the contract (`TranslationCoverageResultSchema`, `TranslationDiffItemSchema`). The three `/api/v1/i18n` routes: https://objectstack.ai/docs/api/plugin-endpoints, which the entry does not link. +- The paragraph on platform-composed `userMessage` sentences, the list of shipped example bundles, and the sentence that validation, delete-restriction and permission-denial messages name fields in the request's language: cut. They describe what the platform does and ask nothing of a bundle author. + +**Anchors that no longer exist in `SKILL.md`.** Every section heading of the old file: `#translation-configuration`, `#stack-level-i18n-config`, `#authoring-translation-bundles-objects`, `#object-level-translation-structure`, `#naming-conventions`, `#file-organization-strategies`, `#authoring-at-runtime-the-translation-item`, `#message-interpolation`, `#simple-format-default`, `#no-icu-messageformat`, `#translation-coverage`, `#os-i18n-check`, `#os-i18n-extract---check--freshness-not-coverage`, `#diff--coverage-schemas`, `#integration-with-ii18nservice`, `#service-contract`, `#registration`, `#server-composed-user-text-usermessage`, `#translation-workflow-best-practices`, `#1-extract-skeletons-from-metadata`, `#2-register`, `#shipped-examples`, `#common-pitfalls`, `#-the-retired-o-shape`, `#verify-your-work`, `#references`, `#see-also`. The new ones are `#first-checks`, `#a-bundle`, `#key-map`, `#traps` and `#where-to-go`. No file in this repository linked an anchor of the old entry. diff --git a/.changeset/34770-platform-skill-router.md b/.changeset/34770-platform-skill-router.md new file mode 100644 index 00000000000..69350448939 --- /dev/null +++ b/.changeset/34770-platform-skill-router.md @@ -0,0 +1,20 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): the objectstack-platform entry file becomes a router + +Clause-②: no +Metadata-protocol: none + +`skills/objectstack-platform/SKILL.md` goes from 24.7 KB to 9.0 KB (421 lines to 105). It now holds three things: four first checks (the installed `@objectstack/spec` version, what the project already has, the contract, `os validate`), the traps that pass `os validate` and then fail at run time, and a table that says which file to open for the task at hand. No rule's teaching changes. Text moved, and this entry says where it went. The skill's files are 2.1 KB smaller together (107.5 KB to 105.5 KB). + +**What the entry keeps.** Five traps: no driver in `plugins:`, an installed package is customized from its paired `.custom` package, who owns the HTTP server (`createHonoApp` or `HonoServerPlugin`), `manifest.engines.protocol`, and `manifest.namespace`. Then the full list of `defineStack()` top-level keys with the rule that an undeclared key is refused, the `requires:` provider table with the three rules that bite most often, and `Seed Data` (the three import modes; a seed cannot create a person, `demoStaff` does). + +**What left, and where it is now.** + +- `references/bootstrap.md` now also holds `Strict Validation` (`#strict-validation`), the manifest notes the entry's two traps do not repeat (`#manifest`), `Project Structure Conventions`, what the `blank` template scaffolds (under `#scaffolding-command`), `Runtime Boot Sequence` (`#runtime-boot-sequence`), the `requires:` tokens that have no provider row and the remaining rules (`#requires-in-detail`), `onEnable`, `Customizing an installed package` in full (`#customizing-an-installed-package`), and `demoStaff` with its example (`#demo-accounts--demostaff-vs-devlogins`). +- `references/operations.md` now also holds `Driver Selection Guide` (`#driver-selection-guide`), when to construct `DriverPlugin` yourself (`#wiring-a-driver-yourself`), `HTTP Layer (Hono)` (`#http-layer-hono`), and the note that `os compile` writes `dist/objectstack.json`. +- Anchors that no longer exist in `SKILL.md`: `#definestack--the-core-configuration` (now `#definestack-keys`), `#full-configuration-reference`, `#strict-validation`, `#compile-artifact-and-runtime-metadata-boundary`, `#manifest-reference`, `#the-app--platform-boundary`, `#the-template`, `#project-structure-conventions`, `#naming-conventions`, `#driver-selection-guide`, `#wiring-a-driver--you-usually-do-not`, `#http-layer-hono`, `#usage-pattern-hono`, `#architecture`, `#runtime-boot-sequence`, `#onenable--where-an-app-binds-runtime-code`, `#demo-accounts--demostaff-vs-devlogins`, `#references`. `#requires--which-service-plugins-boot` and `#seed-data` still do. + +**Not carried over, because another file already says it.** The `App / Platform Boundary` section (objectstack-project owns that decision; `references/bootstrap.md#app-or-platform` keeps the two sentences it does not have), the naming-convention table (objectstack-data's naming rules), the annotated manifest example (every key is in `kernel/manifest.zod.ts`, which the entry's third check points at; the barrel example in `references/bootstrap.md` now shows `engines`), the Hono usage snippet, and the closing list of the other files (the routing table replaces it). In `references/plugin-development.md`, the `Plugin` interface block and the hook example are now one pointer each to `rules/plugin-lifecycle.md` and `references/plugin-hooks.md`, which carry the same text. diff --git a/.changeset/34770-upgrade-skill-router.md b/.changeset/34770-upgrade-skill-router.md new file mode 100644 index 00000000000..f9ecfa42edb --- /dev/null +++ b/.changeset/34770-upgrade-skill-router.md @@ -0,0 +1,23 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): the objectstack-upgrade entry file becomes a router + +Clause-②: no +Metadata-protocol: none + +`skills/objectstack-upgrade/SKILL.md` goes from 24.7 KB to 9.0 KB (481 lines to 159). It now holds five things: the boundary (the four "never" rules and one `conversionId` per commit), four first checks (the authored major, the `os validate` control, where the prescriptions ship, the skills re-install), the Quickstart command block, seven traps that each look finished and are not, and the rule for when you decide a residue item alone and when you ask the owner. A table at the end says which section of the reference file to open. No rule's teaching changes. Text moved, and this entry says where it went. The skill's two authored files are 0.3 KB smaller together (29.5 KB to 29.2 KB). + +**What the entry keeps.** The seven traps: `os migrate meta` rewrites no source file by default, so the printed edits are ported by hand, or `--write` is passed and the edits it only lists are ported, then the range is replayed; a green `validate` does not mean the chain has nothing left, so replay `--from --to --json` until `applied` is `[]` with no `replayedNothing`; stored `sys_metadata` rows are rewritten only at read and only while the release carries their conversions, so run the `--stored` pass before you leave it; data migrations are per-deployment gates the report carries as `pending`; code on a retired API can keep compiling while it reads `undefined`; prose that still teaches the old shape fails nothing; and the parse-gate probe is a plain data literal with no `define*` call. + +**What left, and where it is now.** `references/examples-upgrade.md` now holds the whole run in order, around the three blocks it already had (the worked R1, the report template, the v17-canonical shapes, all unchanged): + +- `0 · Preflight` (`#0--preflight`): the three sources of the FROM major, the `.upgrade/` workspace, the commands that re-install the skills. +- `1 · Mechanical layer` (`#1--mechanical-layer`): what a run does and prints, stored rows, data gates. +- `2 · Semantic residue` (`#2--semantic-residue`): where the prescriptions ship and how to harvest them, the residue classes, what each decide-or-ask condition looks like, the R2 and R3 searches. +- `3 · Acceptance` (`#3--acceptance`): typed, parse-gated, validate, the reverse check (`#reverse-check`) with its three outcomes, the stored-row assertion. +- `Failure modes` (`#failure-modes`) and the `--json` error codes. +- Anchors that no longer exist in `SKILL.md`: `#-the-boundary--read-this-before-the-first-command` (now `#-the-boundary`), `#0--preflight`, `#establish-the-from-major--do-not-guess-it`, `#make-the-work-reviewable-before-you-change-anything`, `#re-install-the-skills-from-the-moved-catalog`, `#1--mechanical-layer--invoke-the-chain`, `#what-os-migrate-meta-actually-does`, `#-the-one-fact-that-surprises-every-operator`, `#stored-rows-rehydration-replays-what-the-release-carries`, `#data-migrations-are-not-metadata-migrations`, `#2--semantic-residue--the-part-that-is-yours` and its `2.1` to `2.6` sections, `#3--acceptance--what-upgraded-means` and its `3.1` to `3.6` sections, `#reverse-check`, `#failure-modes`. `#quickstart`, `#decide-alone-or-ask` and `#cross-skill-routing` still do. + +**Not carried over, because something else already says it.** The list of `os migrate meta` forms (`os migrate meta --help` prints the same forms and describes every flag; the Quickstart keeps the ones a run needs), and two `Failure modes` rows. "Reports changes, but the files are unchanged": its symptom and cause are trap 1, and its fix (pass `--write`, or port the printed edits by hand, then replay) is kept as that trap's last sentence. "Findings that have nothing to do with retired keys" restated first check 2, the control. diff --git a/.changeset/34891-status-row-package.md b/.changeset/34891-status-row-package.md new file mode 100644 index 00000000000..aa00dec82f5 --- /dev/null +++ b/.changeset/34891-status-row-package.md @@ -0,0 +1,16 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-automation': patch +'@objectstack/runtime': patch +--- + +fix(automation): status rows of a flow name two packages hold carry their package, so the toggle answers the switched flow's stored state + +Clause-②: yes (widening) +Metadata-protocol: none + +`FlowRuntimeState` (`@objectstack/spec/contracts`) gains an optional `packageId`: the package of the engine slot the row reads (ADR-0150 D4, one slot per package and name), absent for a flow no package holds. `getFlowRuntimeStates()`, and so `GET /automation/_status`, now stamps it on every row of a package-held flow, so the two rows of a name two packages hold are told apart by `(packageId, name)`. + +`POST /automation/NAME/toggle` (and its namespaced address) on such a name now answers the stored state of the slot it switched, read back from that slot's own row. It used to echo the request whenever the name had two rows, so a flow republished `obsolete` while the switch awaited its durable write was answered `enabled: true` though it does not run. The request is still echoed by a service that does not implement `getFlowRuntimeStates`, by one whose reading holds no row of the switched flow, or, on a door serving no package's slot, when two or more rows carry the name; the composed runtime never reaches that last case, because the bare `toggleFlow` refuses a name two packages hold. + +A reader that means one package's flow of a shared name picks its row by both `packageId` and `name`; a row picked by `name` alone may be the other holder's. diff --git a/.changeset/35086-seed-replay-warn.md b/.changeset/35086-seed-replay-warn.md new file mode 100644 index 00000000000..cef69545cff --- /dev/null +++ b/.changeset/35086-seed-replay-warn.md @@ -0,0 +1,8 @@ +--- +"@objectstack/organizations": patch +--- + +Clause-②: no +Metadata-protocol: none + +A per-organization seed replay that refuses rows now logs at warn, naming the object, the first error and the organization id, instead of an info line. diff --git a/.changeset/35143-subflow-target-publish-gate.md b/.changeset/35143-subflow-target-publish-gate.md new file mode 100644 index 00000000000..1d515f4187e --- /dev/null +++ b/.changeset/35143-subflow-target-publish-gate.md @@ -0,0 +1,29 @@ +--- +'@objectstack/lint': minor +'@objectstack/metadata-protocol': minor +'@objectstack/spec': patch +--- + +fix(lint)!: the publish gate refuses a subflow or map step that calls a flow the deployment does not hold + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** accept-set narrowing, shipped as `minor`: an active publish of a flow whose `subflow` or `map` step names a flow that no part of the deployment holds was accepted before and is refused now (`422 INVALID_METADATA`, rule `flow-subflow-unknown`), with the fix named. The schema is unchanged, stored flows are not rewritten or refused at boot, and drafts are not gated. + +A `subflow` or `map` step runs the flow its `config.flowName` names. When the engine holds no flow of that name, the step fails on every run (`Flow 'X' not found`). `flow-subflow-unknown` reported this only as a CLI warning, because the publish gate judged one flow at a time and could not tell a call to another stored flow from a call to a missing one. + +- **The refusal.** On a flow publish the host now states the names of every flow the deployment holds: every installed package's flows (a disabled package's included), the stored flow rows in every state (a draft counts), the flows the same publish batch or package install carries, and every flow the automation engine holds (a flow registered straight into the engine has no metadata row). A call naming none of them, and not the written flow itself, is an `error` at the publish gate. The names are read only for a flow that calls another flow, and the stored ones in one read of the `name` column. +- **A package install.** An unmanaged install writes its flows one at a time and states the package's flow names on each, so a flow calling a sibling the package declares after it installs. A copy installed under another namespace renames its flows whose names carry the source prefix, but not the `config.flowName` that calls them, so its install is refused, and rolled back whole, unless the deployment holds the old name. +- **No verdict.** When the host cannot read one of those sources (no automation service, a failed store read, said once at `warn`), or the set is empty, the gate does not judge the call. +- **Not judged.** Whether the engine's package-scoped name resolution (ADR-0150 D3) lets the calling flow reach the called one: the set is the whole deployment, never narrowed to the written package's dependency closure. +- **The CLI.** `os validate` / `lint` / `compile` / `build` still report `flow-subflow-unknown` as a warning: the stack is one app, and another installed package may ship the called flow. +- **Exports.** `@objectstack/lint`: `validateFlowSubflowTargets` takes an optional second argument (`FlowSubflowTargetOptions`, `deploymentFlowNames`); `AuthoringRuleContext` gains `deploymentFlowNames`; `runRuntimeAuthoringRules` takes an optional `deploymentFlowNames`. `@objectstack/metadata-protocol`: `saveMetaItem`'s request gains an optional, server-only `copyPlanFlowNames` (the flows the same package install writes; set by the unmanaged install, forwarded by no HTTP door). All optional; an omitted value keeps the earlier behaviour. + +FROM → TO: + +- `{ type: 'subflow', config: { flowName: 'notfy_owner' } }` (no such flow) → `{ type: 'subflow', config: { flowName: 'notify_owner' } }` + +One-line fix: name a flow the deployment holds, or save the called flow first (a draft is enough) and publish the caller after it. diff --git a/.changeset/35266-gallery-template-gate.md b/.changeset/35266-gallery-template-gate.md new file mode 100644 index 00000000000..d9e16a9f469 --- /dev/null +++ b/.changeset/35266-gallery-template-gate.md @@ -0,0 +1,16 @@ +--- +'@objectstack/scenarios': patch +--- + +feat(scenarios): a gallery app exports only when it also installs as a trial copy, with its sample data, and answers there + +Clause-②: no +Metadata-protocol: none + +`gallery-refresh` now runs `run-scenarios --modes scratch,template --template-sample-data`. The new `--template-sample-data` flag makes template mode install the passing scratch build unmanaged with the card's seed rows as the package's sample data (the same rows the export writes into `source/src/sample-data.json`) and the install door's seed copy on (`seedSampleData: true`). Its Run half then seeds nothing itself: it reads the card's rows back from the copy, binds the copied rows to the persona users it creates afterwards (`owner_id`, a persona record's `user` field, a user-handle field), and asks every question and operation over those rows. A card row the copy does not hold is refused by name, so every turn that reads it is not measured. The record keeps the door's report (`seed.copied`) and the bound fields (`seed.bound`), `template.seedSampleData` says the install asked for the copy, and the scorecard's Seed cell reads `N/M copied by the install`. Without the flag, template mode seeds as before. The flag is refused when `--modes` leaves template out. + +The exporter's pass rule now owes the template mode run that way, beside scratch mode's six halves. A record without it, a template mode run without the sample data copied, a refused unmanaged install (the door's status, code and message are the reason) or a failed template half keeps the card out of the gallery. The reason shows in the refresh PR body under `Refused`. + +The exported `source/` now installs as the customer's own editable copy. `objectstack.config.ts`'s `manifest` gains `installModes: ['unmanaged']` and `objectstack.manifest.json` gains `solutionType: 'template'`. A build that carries code `plugins` is refused, because `defineStack` refuses that install mode beside code. Install modes the build already declares with `'unmanaged'` are kept as they are. + +`export-gallery --check` gains the `app-install-modes` finding: an app whose `source/objectstack.config.ts` `manifest:` literal, read as written, declares no `installModes` containing `'unmanaged'`. A gallery tree exported before this release carries that finding until the next refresh rewrites it. diff --git a/.changeset/35529-spec-row-held-base-texts.md b/.changeset/35529-spec-row-held-base-texts.md new file mode 100644 index 00000000000..cc810c4e760 --- /dev/null +++ b/.changeset/35529-spec-row-held-base-texts.md @@ -0,0 +1,13 @@ +--- +'@objectstack/spec': patch +'@objectstack/metadata-protocol': patch +--- + +docs(spec): the row-held-base exception in the request texts names its whole cell + +Clause-②: no +Metadata-protocol: none + +The `packageId` descriptions of the save, draft save, per-item publish, delete and history/diff/rollback requests (`HISTORY_PACKAGE_SELECTOR_DESCRIPTION`) state when a request naming no package follows the row-held base. They now name the two conditions the server already applies and the earlier text left out: the exception holds only for a name no package ships in code (a shipped name is its shipper's, and such a request answers as before), and the base may be declared by one or more packages, not exactly one. The delete text no longer assumes a single dependent: after the base's row is removed, and where the base holds no other member of the name or the member is the canonical one, the next request naming no package is judged over the dependents' rows alone, so one dependent's row is served next and a second delete removes it, while two or more are judged by the same rule. At a named non-canonical member while the base still holds another member, the read naming no package still takes the base's address and answers `404` until the base holds a row there again, and a second delete naming no package still removes a lone dependent's row. Description text only; no schema shape, key, accepted value or server answer moves. + +In `@objectstack/metadata-protocol`, the doc comments of the publish, rollback and delete request types, which ship in the built declarations, now state the same row-held-base exception beside the two-package `409`; comment text only. diff --git a/.changeset/36051-explain-field-channels.md b/.changeset/36051-explain-field-channels.md new file mode 100644 index 00000000000..511274d7383 --- /dev/null +++ b/.changeset/36051-explain-field-channels.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': minor +'@objectstack/plugin-security': patch +--- + +feat(security): the access explanation names the channel that opened each field + +Clause-②: yes +Metadata-protocol: added + +The `fls` layer of the access explanation (`/api/v1/security/explain`, `ISecurityService.explain`) gains an optional `fieldChannels` list. For each field of the object it names the channel that cast the winning read vote and the one that cast the winning edit vote, with the permission sets that cast it: + +- `own_row`: a set's own field row opens the field, and no held set's row closes it; +- `other_set_row`: a set's row opens it while another held set's row closes it, so that set re-opens a field the other hides; +- `view_all_fields`: no row opens it and a set's `viewAllFields` bit casts the read vote (read only, never an edit channel); +- `default`: no held set names the field, so it follows the object grant. + +View All and Modify All are not channels: they cast no field vote. `read` / `edit` is present only where the field merge kept that vote open: a field a row hides carries no `read` entry, a field a row locks carries no `edit` entry, a capability gate or the delegator closes the axis it closes, a field served only through its masking rule carries no `read` entry, and a computed field the caller is not served whole carries no `edit` entry (the write gate refuses a payload naming it). A write-only row on a stored field reports an `edit` channel with no `read`. Whether the object grant allows the operation is the `object_crud` layer's answer. When a field one held set hides is readable through another set, the layer's `detail` names the field and that set. + +The explanation is read-only: enforcement is unchanged. Existing consumers keep parsing, because the key is optional. `PermissionEvaluator.fieldVoteSources(object, sets)` (`@objectstack/plugin-security`) is the vote source the explanation reads: the sets behind each field vote, from the same vote functions the field merge uses. diff --git a/.changeset/36057-scenarios-delete-agent-confirmation-names.md b/.changeset/36057-scenarios-delete-agent-confirmation-names.md new file mode 100644 index 00000000000..3507aad8bd1 --- /dev/null +++ b/.changeset/36057-scenarios-delete-agent-confirmation-names.md @@ -0,0 +1,24 @@ +--- +'@objectstack/scenarios': patch +--- + +refactor(scenarios)!: delete the deprecated agent-confirmation grading names; a `pending_confirmation` operation is graded strictly, with no opt-in + +Clause-②: no (narrowing) — removes published exports of @objectstack/scenarios +Metadata-protocol: none + + + +**BREAKING** for a TypeScript caller of `@objectstack/scenarios/score`, `@objectstack/scenarios/score/full` or `@objectstack/scenarios/runner` that still read the retired relaxed grade, shipped as `patch`: the change is not to the metadata protocol (`Metadata-protocol: none`). Grading does not change: the relaxed grade was already off by default, so every `pending_confirmation` operation the runner grades, and every `gradeCardOperation` call, grades exactly as before (the agent asks first and writes nothing; the person's confirmation turn grades the write after it). + +The scorer carried a temporary rule that also met a `pending_confirmation` operation when the agent applied it itself through a confirm-gated business action, on an ask naming the target. Real human confirmation is on the platform, so the rule was switched off and its names deprecated; this release deletes them, and with them the only way a direct `gradeOperation` call could opt back in. + +- FROM `AGENT_CONFIRMATION_MEETS_PENDING` TO nothing: the switch is gone and grading is strict. Delete the read. +- FROM `GradeOperationOptions.acceptAgentConfirmation` and `GradeOperationOptions.agentConfirmation` TO nothing: `gradeOperation(declared, observation, { probed, asOf })` takes neither. Drop both options; a grade that passed them now grades strictly, as the runner always did. +- FROM `confirmedByAgent` TO `askedFirst`: `OperationGrade.confirmation` is `'asked first'` on a passing `pending_confirmation` grade, and absent otherwise. Compare against `askedFirst` only. +- FROM `AgentConfirmedObservation` and `OperationObservation.agentConfirmed` TO nothing: `observeOperation` no longer reads the agent's applied write for the rule. Stop setting or reading the field. +- FROM `AgentConfirmationRule` TO `Parameters[0]` for its `write` member (the operation's `kind`, `object`, `target` and `values`, which `gradeConfirmedWrite` takes as before) and `AskNaming` from `askNamesTarget(card, operationId)` for its `ask` member, both unchanged. +- FROM `actionGatesOf` (`./runner`) and `ObserveInput.actionGates` TO nothing: the runner no longer reads the build's confirmation gate per action for the grade. Drop the call and the field. +- FROM `ConfirmationTally.confirmedByAgent` TO nothing: the tally is `{ askedFirst }`, and the scorecard reads `irreversible operations: N asked first` with no `· M confirmed by the agent` count. + +Unchanged: `askNamesTarget`, `AskNaming`, `askedFirst`, `OperationGrade.confirmation`, `gradeConfirmedWrite` and its checks. diff --git a/.changeset/36274-verify-artifact-metadata-door.md b/.changeset/36274-verify-artifact-metadata-door.md new file mode 100644 index 00000000000..d10887a1f0e --- /dev/null +++ b/.changeset/36274-verify-artifact-metadata-door.md @@ -0,0 +1,17 @@ +--- +'@objectstack/verify': patch +--- + +fix(verify): a `bootStack` boot of a compiled artifact fills its `metadata` slot the way `os dev` does, so it seeds the way `os dev` seeds + +Clause-②: no +Metadata-protocol: none + +`bootStack` could pass a seed that `os dev` stored wrongly. The case measured: a module package adds a lookup to the app package's object through `objectExtensions`, and seeds it by the target's natural key. On `os dev` the metadata service holds each object as its own package wrote it, because the `MetadataPlugin` that loads the artifact starts before the app seeds. Under `bootStack` that plugin started after the app's seed, or was not composed at all, so the seed read the registry's copy with the extension folded in. With the seed loader as it was before it learned to read the engine's schema first, `os dev` stored the raw key and `bootStack` stored the target's id, so a `bootStack` test could not catch the defect. + +Now: + +- `bootStack(config, { artifact })` composes a `MetadataPlugin` that loads the same artifact, ahead of the app, and the app leaves the four security collections (`positions`, `permissions`, `capabilities`, `sharingRules`) to it, as `os dev` declares it. +- A `MetadataPlugin` passed in `extraPlugins` is registered in the `metadata` slot, ahead of the app, instead of after it. The harness composes no `MetadataPlugin` of its own beside it, as before. + +A source boot (no `artifact`, no `MetadataPlugin` in `extraPlugins`) is unchanged. diff --git a/.changeset/36496-selection-bulk-actions.md b/.changeset/36496-selection-bulk-actions.md new file mode 100644 index 00000000000..6ba7069fec1 --- /dev/null +++ b/.changeset/36496-selection-bulk-actions.md @@ -0,0 +1,30 @@ +--- +'@objectstack/spec': minor +'@objectstack/lint': minor +'@objectstack/platform-objects': patch +'@object-ui/types': minor +'@object-ui/plugin-grid': minor +'@object-ui/plugin-list': minor +'@object-ui/plugin-view': patch +'@object-ui/plugin-detail': patch +'@object-ui/components': patch +'@object-ui/i18n': patch +--- + +feat(spec)!: actions that act on many records are placed at `selection`; the object's `actionLayout.selection` orders the selection bar, and a list view's `bulkActions` is retired + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for metadata that lists bulk actions on a list view: + +- **`view.list.bulkActions` / `object.listViews.*.bulkActions` is refused at parse** (and authoring it is a `tsc` error). FROM `list: { bulkActions: ['mark_done', 'recalc'] }` TO `locations: [..., 'selection']` on the actions `mark_done` and `recalc`; when the order the lists gave is not the default (by `order`, then declaration order), also `actionLayout: { selection: { pinned: [...], more: [...] } }` on the object. Fix: run `os migrate meta --from 18` to list the edits; `--write` applies the ones it can prove (strip the key, add `'selection'`, write the arm), and hands back as a TODO an object whose lists disagree on order or need an arm on an object the stack does not declare. A list that names `delete` (the grid's built-in bulk Delete) keeps its view's Delete: on a view with authored `bulkActionDefs`, which switch the built-in Delete off, the conversion adds a `{ name: 'delete', operation: 'delete' }` def. +- **Multi-select now shows the same actions on every grid view of an object**: every action placed at `selection`, in the arm's order. A view's own `bulkActionDefs` lead the bar while the object sets no `actionLayout.selection`; with the arm set only its `pinned` names are buttons, and the defs lead the bar's 「More」 (an authored def claims its name). Where the conversion writes the arm, a view's defs move from the bar's buttons to its 「More」. A view that listed none of them now draws them too. The built-in bulk Delete follows the object's delete permission, not a view's list: a grid draws it wherever the object allows a delete, on every view with no `bulkActionDefs`, and a view with authored defs draws it only through a `{ name: 'delete', operation: 'delete' }` def; `actionLayout.selection.pinned: []` moves it, and every other action, into the bar's 「More」. **This is a change** (maintainer ruling 7268555255, accept and declare): a view whose list named actions but not `delete`, with no defs, used to hide the built-in Delete and now draws it for anyone the object lets delete. Measured: `showcase_field_zoo`'s `default` and `gated_columns` views (administrators only), and in HotCRM `crm_lead` `all_leads` and `crm_contact` `all_contacts` (Sales Manager and System Administrator). `os migrate meta --from 18` names each such view in a notice. +- **`@object-ui/types` `ListViewSchema.bulkActions` is `never`**, and the `list-view` block's `bulkActions` input is removed. The `object-grid` block's own `bulkActions` / `batchActions` props are unchanged. +- **A `record:quick_actions` bar's own `location` does not take `selection`.** The bar accepts the same set as before this change (`record_page`, `record_row`, `record_related`, `record_section`, `list`); `location: 'selection'` is refused at parse with a prescription naming those single places, because the selection bar belongs to the grid. Studio's location dropdown and the published SDUI manifest offer the same set. +- **An action written on a page component does not take `selection` either.** `action:button` / `action:icon` `locations`, an `action:group` member's `locations` and the group's own `location` filter (`PageComponentActionLocationSchema`) accept every action location but `selection`, refused at parse with a prescription naming the places they take: such an action runs once, with no selection. The `action:group` registration in the SDUI manifest offers the same set. +- **`action-dispatch-contract-mismatch`** now judges an action placed at `selection` (one dispatch per selected record) against its declared `execution`; an action placed at `selection` that declares `execution: 'aggregate'` is refused, with the fix "move it from `selection` to an aggregate `bulkActionDefs` entry". + +The retirement kit: the tombstone's prescription (parse and `tsc`), the protocol-19 conversion `view-bulk-actions-to-action-selection`, the `RETIRED_KEYS_BY_MAJOR` entries `ui/ListView:bulkActions` and `ui/ObjectListView:bulkActions`, and the semantic entry `view-bulk-actions-declared-on-the-action`. A stored `view` row arrives without its object's actions, so the conversion leaves it as stored and reports a TODO; sources and package artifacts that carry the actions beside the views are rewritten. diff --git a/.changeset/36548-non-pair-custom-arrangement-refused.md b/.changeset/36548-non-pair-custom-arrangement-refused.md new file mode 100644 index 00000000000..b124335e56d --- /dev/null +++ b/.changeset/36548-non-pair-custom-arrangement-refused.md @@ -0,0 +1,27 @@ +--- +'@objectstack/metadata-protocol': minor +'@objectstack/cloud-connection': minor +'@objectstack/spec': patch +--- + +fix(metadata-protocol)!: a `.custom` package that is not the object's pair is refused when it writes the object's arrangement, at save and at install + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** accept-set narrowing, shipped as `minor`, inside the 19 prerelease window: `fieldGroups`, `relatedLists` and `actionLayout` on an object extension exist only in `19.0.0-next.*`, so no stable release admits what is refused here. The schema is unchanged and no stored row is rewritten or refused at boot. + +ADR-0146 D10 gives an extended object's whole arrangement to its paired `.custom` package. The registry merge already served only that pair; the doors judged the writer by its `.custom` suffix alone, so a `.custom` package that is not the object's pair was saved and installed, and then never applied (one boot-log line). The maintainer's ruling: 「保存和安装都拒绝」. + +- **Refused.** The save, publish, restore and draft-promotion doors, and so a package duplicate, answer `400 VALIDATION_ERROR`; the marketplace install answers `422 VALIDATION_ERROR` with nothing installed or written. One issue per key; the first sentence names the object's pair (`pairsOf` of the object's owner, the lookup the merge serves by), or says the object has none. No error code is minted. +- **Still admitted.** The object's App pair; a per-package pair an earlier version created, on its own package's objects, while it is installed. At install the artifact is read first and the registry second, so a pair the same act delivers counts as installed, and a target whose owner neither knows is not judged by role. +- **Not judged (unchanged).** `os validate` / `os build` (they cannot read the installed packages; the suffix rule still applies), a code-defined stack booted without them, and a stack that names no package id: the merge skips the key and the boot log names it. Boot never refuses. +- **Exports.** `@objectstack/metadata-protocol`: `ExtensionArrangementSubject` gains an optional `pairsOf(object)`, and `ObjectExtensionRegistry` an optional `getPackage(id)`. Omitted, the judge keeps the suffix rule. + +FROM → TO: + +- `PUT /api/v1/meta/object_extension/crm_account?package=partner.custom` with `{ extend: 'crm_account', fieldGroups: [...] }`, where `crm_account` belongs to HotCRM (saved, never applied) → the same body under `?package=hotcrm.custom`, the object's pair. + +One-line fix: move the key into the package the refusal names, or remove it and place what the package brings with `place`. diff --git a/.changeset/36987-auth-updateuser-returns-void.md b/.changeset/36987-auth-updateuser-returns-void.md new file mode 100644 index 00000000000..5901cd43445 --- /dev/null +++ b/.changeset/36987-auth-updateuser-returns-void.md @@ -0,0 +1,18 @@ +--- +'@object-ui/auth': patch +--- + +fix(auth)!: `createAuthClient().updateUser` declares `Promise`, because the server answers a receipt, not the user + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a typed caller and for a host that implements `AuthClient` itself, shipped as `patch`: the change is not to the metadata protocol (`Metadata-protocol: none`). Nothing that worked at runtime breaks for a caller of `createAuthClient()`: the value it now drops was never a user. + +The published typing narrows. `AuthClient.updateUser` was declared to return the updated user, but better-auth's `POST /update-user` answers `{ status: true }`, and the client passed that answer on as if it were a user. A caller that trusted the type read a user with no `id`, `name` or `email`. + +- FROM `AuthClient.updateUser` declared to resolve the updated user TO `AuthClient.updateUser: (data: Partial) => Promise`, which resolves nothing (it was `(data: Partial) => Promise`). At runtime `createAuthClient().updateUser` resolves with `undefined` instead of the receipt. A refusal still rejects, as before. +- **A caller that read the result** (`(await client.updateUser(data)).name`) no longer compiles. It read `undefined` at runtime. Read the stored fields with `getSession()` after the write. `useAuth().updateUser` already resolved with nothing and keeps the session user's identity, so React callers see no change. +- **A host that builds its own `AuthClient` and passes it as `AuthProviderOptions.client`**, with an `updateUser` that returns the user (`async (data): Promise => …`), no longer assigns to the interface. Return nothing from it, or annotate it `Promise`. `AuthProvider` never read that value. diff --git a/.changeset/37087-console-reads-form-items.md b/.changeset/37087-console-reads-form-items.md new file mode 100644 index 00000000000..8bbd154cbaa --- /dev/null +++ b/.changeset/37087-console-reads-form-items.md @@ -0,0 +1,15 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +'@object-ui/i18n': patch +--- + +feat(console): the console reads and edits forms as `form` items (objectstack#37087, ADR-0159) + +- **Setup → Public forms** lists and switches `form` items: the list is the `form` read, a switch saves the `form` item (its body with `sharing.enabled` set, without the `data` an old-shape form is served with), and "Restore package original" resets the `form` override. What the page shows is unchanged: every public form, on and off, its address and preview; a form its installed app ships switched off reads as off. A form whose app's own document cannot be read now offers no switch. +- **Studio's form editor**: the public form designer is the `form` type's editor (`EditPage` and `CreatePage`), with list columns for name, label, object, public address and status. It reads and writes the `form` item, whose body is at the top level, and has no switch: every save and publish writes `sharing.enabled` and `sharing.allowAnonymous` as they are stored at that moment, so a publish never opens a form Setup switched off. A form an installed app ships is saved as a declared override in the app's customization package. When the server refuses a save or publish because another form already uses the address, the editor says the address is taken, not that a draft is pending. The `form` type stays out of Studio's menu for now. +- **The console's own form page** (the signed-in one an action of type `form` opens) reads `GET /api/v1/meta/form/NAME`. The anonymous form route is unchanged. +- New `engine.studio.publicForms.*` and `engine.list.col.publicAddress` / `engine.list.col.publicState` strings in `./namespaces/studio` (en, zh). + +Clause-②: yes +Metadata-protocol: none diff --git a/.changeset/37087-forms-in-studio-menu-developer-page-retired.md b/.changeset/37087-forms-in-studio-menu-developer-page-retired.md new file mode 100644 index 00000000000..d0664c41af8 --- /dev/null +++ b/.changeset/37087-forms-in-studio-menu-developer-page-retired.md @@ -0,0 +1,29 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +'@object-ui/i18n': patch +'@objectstack/platform-objects': patch +--- + +feat(studio)!: forms are listed in Studio's menu, and the console's Developer → Public Forms page is retired (objectstack#37087, ADR-0159) + +Clause-②: yes (narrowing) — released translation keys, a Studio navigation entry and a console page are removed (listed below); two `publicFormsSetup` keys are added in every locale +Metadata-protocol: none + + + +**Forms in Studio's menu.** `form` is a metadata type of its own (ADR-0159), and Studio now lists it: under UI, in the common tier, after Reports. A package's menu always shows the row, whether the package holds a form or not, and the type directory lists it too. The row opens the package's list of forms, and a form opens in Studio's form editor. ADR-0084's type-to-group table gains the `form` row. + +**Developer → Public Forms is retired.** The console page that listed public forms and edited each one in a dialog read and wrote forms as views. A public form is a `form` item now: it is designed in Studio's form editor, and its public link is switched on or off in Setup → Public forms. Studio's Developer group no longer shows the entry. Both addresses of the page, `/apps//developer/public-forms` and `/apps//component/developer/public-forms`, redirect to Studio's list of forms, so a bookmark still lands somewhere useful. Setup's Public Forms entry is unchanged. + +**Setup names both forms when an address is taken.** Switching a public form on while another form holds its address is refused. The message now names the form that holds the address beside the form being switched on, so the administrator knows which two forms to tell apart. When the other form cannot be read, the message says another form holds the address. + +**BREAKING**: released keys and one navigation entry are removed. No code in the platform reads them any more. + +- `@object-ui/i18n`, `./namespaces/developer`, every locale: the 47 keys under `console.developer.publicForms` (shipped since 18.2.0). The retired page was their only reader. +- `@objectstack/platform-objects`: the Studio app's navigation entry `nav_public_forms` (component `developer:public-forms`) and its label key `apps.studio.navigation.nav_public_forms.label` in every locale. Setup's entry of the same id, `apps.setup.navigation.nav_public_forms`, stays. +- `@object-ui/console`: the `PublicFormsPage` module. The component key `developer:public-forms` stays registered, as the redirect above. + +If a deployment overrides one of the removed keys (in its own i18next resources), that override no longer applies: nothing asks for the key. Remove the override. A project's translation bundle could never name `apps.studio.navigation.nav_public_forms`: the Studio app is the platform's, and `translation-target-unknown` already refused a key under an app the project does not define. A `translation` item saved in an environment, in Studio or through the metadata API, is not checked against navigation: one that names the removed key still saves and publishes, and translates nothing. Delete the key from such an item. + +New keys, in every locale of `@object-ui/i18n`: `publicFormsSetup.refusalAddressTaken` and `publicFormsSetup.refusalAddressTakenUnknown`. diff --git a/.changeset/37111-stored-forms-apply.md b/.changeset/37111-stored-forms-apply.md new file mode 100644 index 00000000000..05fe18ccb4f --- /dev/null +++ b/.changeset/37111-stored-forms-apply.md @@ -0,0 +1,15 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/cli': patch +--- + +feat(metadata-protocol): the stored-form ceremony's write half, the `--apply` the next major's upgrade command runs (ADR-0159 D7) + +Clause-②: yes (widening) +Metadata-protocol: none + +`applyStoredFormsOf(protocol, { actor })` runs the census `os migrate stored-forms` prints and acts on it, all or nothing with the switch: when the precheck counts any row, it writes nothing and every stored row stays byte-equal. Otherwise it ensures the `.custom` pairs the moves land in (they stay if the run fails; an empty pair changes no answer and the next run reuses it), then, in one transaction, writes each form that is kept with a carried withdrawal or moved as a `form` row at its destination, with its body as stored (a folded row's withdrawal switches the kept form off, its link kept; a declared override is written as its pair's own row), reads each one back, and only then deletes or re-saves the old rows: a view item row is deleted, a stored container is re-saved without the forms that left it (its lists and the forms it keeps byte-equal), and a container left with nothing is deleted. Internal record forms are removed the same way, with their bodies in the result. Forms left in place and drafts are not touched; a second run moves nothing. On a database whose default driver cannot roll a transaction back, a run that would write or take a row is refused before anything is written, naming the driver and what to do (run against a database whose driver supports transactions, or stay on the current release). It is exported for the major's upgrade command only; `os migrate stored-forms` stays read-only. + +The census gains three readings: a withdrawal in a `view` row a `form` row outranks at its place, and one in a second pair's declared override, are read today, so the fold does not name the form newly closed; a row bound to a package that ships no form of the name moves into the pair as its own item where the base records no version (that item declares no `basedOn`); and where no pair id can be derived from a base, the refusal names why in words. Two more keep the census and `--apply` in step: a move, or a kept row that carries a withdrawal, whose destination row the store seals (a managed package ships the form's name as a `form` item, and the destination is not a declared override) holds the upgrade, naming that package, instead of failing the run; and a form no door serves today is left in place by the upgrade, whatever package its row is bound to (`served_by_no_door`, a new member of the exported `StoredFormLeftReason`), which `os migrate stored-forms` prints; such a form does not hold the upgrade at the pair door or at a sealed destination either. On a database that cannot roll back, `os migrate stored-forms` says the upgrade's run will be refused (`runRefused` in `--json`). + +The operations page `content/docs/deployment/stored-forms-upgrade.mdx` says what the upgrade command writes. diff --git a/.changeset/37111-stored-forms-census.md b/.changeset/37111-stored-forms-census.md new file mode 100644 index 00000000000..4f80a2ae4e7 --- /dev/null +++ b/.changeset/37111-stored-forms-census.md @@ -0,0 +1,15 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/cli': patch +--- + +feat(cli): `os migrate stored-forms`, the read-only census and precheck of the stored-form ceremony (ADR-0159 D7) + +Clause-②: yes +Metadata-protocol: none + +The next protocol major stops reading the three old shapes of a form (a view container's `form`, a `formViews` entry, a `viewKind: 'form'` item). Its upgrade command moves the stored rows that still hold one, in the same run that switches to the major, all or nothing. `os migrate stored-forms` shows that outcome before the upgrade and writes nothing: for each form name at each package that can serve it, whether the row is kept, moved (into the base's paired `.custom` package as a declared override, into a writable package's own form row, or into the environment), folded into the served row, removed as an internal record form, or left in place; and whether the upgrade can switch, naming each row that holds it (its pair cannot be ensured, its form content cannot be read, or one slot of a paired `.custom` package is claimed by more than one move) with the action for its cause. A row bound to a read-only package that ships no form of its name moves into that package's paired `.custom` package as a form of its own. Old-shape drafts are listed: they are neither moved nor deleted, and cannot be published after the upgrade. A row read at several packages is named at each, and is removed only where it is an internal record form at every one of them; read at two packages of one App that would both move it, it holds the upgrade, since the App's `.custom` package holds one row of a form's name (as does a row that package already holds of the name, beside a row planned into it); read at several packages, of one App or several, that would not all move it or all remove it, it holds the upgrade at each of them; a row with a public link behind an internal form left in place holds the upgrade where another package would move it, and neither row is folded, moved or removed at any package (a plan that would do so holds); and a row that holds is folded into no other row. A withdrawal a folded row carries that no layer reads today is named newly closed. + +`listStoredFormsOf(protocol)` answers the census over a protocol instance; it and its types are exported (`StoredFormCensus` and the shapes it names). The start-up message for a stored view whose form content cannot be read now names the command. `orderedFormRowsAt` is the served-row order the effective `form` read already used, now read by the census too; the read serves what it served. + +The operations page is `content/docs/deployment/stored-forms-upgrade.mdx`. diff --git a/.changeset/37375-stored-view-all-fields-review-list.md b/.changeset/37375-stored-view-all-fields-review-list.md new file mode 100644 index 00000000000..13b936d0585 --- /dev/null +++ b/.changeset/37375-stored-view-all-fields-review-list.md @@ -0,0 +1,27 @@ +--- +'@objectstack/cli': patch +'@objectstack/metadata-protocol': patch +'@objectstack/spec': patch +--- + +feat(cli): `os migrate meta --stored` lists the stored permission sets whose View All / Modify All no longer read fields in 19 + +Clause-②: yes (widening) +Metadata-protocol: none + +From protocol 19, View All (`viewAllRecords`) and Modify All (`modifyAllRecords`) widen records only and cast no field vote, and a permission set stored in a deployment (`sys_metadata`, for example saved in Studio) is read with that meaning and never rewritten on upgrade. The upgrade asks for a one-step check of which stored sets are affected; `os migrate meta --stored` now prints it. + +On a preview and an `--apply` run alike, the command lists every stored permission set's `objects` entry, the `'*'` entry included, that carries `viewAllRecords: true` or `modifyAllRecords: true` and no `viewAllFields`, one line per entry with the set, its scope and the bits: + +```text +◆ 2 object entry(ies) in 1 stored permission set row(s) hold View All or Modify All and no `viewAllFields` — since protocol 19 they read no field another set hides; listed for review, never rewritten: + • permission/ops_auditor [env-wide] — objects entry 'ops_ticket' (viewAllRecords) + • permission/ops_auditor [env-wide] — objects entry '*' (viewAllRecords, modifyAllRecords) +``` + +The fix, where the set's holders should still read every field of that object: add `viewAllFields: true` to the entry through the metadata API (Studio's permission matrix has no control for it). Beside Modify All the set's own `readable: false` rows now bind and no edit is restored; grant an edit with an explicit `editable: true` field row. Declaring `viewAllFields` either way, `true` or `false`, takes the entry off the list. + +The list is read-only: it writes nothing, moves no count and does not change the exit code or the "already on protocol" verdict. `--type` narrows it like the rest of the report. It uses the same predicate as the source conversion `permission-view-all-fields-beside-record-bypass` (`os migrate meta --from 18`), so it names exactly the entries that conversion rewrites in a source. + +- `@objectstack/metadata-protocol`: `StoredMigrationReport` gains `viewAllFieldsReview` (exported type `StoredViewAllFieldsReview`: `id`, `name`, `organizationId`, `packageId`, `state`, `object`, `bits`), and `formatStoredMigrationReport` prints it. `os migrate meta --stored --json` carries the same key, as an empty list on a database with no `sys_metadata` table yet, and so do the `POST /meta/_migrate-stored` response payload and `client.meta.migrateStored()`, which return the same report. +- `@objectstack/spec`: the upgrade text of the protocol-19 semantic entry `permission-view-all-modify-all-cast-no-field-vote` no longer says that no command lists the affected stored sets; its description and its one-step check now name `os migrate meta --stored`. Text only: no schema, key or behaviour changes. diff --git a/.changeset/37405-field-write-lock-adr-skill.md b/.changeset/37405-field-write-lock-adr-skill.md new file mode 100644 index 00000000000..38872b90a95 --- /dev/null +++ b/.changeset/37405-field-write-lock-adr-skill.md @@ -0,0 +1,15 @@ +--- +'@objectstack/spec': patch +'@objectstack/skills': patch +--- + +docs(skills,spec): the `objectstack-data` skill teaches which of the four field locks to use, and the `uiReadonly` + `readonly` refusal names ADR-0163 + +Clause-②: no +Metadata-protocol: none + +`skills/objectstack-data/rules/validation.md` gains `## Locking a Field`: a two-by-two table of `readonly`, `readonlyWhen`, `uiReadonly` and `uiReadonlyWhen` (who is kept out, and when), one checked sales-order example, and what each column does at run time. The server lock (`readonly`, `readonlyWhen`) drops the value from every non-system write and answers success; the hand lock (`uiReadonly`, `uiReadonlyWhen`) stops the console offering the field while an action, an import and the API still write it, each write judged by the object's validations. A status field that only a Confirm action moves is `uiReadonly: true`; under `readonly: true` a declarative action's own write is dropped. The section also covers the object-level `uiReadonlyWhen` and how a field replaces it, what a console create does with a `uiReadonly` field, and the refused pair. + +One sentence the skill carried is corrected on the way: an import is not a system-context write, so `readonly: true` drops an imported value like any other client write. The two bullets that said otherwise are now one pointer at the new section, and `SKILL.md` § Conditional Field Rules routes there. `evals/objects-fields-relationships.json` gains case 30, a `uiReadonly` status field. + +`@objectstack/spec`: the parse refusal for `uiReadonly: true` beside `readonly: true` keeps its wording and now ends with where the model is recorded: `The two locks and which one to choose: ADR-0163 (D1, D6).` No schema, accepted value or default changes. diff --git a/.changeset/37444-form-list-words-off-first-load.md b/.changeset/37444-form-list-words-off-first-load.md new file mode 100644 index 00000000000..e521c198789 --- /dev/null +++ b/.changeset/37444-form-list-words-off-first-load.md @@ -0,0 +1,13 @@ +--- +'@object-ui/app-shell': patch +'@objectstack/console': patch +--- + +perf(app-shell): every Console page stops loading the Studio designer's English strings before its first screen + +Clause-②: no +Metadata-protocol: none + +Since the Studio forms list gained its "On" column, every Console page fetched the Studio designer's string table (about 81 KB gzip in two files) before its first screen, though only that list shows the words. The column's words now load the first time the column draws. By then the Studio list has already loaded the same strings, so they show at once. + +Nothing a user sees or saves changes. Nothing to migrate. diff --git a/.changeset/37444-list-route-defers-authoring.md b/.changeset/37444-list-route-defers-authoring.md new file mode 100644 index 00000000000..be1e1fffc56 --- /dev/null +++ b/.changeset/37444-list-route-defers-authoring.md @@ -0,0 +1,13 @@ +--- +'@object-ui/app-shell': patch +'@objectstack/console': patch +--- + +perf(app-shell): an object list stops loading the package ask, the view settings panel and the create-view dialog before its first screen + +Clause-②: no +Metadata-protocol: none + +An object list page fetched about 183 KB (brotli) of authoring code before its first screen, though it only needs that code when someone opens it. Three pieces did this. The "pick or create a package" ask that a view create may open was drawn closed on every list, and it brought in the package page's create dialog, its form and the Studio strings. The view settings panel and the create-view dialog were also drawn closed on every list. Now each one loads the first time it is opened, and after that it stays mounted, so closing it works as before. When a view create is refused, the reason loads with the refusal, and its toast shows once those strings arrive. + +Nothing a user sees or saves changes, apart from a short wait the first time one of these opens. Nothing to migrate. diff --git a/.changeset/37444-list-route-defers-form.md b/.changeset/37444-list-route-defers-form.md new file mode 100644 index 00000000000..a538c7e75dc --- /dev/null +++ b/.changeset/37444-list-route-defers-form.md @@ -0,0 +1,14 @@ +--- +'@object-ui/plugin-view': patch +'@object-ui/app-shell': patch +'@objectstack/console': patch +--- + +perf(plugin-view, app-shell): an object list stops loading the form package before its first screen + +Clause-②: no +Metadata-protocol: none + +An object list page fetched the whole form package (about 46 KB gzip) before its first screen, though it draws a form only when someone creates or edits a record. Two things did this. The object view imported its create and edit form statically, and the console drew a closed record-form dialog on every object page. Now the object view loads its form the first time one opens, and the console mounts the record-form dialog the first time it opens and keeps it mounted after that, so closing it works as before. + +Nothing a user sees or saves changes, apart from a short wait the first time a form opens on a page. Nothing to migrate. diff --git a/.changeset/37753-build-progress-frame-retired.md b/.changeset/37753-build-progress-frame-retired.md new file mode 100644 index 00000000000..66e78b95621 --- /dev/null +++ b/.changeset/37753-build-progress-frame-retired.md @@ -0,0 +1,22 @@ +--- +'@objectstack/spec': minor +--- + +fix(spec)!: retire the build-progress stream frame (`ai/build-progress.zod.ts`) — its reader and its producer are gone + +Clause-②: no (narrowing) — six published exports of `@objectstack/spec/ai` are removed +Metadata-protocol: narrowed + + + +**BREAKING** for TypeScript code that imports the build-progress frame from `@objectstack/spec/ai`. The module declared the payload of the `data-build-progress` stream part the build chat drew as its progress panel. That panel was removed with the build chat front end, and the cloud build loop that emitted the frame was removed with it, so nothing parsed the frame any more and the exported schemas read as a capability that no longer exists (ADR-0049 enforce-or-remove). It was never authored metadata: no metadata type, source file or stored row carries it, so there is nothing for `os migrate meta` to rewrite. A lingering import stops compiling, which is where an upgrader meets the change. + +What moves (each line FROM → TO): + +- `BuildProgressFrameSchema`, `BuildProgressFrame` (`@objectstack/spec/ai`): FROM the frame's `data` floor (`phase`, `hop`, `tool`) TO removed — delete the import and the code that emits or reads a `data-build-progress` part. +- `BuildProgressPhaseSchema`, `BuildProgressPhase`, `BUILD_PROGRESS_PHASES` (`@objectstack/spec/ai`): FROM the closed phase vocabulary (`structure`, `data`, `verify`, `done`) TO removed — delete the import. +- `BUILD_PROGRESS_FRAME_TYPE` (`@objectstack/spec/ai`): FROM the literal `'data-build-progress'` TO removed — delete the import. + +The fix: delete the imports. A host that still streams a progress part of its own passes any `data-` part name to `ctx.onProgress` (`ToolExecutionContext.onProgress`, unchanged) and owns the payload shape it sends. + +The retirement kit: `ai/build-progress.zod.ts` and its test deleted, `RETIRED_DEFS_BY_MAJOR[19]` rows `ai/BuildProgressFrame` and `ai/BuildProgressPhase`, D3 `ai-build-progress-frame-retired`, the `json-schema.manifest/ai.json` and `authorable-surface/ai.json` rows deleted deliberately (the def is no longer emitted), the regenerated `api-surface`, `export-origins` and `declaration-map` shards, the removed `build-progress` reference page, and the `type-alias-convention` pin count 881 → 879. diff --git a/.changeset/37766-abandoned-mirror.md b/.changeset/37766-abandoned-mirror.md new file mode 100644 index 00000000000..5836107f822 --- /dev/null +++ b/.changeset/37766-abandoned-mirror.md @@ -0,0 +1,16 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +fix(approvals): an abandoned approval never writes a closed value on its status mirror (ADR-0162 D5, Execution item 7) + +Clause-②: no +Metadata-protocol: none + +A request is abandoned by its submitter's recall (while it is pending, or in the revise window after a send-back), by the override arm of a recall (an administrator, or a system context), and by the sweep that releases a record held by a dead run. Each puts a value back on the field the approval mirrors its status onto. Where the object's `closedStates` lists any value for that field (ADR-0162 D1), the mirror now chooses that value so that it never closes the document again: + +- **`recalled`** is written where the field declares it and the object does not close on it, as before. A declared `recalled` the object closes on is withheld, and a `warn` line says so: listing `recalled` among the closed values closes nothing through the mirror. +- **Otherwise the order**: the value held at submit, the field's declared default, empty. A closed value is passed over at each step, and on a required field an empty value at submit is passed over for the default. A pass is logged at `info`. +- **A closed value the approval did not write is left alone.** Where the field holds a closed value, the mirror asks the request table once, by the request's root run and record, whether a request of the same approval on the same record had that value as its status. Where none did, it writes nothing and logs it at `info`. A request of the approval on another record (another item of a `map`) does not count. Where it cannot tell (the request records no root run, or a request on the record that records none was opened since the approval's run started), it goes down the order. + +Every other write of the mirror is unchanged, and so is every write on an object that closes on no value of the mirror field. diff --git a/.changeset/37766-approval-closed-states-authoring-rule.md b/.changeset/37766-approval-closed-states-authoring-rule.md new file mode 100644 index 00000000000..a89a93a2bab --- /dev/null +++ b/.changeset/37766-approval-closed-states-authoring-rule.md @@ -0,0 +1,14 @@ +--- +'@objectstack/lint': patch +--- + +feat(lint): an approval that cannot show itself in progress on a field its object closes on is refused where it is authored (ADR-0162 D5) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `@objectstack/lint` exports `validateApprovalClosedStates`, `approvalRootObjectsOf`, `APPROVAL_CLOSED_STATE_GAP` and the type `ApprovalClosedStateFinding`; the rule's sentences are registered in all 11 platform locales. + +A new member of the reference-integrity suite, `validateApprovalClosedStates` (finding `approval-closed-state-gap`, at error), judges each flow of a stack as the root of an approval, on each object it can start on a record of, through the one judge the approvals plugin's first request asks (`judgeApprovalOpeningSync`, `@objectstack/metadata-core`). `os validate`, `os build` and `os lint` refuse the gap on a project's stack, and the runtime publish door (Studio, REST `/meta`, MCP) refuses it with `INVALID_METADATA` (422) on a `flow` or an `object` write: an active save, a draft's promotion, a restore and a package publish (a draft save is not refused). An `object` write judges the written package's live flows and is charged only with a gap it adds. In a package publish each draft is judged against the batch's objects, and a flow the batch redrafts is judged as its draft, so a package that declares `closedStates` and repairs its flow in the same publish passes. The rule refuses only what it has in view: a call to a flow the stack does not hold, a node type the spec does not ship and a host with no `job` service are not refused here, and are judged at the approval's first request, which stays the rule. An object that declares no `closedStates` is judged nowhere. + +Why the protocol line reads none: the rule reads only `closedStates`, which this release adds. No object a released version accepts declares it, so nothing that could be published before is refused now. diff --git a/.changeset/37766-opening-check.md b/.changeset/37766-opening-check.md new file mode 100644 index 00000000000..ce7e3b7040f --- /dev/null +++ b/.changeset/37766-opening-check.md @@ -0,0 +1,19 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +feat(approvals): an approval that cannot show itself in progress on a field its object closes on does not open (ADR-0162 Execution item 7, the check) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `sys_approval_request` gains the engine-written, read-only column `between_steps_json`; `ApprovalService` gains `noteSweepClockScheduled()`, and the input of `ApprovalService.openNodeRequest` gains the optional member `locale` (the run's locale, for the refusal's wording); the plugin's message catalog gains twelve `approvalOpening*` sentences in all 11 locale packs. + +At an approval's first request the plugin now reads the approval whole: the flow its root run was started on and every flow a `subflow` or a `map` in it names, to any depth. Where a step can act on an object that declares `closedStates`: + +- **The between-two-steps set is stamped** on the request, and every later request of the same approval carries the same set. It lists the nodes after which a step of the approval can still follow, so that a run that stops there can later be told from one that stopped after the last step. +- **The approval does not open** where a step mirrors onto a field the object closes on at `pending`, `returned`, `approved` or `rejected`, and one of these is missing: the field declares `pending` and the object closes on neither `pending` nor `returned`; a `state_machine` rule on the field that declares the moves out of a closed `approved` or `rejected` includes `pending` among them; the field has no `readonlyWhen` and no request-status option has a `visibleWhen`; every step that can act on the object mirrors onto the same field; no node that can pause the run (a `wait`, a `screen`, a node type with no descriptor) stands between two steps, and no `map` runs an approval step for items it does not show are not records. An approval one of whose flows cannot be read does not open either, and neither does one on a host that runs no `job` service. + +A refused approval fails its run at the step with `VALIDATION_FAILED` and one sentence per gap naming the flow, the step, the object, the field and what is missing, in the run's locale. No request row is written. + +Not judged, and unchanged: an application in which no object declares `closedStates`; an approval whose objects declare none, once it has been read whole (in an application where some object declares the key, an approval one of whose flows cannot be read is refused, whatever objects the parts that were read act on, since its objects cannot be known); a request whose run hands no root run; a later request of an approval already open (also one opened before the object declared the key); a request that cannot be placed because an earlier request on the record since its root run started records no root run. A writing node between two steps of a flow that runs as the user is not refused. diff --git a/.changeset/37766-opening-judge-metadata-core.md b/.changeset/37766-opening-judge-metadata-core.md new file mode 100644 index 00000000000..545d0778953 --- /dev/null +++ b/.changeset/37766-opening-judge-metadata-core.md @@ -0,0 +1,10 @@ +--- +'@objectstack/metadata-core': patch +--- + +feat(metadata-core): the judge of an approval's opening conditions on a closing field lives here, so every door asks one copy (ADR-0162 D5) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `@objectstack/metadata-core` exports the judge the approvals plugin's first-request check used to hold, `judgeApprovalOpening` (it awaits each flow it reads), with `judgeApprovalOpeningSync` (over a stack in hand: a flow read that answers a promise counts as a flow it cannot read), the walk both drive, `approvalFlowWalk`, and the helper and types they read (`closedValuesOf`, `OpeningCheckSource`, `OpeningFlow`, `OpeningFlowBody`, `OpeningGap`, `OpeningJudgement` and the rest). `OpeningCheckSource.calleeFlow` may answer a flow or a promise of one. The verdict and its gaps are unchanged; nothing an author writes changes. diff --git a/.changeset/37766-opening-judge-plugin-approvals.md b/.changeset/37766-opening-judge-plugin-approvals.md new file mode 100644 index 00000000000..1f4f4cfe96b --- /dev/null +++ b/.changeset/37766-opening-judge-plugin-approvals.md @@ -0,0 +1,10 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +refactor(approvals): the first-request check asks the opening judge in `@objectstack/metadata-core` (ADR-0162 D5) + +Clause-②: no +Metadata-protocol: none + +The check an approval's first request makes on a field its object closes on now calls `judgeApprovalOpening` from `@objectstack/metadata-core`, the same judge the authoring rule `validateApprovalClosedStates` asks. `approval-opening-check.ts` re-exports it and its types under the names it exported before. Which approvals open, the refusal and its sentences are unchanged. diff --git a/.changeset/37766-opening-lead.md b/.changeset/37766-opening-lead.md new file mode 100644 index 00000000000..41fcfa5b582 --- /dev/null +++ b/.changeset/37766-opening-lead.md @@ -0,0 +1,12 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +fix(approvals): the opening refusal no longer says the object closes on its approval field when its only gaps are the host's or an unreadable flow + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: the plugin's message catalog gains the sentence `approvalOpeningRefusedClosedStatesLead` in all 11 locale packs. + +An approval's first request is refused when an object it can act on declares `closedStates` and the host runs no job service, or when a flow it runs cannot be read. Those gaps are raised whatever field the object closes on. The refusal's lead used to say "the object closes on its approval field" in every case, which is false for an object that closes on another field. Where every gap is one of those two, the lead now says only what is true: the approval can act on an object that declares `closedStates`. The sentences per gap are unchanged. diff --git a/.changeset/37767-hold-root-run-spec.md b/.changeset/37767-hold-root-run-spec.md new file mode 100644 index 00000000000..da86dbe6298 --- /dev/null +++ b/.changeset/37767-hold-root-run-spec.md @@ -0,0 +1,10 @@ +--- +'@objectstack/spec': patch +--- + +feat(spec): a run's writes name the root run of its tree (`ExecutionContext.flowRootRunId`, `HookContext.provenance.flowRootRunId`, ADR-0162 D5) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `ExecutionContextSchema` and the `provenance` of `HookContextSchema` gain the optional string `flowRootRunId`, beside `flowRunId`: the run id of the root of the run tree the writing run belongs to (the run itself for a root run). The automation engine stamps it on every write a run makes; it is never read from a request. Nothing an author writes changes. diff --git a/.changeset/37767-hold-root-run.md b/.changeset/37767-hold-root-run.md new file mode 100644 index 00000000000..db64ff6ec72 --- /dev/null +++ b/.changeset/37767-hold-root-run.md @@ -0,0 +1,13 @@ +--- +'@objectstack/core': patch +'@objectstack/objectql': patch +'@objectstack/service-automation': patch +'@objectstack/runtime': patch +--- + +feat(automation): every write of a run carries the root run of its tree (`flowRootRunId`, ADR-0162 D5) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: a data write a run makes (`resolveRunDataContext`, the run identity of `@objectstack/service-automation`) carries `flowRootRunId`, the run id of the root of its run tree, beside `flowRunId`; the engine carries it onto the write's `HookContext.provenance` (`@objectstack/objectql`), the platform system api strips it with the other run marks, a sandboxed body and script see it among the declared provenance members (`@objectstack/runtime`), and it is one of the fields an entry point may not set on an `ExecutionContext` (`assembleExecutionContext`, `@objectstack/core`). The approvals plugin reads it to let every run of an approval through the hold. Absent on a write that is not a run's. diff --git a/.changeset/37767-hold.md b/.changeset/37767-hold.md new file mode 100644 index 00000000000..227e6743eb1 --- /dev/null +++ b/.changeset/37767-hold.md @@ -0,0 +1,23 @@ +--- +'@objectstack/plugin-approvals': minor +--- + +feat(approvals)!: on an object that declares `closedStates`, the document is held for the whole approval (ADR-0162 D5, Execution item 8, the hold) + +Clause-②: yes (narrowing) +Metadata-protocol: semantic +Skills-docs: none — `skills/` names no `closedStates` (git grep, 0 hits); its `lockRecord` rows describe the lock while a request is pending, which this does not change, and `content/docs/automation/approvals.mdx` teaches the hold + +**BREAKING** for a caller that edits a record of an object that declares `closedStates` while its approval is between two steps, or after its last decision until the approval is over: FROM the edit landing (the record was locked only while a request was pending, and only under a node whose `lockRecord` is not `false`) TO the edit refused `409 RECORD_LOCKED`. The same holds for an automation that runs as a user outside the approval's own flow, such as a record-change flow with `runAs: 'user'` that a decision sets off. The one-line fix: make the edit before submitting or after the approval is over, or make it from the approval's own flow, whose every run passes; for such an automation, run it with `runAs: 'system'`. No metadata changes and no stored metadata is refused. + +What the hold is. Every decision on such an approval leaves a mark on its request (`unjudged_since`), cleared once the approval is judged or its next request opens. While a mark stands, the pending lock holds the record and its direct `master_detail` lines as a pending request under a locking node does, whatever field the object closes on and whatever the node's `lockRecord` says. It passes: + +- a system context, the approval status mirror among them; +- a write that carries only the mirror field; +- a write by any run of the approval, the record's run or a `subflow` or `map` run under it at any depth, known by the root run (`flowRootRunId`) the automation engine now carries on every write of a run; a hook's write through its own `ctx.api` carries it, a write a hook makes as another caller does not; +- the revise window of a returned request; +- the record's own delete, which lands and ends the approval: it is marked abandoned on its latest request, its marks are cleared, and nothing is written (the reconciler does the same for a record deleted another way). + +An approval that opened before its object declared `closedStates` left no marks and is not held. The approvals-family lock read (`getRecordLock`, the `/lock` and `/locks` routes) answers for a pending request only, as published: in a passage it answers `{ "locked": false }`. + + diff --git a/.changeset/37767-outcome-when-approval-over.md b/.changeset/37767-outcome-when-approval-over.md new file mode 100644 index 00000000000..131a7031538 --- /dev/null +++ b/.changeset/37767-outcome-when-approval-over.md @@ -0,0 +1,20 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +feat(approvals): on a field its object closes on, an approval's decision is written when the approval is over (ADR-0162 Execution item 8, the outcome) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `sys_approval_request` gains the engine-written, read-only datetime column `unjudged_since` (the mark) and an index on it; the `getRun` member of the automation surface the plugin declares (`ApprovalResumeSurface`) now also types the step log the engine already returns; the plugin's message catalog gains `approvalAbandonedTitle` and `approvalAbandonedBody` in all 11 locale packs, sent on the topic `approval.abandoned`. + +What changes, only for an approval the check stamped when it opened (one with a step that can act on an object that declares `closedStates`): + +- **The decision is held back.** Where the object closes on the step's mirror field at `approved` or `rejected`, neither decision is written onto the record when it is made. The request records it as before, and the field keeps `pending`. Every other status (`pending` as a request opens, `returned` at a send-back, what a recall leaves) is written as before. +- **The mark.** Every decision on a request of such an approval sets `unjudged_since` in the update that records it, also where nothing is held back. It is cleared when the approval is judged, and when the approval's next request opens on the record. A recall, an administrator's override and the dead-run sweep clear it on the approval's earlier requests. +- **The door judges the approval.** After a decision (by a person or the SLA clock), a send-back (and its auto-rejection), a resubmission, a recall and the continuation of a restored run, the plugin reads the run that carries the record and the approval's requests on it. Finished (the run completed, stopped after the last step, or is parked at a pause no step can follow): it writes the latest request's decision, as the person who decided it. In progress (a request is open, or the run is parked at a pause a step can follow): nothing. Ended between two steps (the run stopped on a node a step could still follow, a failure the flow routed at the top level ended it, or a later step could not open, whatever the flow did with that): the approval is abandoned. Cannot tell (the run is being advanced or cannot be read): nothing, and the mark stays. +- **An abandoned approval.** The latest request is marked abandoned, the field is put back by item 7's order (never a closed value, and nothing where another approval's request is open on the record on the same field), a timeline line with no actor says why and what the record was put back to, and the submitter is told on `approval.abandoned` instead of `approval.approved` or `approval.rejected`. The decisions already made stay on their requests. +- **A restored run is refused.** `continueRestoredRun` refuses a request of an abandoned approval with `INVALID_STATE` and tells the operator to cancel the restored run. + +Unchanged: an object that declares no `closedStates`; an approval that opened before its object declared the key, or whose requests could not be placed. An approval on an object that declares the key on another field than the approval's holds nothing back: its decisions are written at once, as before, and the door only clears the mark. diff --git a/.changeset/37767-reconciler.md b/.changeset/37767-reconciler.md new file mode 100644 index 00000000000..8c77832acc2 --- /dev/null +++ b/.changeset/37767-reconciler.md @@ -0,0 +1,29 @@ +--- +'@objectstack/plugin-approvals': patch +'@objectstack/service-messaging': patch +--- + +feat(approvals): the reconciler, and the door reads every run of an approval (ADR-0162 Execution item 8) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `ApprovalService` gains `reconcileMarkedApprovals(options?)`, which the plugin runs on the sweep clock beside the escalation, dead-run and stranded-request sweeps; the `getRun` member of the automation surface the plugin declares types the step log's `childRunIds` and `childRunIdsTruncated`, the run's `trigger`, `completedAt` and `summary`, and an optional `{ strict }` read; the plugin's message catalog gains `approvalFlowNotContinuedTitle` and `approvalFlowNotContinuedBody` in all 11 locale packs, sent to the organization's administrators on the topic `approval.flow_not_continued`; `PLATFORM_NOTIFICATION_TOPICS` of `@objectstack/service-messaging`, the topics a notification preference may name, gains that topic. + +Only for an approval the check stamped when it opened (one with a step that can act on an object that declares `closedStates`): + +- **The door reads every run of the approval.** Where it read the run that carries the record and the latest request's own run, it now walks the tree from the run that carries the record, following the child runs each delegating step records: every `subflow` child, and every `map` item run that does not carry another record (an item that is a record carries an approval of its own). It reads the whole tree before it answers, and one run decides for the whole approval: one that the store could not answer for, or that reports a status of a run in motion (`pending`, `running`, `retrying`), makes it cannot tell; otherwise one parked at a node a step can follow, in progress; otherwise one that ended between two steps, abandoned. A run parked at such a node on a child run says what its child says, so the walk reads the child, at any depth. The automation engine reports none of those three statuses for a flow run today: a run it is advancing reads as paused with its pause gone, or as a run with no row, and is held by the rule for a run that stopped, below. So a sibling child whose failure the flow routed, a middle run two levels down that failed, an item run that failed before its step, and a run between two others that is being advanced are no longer read as finished. A failure routed to a pause no step follows is read as abandoned, as on the base. A stop is answered where a request of the approval opened after it. One judgement reads at most 200 runs beside those it kept as ended: past them it is cannot tell, keeps what it read, and the next judgement reads on. That has an end: once the approval's marks have stood for the hour of the age bound, a judgement reads on only while it keeps a run the approval had not kept (the kept list holds 200 runs), and the judgement that keeps none places the approval by the step last decided, below. Two costs come with that rule. A tree the judgements cannot finish is placed without being finished, and from about 399 runs a tree can be one no judgement finishes: the walk reads the runs it starts from before the runs below them, so for a `map` of 199 items that each call a `subflow`, every judgement reads the run and its 199 items and none of the runs below them. And the placement follows from the shape of the flow, so an approval submitted again on the same flow can meet the same end: the remedy is the flow's, not the submitter's. Reading on can take up to 200 further visits of the reconciler after the hour: one each sweep (every 5 minutes by default, the plugin's `escalationScanIntervalMs`), or one each turn of its walk where more requests are marked than one sweep reads. A run parked on a child run that such a judgement did not get to says nothing of its own, and the child a parked run waits on is read next, before the runs beside it. +- **The plugin keeps what it read.** At every door, one that leaves the next request pending included, and as each request opens, the approval's latest request keeps, in its config snapshot (`__runsRead`): the runs that are not read again (`ended`), the runs read to their end over a child run that was not (`open`), a failure between two steps found in a run that ended, and the states the last judgement read that say a run has stopped (`stood`), which the rule for a run that stopped uses, below. A run is kept as ended only once it was read to an end and every child run its steps name is kept as ended too. So a child whose read failed, a child with no row, and the runs past the 200 one judgement reads are read on the next pass, which starts from the open runs as well. A run that a stored step names and that a pass did not read is never left out without a word: it is read on a later pass, it counts as passed by the rule below, or the approval is cannot tell and then placed. A run that no stored step names any more is not covered by that: see the limit of this release, below. A run the plugin read before the automation engine trimmed its history is not needed again, so an approval whose refused outcome is tried again after its run's history went is judged as it would have been. +- **A run with no row, under a run that went on past it, is passed.** A run the engine has no row for counts as passed, and is kept as ended, where a run the plugin read went on past the step that names it: that step succeeded, and the run reached an end of its flow, or logged a later step and is not parked at that step. So an early child run trimmed before the plugin read it does not hold the approval back. A step that failed is never passed, also where the flow routed the failure and went on. A run the plugin had read to its end over an unread child, and whose own row is gone since, is not passed either: nothing names that child any more. +- **A step log the engine marked, or the history row cut, is cannot tell.** Two logs are read as cut, and are not judged from as they stand: one with a step that carries the engine's mark `childRunIdsTruncated` (its execution started more child runs than the 200 a step names, or the history row shed the step's list to fit its size), and the log of a run that ended whose history row keeps fewer steps than the run logged (the row bounds the log by bytes, to a tail of it or to none, while the run's summary still counts every step). Within the age bound nothing is written; past it the approval is placed by the step last decided, as for a run with no row, below. A run whose log is cut is not kept as ended, the child runs it does name are still read, and it speaks for none of them: no run it names counts as passed. A summary that is absent or dropped its per-node detail gives nothing to compare, and reads as cut. +- **The limit of this release: a log that loses whole steps carries no mark (ruling 7268216330 on #37767).** The engine marks one thing: a step whose child-run links were shed carries `childRunIdsTruncated`, above. A log that loses whole steps carries no mark, whichever way it loses them: the engine's compaction of a log of more than 200 steps, the history row's halving of a log over its 64 KB cap, a row stored as null. The plugin reads what the log kept, and a child run named only by a dropped step reads as one the run went past: it is not read. For a halved row and a null row the plugin can still tell that steps are missing, from the run's summary, which counts every step: that is the second log read as cut, above, and the approval is held and then placed. For a compacted log it cannot tell. A run that logged more than 200 steps is stored with 200 of them: every top-level step and every failed step, then the most recent of the rest (the most recent 200 of the top-level and failed steps, where those alone pass 200), and it is judged from those, as before this change. What an operator gets in that case: a `subflow` or `map` step the compaction dropped (one that succeeded inside a `loop`, `parallel` or `try_catch` region, or an early step of a very long run) no longer names the child runs it started; a failure the flow routed inside such a child run, between two steps, is not seen; and the approval can be written as finished, with no notice and no line in the log. A process that still holds the run in memory reads its whole log, so this is a judgement made once that process is gone. No approval is judged worse than before this change, whose door read no child run. +- **The kept reading is its own key.** It is written onto the snapshot read again just before the write, and only while the column still reads the same, at most three times. It cannot write a stale snapshot over a note another writer left there (`__laterStepNotOpened`, `__strandedContinuation`). The judgement reads the note that a later step could not open once it has read the runs, so a note that lands while they are read is judged with. +- **A run that stopped, placed by the step last decided.** A run the engine has no row for and that no run the plugin read speaks for (its history is gone, or a process stopped while advancing it), a run whose step log is cut, above, a tree of more runs than the judgements can read in full, above, and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), in the run that carries the record or in a child run any number of levels below it, are cannot tell for an hour from the approval's marks (the age bound). Past it, each has stopped at the step last decided once two judgements in a row read it in the same state, for the same run. The hour is counted from the marks and not from the run's last movement, and a run the engine is resuming reads as paused with its pause gone or as a run with no row; so an approval whose flow waits longer than the hour between two steps by design (a `wait` node, a batch over records whose items are approved one by one, a child run parked outside the approval's steps) is past the bound whenever it resumes. Only an approval that holds nothing back can wait so: the check at its opening refuses each of the three between two steps of an approval on a field its object closes on. There a placement ends the hold and writes nothing. The judgement that reads a run in such a state first therefore does not place it (it cannot tell, and a run parked on a child that has ended is in progress), and keeps the state it read (`stood` in `__runsRead`); the next judgement places the run if it reads the same, and reads it anew if it does not. A judgement within the hour keeps what it read as well, a door's included, so an approval read in that state within the hour is placed by the first visit past it, and one that was not takes one visit more. A reading that could not be kept leaves on the request the reading kept before it: the next judgement stands on that earlier one, so a state kept earlier can still count, and where none was kept nothing is placed. An approval whose reading is never kept is therefore held with no end. Two passes that each fall inside a resume of the same run still read it as stopped. Whether a later step can follow that step is asked in the flow its request records, so a node of another flow that carries the step's id does not answer for it. Where one can, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and a run still parked there is cancelled, with the runs that wait on it up to the run that carries the record, through a `map` whose items are not records as through a `subflow`. The cancel follows the put-back, and is not tried again once the put-back has landed: where it fails, or the process stops between the two, the run stays parked, the approval stays abandoned, and the door that continues a restored run refuses it. At the last step, the outcome is written and, once that write has landed, the administrators are told that the flow could not be seen through to its end after that step; the run's pause is left for an operator. A refused write sends no such notice, and the pass on which the write lands sends it. The notice says what to do in each case: continue or cancel a run that is still paused, and where the run has ended or no run is left, check that the steps after the decision were done. An approval placed for a cut log or a tree too large to read can be one whose flow did go on, which the plugin could not read in full: at its last step the administrators get the notice for a flow that ran, and where a later step can follow, the submitter submits again. +- **The reconciler.** Each pass reads two windows of at most 200 marked requests (`unjudged_since`): the oldest marks, and the next page of a walk over every marked request by id, so that marks which stay cannot keep the newer ones from being read. It judges each approval among them once, as the door would have: it writes the outcome in the name of the request's recorded decider, abandons the approval, or, where nothing was held back, clears the mark and writes nothing (where it concluded that a run had stopped, a line in the log says so). It ends what no door saw: a run that was cancelled, a parent run cancelled while its child's request was pending, and the stopped runs above. Past the age bound it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child run has ended or has no row, each once two judgements in a row read it so, as above. The item run of a `map` whose items are records is such a child once it is in a terminal status: its steps are an approval of the item's own record and are not read, only whether it has ended, and it is kept as ended only once it has. +- **A refused write is tried again.** A refused outcome or put-back leaves the marks, and the next pass tries it again. The timeline line and the administrators' notice (keyed per request and status) are left once for one refusal; the same holds for the line an abandoned approval leaves. +- **A deleted record.** Where the approval's record was deleted, the reconciler clears the marks of its requests and writes nothing: no retry and no notice. +- **The stranded-request report** (`inspectStrandedRequests`) leaves a decided request the check stamped to the door and the reconciler, and still reports a returned one. + +- **A refusing end is an end.** The door reads a run that reached an end of the flow as having ended there, a refusing end (`outcome: 'refused'`) included, as it already did for a completed run. + +Unchanged: an object that declares no `closedStates`; an approval that opened before its object declared the key. diff --git a/.changeset/37767-status-mirror-closing-field-refusal.md b/.changeset/37767-status-mirror-closing-field-refusal.md new file mode 100644 index 00000000000..b74af8a9633 --- /dev/null +++ b/.changeset/37767-status-mirror-closing-field-refusal.md @@ -0,0 +1,16 @@ +--- +'@objectstack/plugin-approvals': patch +'@objectstack/service-messaging': patch +--- + +fix(approvals): on a field the object closes on, a refused write of the approval status mirror is no longer swallowed (ADR-0162 Execution item 8) + +Clause-②: no +Metadata-protocol: none + +A validation rule, an option's `visibleWhen` or a hook of the app can refuse the write that mirrors an approval's status onto the record. The mirror used to log every such refusal at `warn` and go on. On a field the object closes on at `approved` or `rejected` (`closedStates`, ADR-0162 D1): + +- **The `pending` of an approval's first request.** The approval does not open. The request's row is voided as `cancelled`, nobody's inbox lists it, no lock is taken, and the run fails at that step with the refusal's own message. The record keeps the value it held, a closed one included. +- **Every other write** (a decision, a send-back, a recall's put-back, a later request's `pending`, the dead-run sweep's put-back). The field keeps the value it held, and the refusal is reported three ways: an `error` line naming the write and the fix, a line with no actor on the request's timeline carrying the refusal's message, and a notice to the organization's administrators under the new topic `approval.status_mirror_refused`, which the notification preference options now list. + +An object that declares no closed state is unchanged: its mirror still logs a refused write at `warn`, and its approval still opens. diff --git a/.changeset/37767-step-child-runs.md b/.changeset/37767-step-child-runs.md new file mode 100644 index 00000000000..fb072d0c442 --- /dev/null +++ b/.changeset/37767-step-child-runs.md @@ -0,0 +1,18 @@ +--- +'@objectstack/service-automation': patch +--- + +feat(automation): a delegating step records the child runs it started (ADR-0162 Execution item 8) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `AutomationEngine` gains the public read `runStartedFor(context)` and an optional second argument to `getRun(runId, { strict })`; a node executor's result (`NodeExecutionResult`) gains the optional `childRunIds`, and the exported step type (`StepLogEntry`) gains the optional `childRunIds` and `childRunIdsTruncated`, which the engine writes onto the step's log entry (`ExecutionStepLogSchema`, in `@objectstack/spec`). + +- **`childRunIds` on a step.** A `subflow` step names the one run it started, on every exit: paused on its child, completed, failed or refused. A `map` step names the item runs that execution of the step started. Absent on a step that started none, and on a child that paused with no run id. `getRun` serves it with the rest of the step log, so a reader can walk a run's tree from its root; before this, a parent's link to its child lived only on the parent's pause (`correlation: 'subflow:'`), and only while the parent was parked. +- **A step names at most 200 child runs.** A `map` can start up to 10,000 item runs. A step whose execution started more than 200 names the first 200 started and carries `childRunIdsTruncated: true`, so a reader never takes the list for all of them. +- **What the durable history keeps of the links.** A log of more than 200 steps is compacted for history: it keeps every top-level step and every failure while those number 200 or fewer, and otherwise the most recent 200 of them, so compaction can drop a step with its link. A terminal run's step log over the history row's 64 KB cap is stored without every step's `childRunIds`, each step that named child runs marked `childRunIdsTruncated: true`, before any step is dropped; only a log still over the cap without them is halved from its head, as before. A mark costs 28 bytes on each step it lands on, so a log that fits the cap without its links by less than its marks' bytes is halved where a log that never named a child run was not. +- **`runStartedFor(context)`.** A run that ends inside `execute` answers no `runId` (the contract sets it on a paused run only). The engine now answers the id of the run the last `execute` call started for that very context object, whatever it ended in. A run is named once it is past the gates that skip it and leaves a history row, or where it fails before its first node and is recorded as failed; `undefined` where no run started (the flow was missing, disabled, had no start node, or its start condition or the re-entry guard skipped it). Under `errorHandling.strategy: 'retry'` it is the last attempt that started a run. The `subflow` and `map` nodes read it for a child that ended inside the call. +- **`getRun(runId, { strict: true })`.** A store that fails is still logged and read as `null` by default. With `strict`, its failure is thrown instead, so a caller that decides on a missing run can tell a run with no row from a store that did not answer. + +Unchanged: what a run does, the `runId` the contract returns, every existing step field, and which steps a run's history row keeps, but for the marks' bytes above. diff --git a/.changeset/37767-step-log-child-runs-spec.md b/.changeset/37767-step-log-child-runs-spec.md new file mode 100644 index 00000000000..1ed247148c4 --- /dev/null +++ b/.changeset/37767-step-log-child-runs-spec.md @@ -0,0 +1,11 @@ +--- +'@objectstack/spec': minor +--- + +feat(spec): a run's step log names the child runs a step started (`ExecutionStepLogSchema.childRunIds`, `childRunIdsTruncated`, ADR-0162 Execution item 8) + +Clause-②: yes (widening) +Metadata-protocol: added +Skills-docs: none — `skills/` names none of `ExecutionStepLog`, `childRunIds`, `childRunIdsTruncated` or `runStartedFor` (git grep, 0 hits): the step log is a runtime record no skill teaches an author to write + +Widened: `ExecutionStepLogSchema` gains two optional keys. `childRunIds: string[]`: the run ids of the child runs the step started, the one run of a `subflow` and, for a `map`, the item runs that execution of the step started, at most 200, the first ones started. Absent for a step that started none. `childRunIdsTruncated: true`: the step started more child runs than `childRunIds` names, either more than 200, or the run's history row shed the step's links to fit its size limit, leaving `childRunIds` absent. The engine writes both (`@objectstack/service-automation`); a reader of `getRun` can walk a run's tree from its root with them. Nothing an author writes in a flow changes. diff --git a/.changeset/37768-closed-state-refusal-sentences.md b/.changeset/37768-closed-state-refusal-sentences.md new file mode 100644 index 00000000000..7cd9079c9bb --- /dev/null +++ b/.changeset/37768-closed-state-refusal-sentences.md @@ -0,0 +1,17 @@ +--- +'@objectstack/spec': patch +'@objectstack/objectql': patch +'@objectstack/service-storage': patch +--- + +feat(spec,objectql): the closed-state refusal's own sentences, in every locale (ADR-0162 D8) + +Clause-②: yes (widening: new keys in the published Operation Message Catalog and the upload-link copy; contract-review-tier review owed) +Metadata-protocol: none + +A write refused because a record is in a closed state (`409 RECORD_LOCKED`, ADR-0162) tells the person what happened, in their own language, with a sentence from the Operation Message Catalog. + +- **New catalog keys** in `BUILTIN_OPERATION_MESSAGES`, in every locale the catalog carries (en, zh-CN, ja-JP, es-ES), overridable per deployment under `errors.` like every other key: `record_closed` with its `_unlabeled`, `_untitled` and `_opaque` forms, and `record_closed_delete_blocked` with its `_untitled` and `_opaque` forms. English, for example: "Invoice 'Northwind March' is closed, so it and its lines can no longer be changed or deleted", and "Customer 'Contoso Holdings' cannot be deleted: deleting it would also remove a closed Invoice or one of its lines". +- **The engine words the refusal from them.** The refusal names a title only from a field that holds display text and that the writer's generic read returns, and that the writer is served under its own field permissions (readable and queryable): not a field the generic read withholds (`internal`, or a credential type), not a reference field, not a field the object's `closedStates` names. Otherwise the sentence names the object's label only, and so it does when a registered security service cannot be resolved. With no security service registered there is no field-level security, and the title is named. A line's write names its master by label alone. A delete refused for what it would also remove names the record asked to be deleted and the label of the object in the way, with the title only when the delete names exactly one record by id. No sentence carries a record id, an API name or a state value. +- **On the error**: `userMessage` and the wire's `error` carry the sentence; `message` reads `RECORD_LOCKED: ` followed by the sentence, as the approval lock's refusal does; the developer sentence moves to `developerMessage`, which the REST layer does not relay. A refusal that could not judge the write keeps the developer sentence and sets no `userMessage`. +- **Upload-link page**: a closed-state refusal reaches the page with the engine's declared catalog sentence, which the page shows. The page's own `recordLocked` answers only a `RECORD_LOCKED` with no declared sentence. The page also carries a closed-state sentence (`recordClosed`) in each of its 11 languages; choosing it by the lock's reason comes with a later change. diff --git a/.changeset/37768-closed-states-metadata-core.md b/.changeset/37768-closed-states-metadata-core.md new file mode 100644 index 00000000000..708da5d7204 --- /dev/null +++ b/.changeset/37768-closed-states-metadata-core.md @@ -0,0 +1,10 @@ +--- +'@objectstack/metadata-core': patch +--- + +feat(metadata-core): the field-level-security scrub serves an object's closed states without the fields a caller cannot read + +Clause-②: yes (widening: one new optional authorable key, `ObjectSchema.closedStates`) +Metadata-protocol: added + +`closedStates` (ADR-0162 D1) is classified in the object-schema FLS reference table as a map keyed by this object's fields: an entry whose field is denied to the caller is left out of the served definition, and a map left empty is deleted. The listed values are option codes, never field references, so a value spelled like a denied field is served as written. The stored declaration is untouched. diff --git a/.changeset/37768-closed-states-objectql.md b/.changeset/37768-closed-states-objectql.md new file mode 100644 index 00000000000..8042146d6ff --- /dev/null +++ b/.changeset/37768-closed-states-objectql.md @@ -0,0 +1,17 @@ +--- +'@objectstack/objectql': minor +--- + +feat(objectql): a record in a closed state, and its lines, are closed to change (`closedStates`, ADR-0162 D2 to D7, D10) + +Clause-②: yes (widening: the engine enforces the new optional key `ObjectSchema.closedStates`; an object without it behaves exactly as before) +Metadata-protocol: none + +A record whose stored state is one of the values its object lists in `closedStates` is closed, and so are its direct `master_detail` lines (a junction row is a line of both masters). Every write a system context does not make is refused `409 RECORD_LOCKED`, with `reason` (`record_closed`, `master_closed`, `cascade_reaches_closed`, `cannot_judge`), `object`, `blockingObject` and `lockReason: 'closed_state'`; the message names no record id and no state value. + +- **What is judged**: an update or delete of a closed record; a line create, update, delete or move under a closed master, or out of one. An update is judged by the stored row, not by its payload, so the write that closes a record lands whole, other fields included, and the next write is refused. A write with no context is bound. +- **Many-row writes are refused whole**, before any row is written: one existence probe where the store compiles the line semi-join (SQL, the memory driver), otherwise the write's one read of its matched rows, under the engine's per-row ceiling. +- **Refused when it cannot be judged**: a master named in a form the engine cannot read as one id, a master or state read that fails, a many-row line write over the ceiling on a store with no probe. +- **Cascades and restore**: a delete whose cascade reaches a closed record removes no row, with or without transactions; restoring a line under a live closed master that is not part of the entry is refused. The referential clear of a deleted record's references, the recycle-bin relink, and the roll-up summary recompute (a system context) land. Change Owner and the hand-over of a banned user's work are bound like any edit: each closed record is listed among the failures. +- **Placement**: after the permission and record-access gates, before the before-hooks; a master the write names is checked through the caller's own read first. A master a before-hook supplies is not judged. +- **The registry fold** keeps a package's declaration honest: an extension's redeclaration that removes, retypes, makes multi-value or narrows a field the declaration names is refused (the field stands, and the fold logs it once), and a tenant overlay may add closed values but may not shorten the package's list or break a field it names. diff --git a/.changeset/37768-closed-states-platform-objects.md b/.changeset/37768-closed-states-platform-objects.md new file mode 100644 index 00000000000..b57babeb0eb --- /dev/null +++ b/.changeset/37768-closed-states-platform-objects.md @@ -0,0 +1,10 @@ +--- +'@objectstack/platform-objects': patch +--- + +feat(platform-objects): the Studio object form's closed-states row is translated in every metadata-forms locale pack + +Clause-②: yes (widening: one new optional authorable key, `ObjectSchema.closedStates`) +Metadata-protocol: added + +The object form's Advanced section offers `closedStates` (ADR-0162 D1); its label and help text are authored in all eleven metadata-forms locale packs. diff --git a/.changeset/37768-closed-states-spec.md b/.changeset/37768-closed-states-spec.md new file mode 100644 index 00000000000..4a410432ed6 --- /dev/null +++ b/.changeset/37768-closed-states-spec.md @@ -0,0 +1,15 @@ +--- +'@objectstack/spec': minor +--- + +feat(spec): an object declares its closed states (`closedStates`, ADR-0162 D1) + +Clause-②: yes (widening: one new optional authorable key, `ObjectSchema.closedStates`) +Metadata-protocol: added + +An object may now declare the states in which its records are closed: a map from a stored, single-value `select` field of the object to the list of that field's option values that close a record, e.g. `closedStates: { status: ['paid', 'void'], approval_status: ['approved'] }`. A record is closed when any listed field holds one of its listed values. In a closed state the record and its direct `master_detail` lines are closed to change for every caller that is not a system context. + +- **Refused where the object is authored**, at parse and at the metadata save and publish door, one located issue each: a key that names no field of the object; a field that is not a single-value `select` (another type, `radio` included, or `multiple: true`); a select whose options are not declared inline on it (a `picklist`-backed select); an empty list; a value that is not one of the field's options; a value listed twice. So is the edit that would leave such a declaration behind: removing or retyping a field, or removing an option, that a declaration still names. Take the entry out of `closedStates` first. +- **Optional**: an object without the key behaves exactly as before. A line object declares nothing to be closed with its master, and may declare its own `closedStates`. The key has no tie to a `state_machine` rule in either direction. +- Liveness row `object.closedStates`, the Studio object form's Advanced section offers it as a JSON row, and the reference docs, authorable-surface record and state counts are regenerated. +- The error-code ledger registers `RECORD_LOCKED` for `@objectstack/objectql`, the engine's closed-state refusal, beside the approval lock that already emits it. diff --git a/.changeset/37792-object-pin-overview.md b/.changeset/37792-object-pin-overview.md new file mode 100644 index 00000000000..7cc7a9e7d89 --- /dev/null +++ b/.changeset/37792-object-pin-overview.md @@ -0,0 +1,16 @@ +--- +'@objectstack/spec': minor +'@object-ui/plugin-detail': minor +'@object-ui/app-shell': minor +'@objectstack/platform-objects': minor +'@objectstack/metadata-core': minor +--- + +feat: an object can keep its record page from pinning the overview, with `pinOverview: false` + +Clause-②: yes (widening) — `ObjectSchema` gains the optional boolean `pinOverview`; `RecordPageColumns` gains the optional `pinOverview` prop, and `recordPagePinsDetails` an optional fourth argument of the same name +Metadata-protocol: added + +On a wide desktop full record page the overview (the record's own fields) is pinned to a left column beside the other tabs. An object can now turn that off with `pinOverview: false`: the page keeps the overview as its first tab, open by default, and lays its fields out by width in up to three columns, as a page whose overview is its only tab does, at any width and also when the overview holds a related table. Leaving the key out, or writing `true`, keeps the page exactly as before. Only the desktop full standard record page reads it: the side preview and a phone never pin, so they look the same either way, and print pages and authored `kind: 'full' | 'html' | 'react'` pages do not read it. An object extension cannot write it (refused with a message naming `ObjectSchema.pinOverview`), and a non-boolean value is refused at parse. The object metadata form offers it as a switch; an untouched switch writes nothing. + +Nothing to migrate. diff --git a/.changeset/37802-object-field-tabs.md b/.changeset/37802-object-field-tabs.md new file mode 100644 index 00000000000..f36eedc69ad --- /dev/null +++ b/.changeset/37802-object-field-tabs.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': minor +'@object-ui/plugin-detail': minor +'@object-ui/app-shell': minor +'@object-ui/types': minor +'@objectstack/platform-objects': minor +'@objectstack/metadata-core': minor +'@objectstack/lint': minor +--- + +feat: an object can draw field groups as tabs of its record page, with `fieldTabs` + +Clause-②: yes (widening) — `ObjectSchema` gains the optional `fieldTabs: [{ key, groups }]`; `@object-ui/plugin-detail` exports `fieldTabIdOfField` and the type `RecordPageFieldTab`, and `DefaultPageColumns` gains the optional `fieldTabs` +Metadata-protocol: added + +`fieldTabs: [{ key: 'content', groups: ['content', 'import'] }]` takes the named field groups out of the standard record page's overview and draws them as a tab right after it (`?related=fields:content`), before the related lists and the built-in tabs, in declared order; on a pinned page the first field tab is the one open beside the overview. The tab's title and icon are its first group's, and a one-group tab draws no second heading. The overview keeps the groups no tab names, the ungrouped fields, the body tables and the approval band. Each tab has its own "show empty fields" row; a tab whose groups are all hidden (`visibleWhen`) or missing on the served object is not drawn; the reader cannot move or hide these tabs; a cited `?section=` inside a tab opens that tab first. The entry form, print pages and authored pages are unchanged. + +The parse refuses a group the object does not declare, a group two tabs name, a group with `relatedList`, a repeated `key`, and the form-level keys (`fields`, `label`, `icon`, `visibleWhen`); the undeclared-group refusal and the `fields` refusal name the form-level `FormSchema.fieldTabs`, which lists field names. `FormSchema.fieldTabs` in `@object-ui/types` refuses a missing `fields` with a message naming `ObjectSchema.fieldTabs`. An object extension cannot write the key. `composeStacks` with `objectConflict: 'merge'` refuses two declarations of one object whose `fieldTabs` differ, as it does every other object-level collection. The object metadata form offers it as a repeater. `os lint` warns (`object/field-tabs-empty-overview`) when the tabs take every field out of the overview. + +Absent: unchanged. Nothing to migrate. diff --git a/.changeset/37815-body-capabilities-every-gate.md b/.changeset/37815-body-capabilities-every-gate.md new file mode 100644 index 00000000000..68beb2b9aeb --- /dev/null +++ b/.changeset/37815-body-capabilities-every-gate.md @@ -0,0 +1,30 @@ +--- +'@objectstack/lint': minor +'@objectstack/spec': patch +--- + +feat(lint)!: a hook body's gated calls, and an action body's calls to every gate besides `api.write`, are refused at publish when the body is not granted the token + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: follow-up #38655 + + + +**BREAKING** for the publish of an action, an object or a hook whose L2 body calls a member the QuickJS sandbox gates without that member's token in `body.capabilities`. Such a body saved and published before; the sandbox refused the call with `403 INSUFFICIENT_PRIVILEGES` every time the body reached it, so it never worked. It is refused now, at the runtime publish door and in `os validate` / `lint` / `compile` / `build`, with the token named. The schema is unchanged and stored metadata is not rewritten or refused at boot; the refusal comes at the next publish. + +The gates are the sandbox runner's own, token by token, and the rule's list is pinned to the runner's source: the `ctx.api.object(…)` read leaves (`find`, `findOne`, `count`, `aggregate`) behind `api.read`, the write leaves behind `api.write`, `ctx.api.transaction(…)` behind `api.transaction`, `ctx.log.debug|info|warn|error(…)` behind `log`, `ctx.crypto.randomUUID()` behind `crypto.uuid`, `ctx.email.send(…)` behind `email.send`, `ctx.activity.append(…)` behind `activity.append`, and on a hook body `ctx.title(FIELD)` with an argument behind `api.read` (`ctx.title()` needs no token). + +- `hook-body-capability-undeclared` (new): an L2 hook body that calls any of those gates without its token. A hook body is never granted `email.send`, so its `ctx.email.send(…)` call is refused with the remedy that works: remove the call and send the mail from an action, a job or a flow. A hook body `os build` / `os verify` lowered from an inline `handler` is judged the same way: its grant is the one the build inferred from its calls, and the build reads each gated call in each spelling the rule reads. Runs on the runtime `hook` door. +- `action-body-capability-undeclared` (new): an L2 action body that calls a gate other than the writes without its token. An action body `os build` / `os verify` lowered from an inline `target` function is judged the same way, against the grant the build inferred from its calls. Runs on the runtime `action` and `object` doors. +- `action-body-write-capability-undeclared` is unchanged: an action body's write without `api.write` keeps its id and its words. + +## FROM → TO + +- Authored hook body (arm a). FROM: `hooks: [{ …, body: { language: 'js', source: "await ctx.api.object('task').update({ id, done: true })", capabilities: [] } }]` saved and threw at every run. TO: declare the token, `capabilities: ['api.write']`. +- Authored action body, other tokens (arm b). FROM: `body: { language: 'js', source: 'await ctx.api.transaction(async () => { … })', capabilities: ['api.write'] }` saved and threw at every run. TO: declare the token, `capabilities: ['api.write', 'api.transaction']` (likewise `log`, `crypto.uuid`, `email.send`, `activity.append`, `api.read` for the call the finding names). +- Authored hook body calling `ctx.email.send(…)`. FROM: saved and threw at every run. TO: remove the call and send the mail from an action, a job or a flow. + +A hook written as an inline `handler`, and an action written as an inline `target` function, need no change: the build infers the grant from each gated call in each spelling the rule reads (`?.`, whitespace or a comment between steps, the optional call), so the body it lowers carries the token. FROM, `actions: [{ …, target: async (ctx) => { await ctx.api.transaction(…) } }]` built clean; TO, it still builds clean, its lowered body granted `api.transaction`. + +`os explain hook-body-capability-undeclared` and `os explain action-body-capability-undeclared` carry an entry for each. `@objectstack/lint` exports the two rule id constants, `ACTION_BODY_CAPABILITY_UNDECLARED` and `HOOK_BODY_CAPABILITY_UNDECLARED`. `@objectstack/spec` adds only the upgrade-guide entry `hook-and-action-bodies-calling-an-ungranted-gate-refused`. diff --git a/.changeset/37815-record-write-hint-update.md b/.changeset/37815-record-write-hint-update.md new file mode 100644 index 00000000000..09add589336 --- /dev/null +++ b/.changeset/37815-record-write-hint-update.md @@ -0,0 +1,10 @@ +--- +'@objectstack/lint': patch +--- + +fix(lint): the `action-record-write-discarded` hint prescribes a write a sandboxed body can run + +Clause-②: no +Metadata-protocol: none + +The hint now reads `ctx.api.object('').update({ id: ctx.recordId, : … })`. It used to prescribe `ctx.api.object('').updateById(ctx.recordId, { … })`, and the sandbox an action body runs in installs no `updateById` on `ctx.api.object(…)`: following the hint turned the discarded write into `TypeError: not a function` on the action's first run. The `os explain action-body-write-unknown-field` text no longer lists `create` and `updateById` among the calls an action body persists through, for the same reason. What lint judges is unchanged: an `updateById` payload in a body is still graded. diff --git a/.changeset/37852-form-type-followups.md b/.changeset/37852-form-type-followups.md new file mode 100644 index 00000000000..e8e5f1f9225 --- /dev/null +++ b/.changeset/37852-form-type-followups.md @@ -0,0 +1,15 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/spec': patch +--- + +fix(metadata-protocol): the destructive-change refusal names the authored forms that still edit a removed field, and a copied form's name follows its object + +Clause-②: no +Metadata-protocol: none + +The `409 DESTRUCTIVE_CHANGE` refusal of an `object` save now names an authored `form` item that still edits a field the save removes, as `{ type: 'form', name, where }` in the finding's `stillShownBy` and in its message. Before, it named only the old-shape form views (`view` items) and passed over every `form` item. A form the `form` listing projects from an old-shape `view` row is still named once, as that view. + +A package copied under a namespace of its own (the unmanaged install's `targetNamespace`, and `duplicatePackage`) now gives each `form` item the copy name of its object as the prefix of its `OBJECT.KEY` name, as it already did for `view` items: `ticket.entry` of an object `ticket` copied as `acme_ticket` is written as `acme_ticket.entry`, and a form action's `target` naming it follows it. Before, a form of an object whose name carried no namespace prefix kept the source's name, which its own `object` no longer matched. + +`FieldStillShownBySchema.type` (`@objectstack/spec/api`) now names `form` among the types it reports: `view` is a list view or a form in an old-shape view, `form` an authored form item. `DestructiveChangeIssueSchema.stillShownBy` names `form` among the `field_removed` item types, and `where` gives a `form` entry's path. Prose only; no shape changes. diff --git a/.changeset/37909-rule-message-render.md b/.changeset/37909-rule-message-render.md new file mode 100644 index 00000000000..16bf6035ee9 --- /dev/null +++ b/.changeset/37909-rule-message-render.md @@ -0,0 +1,18 @@ +--- +'@objectstack/objectql': minor +'@objectstack/spec': minor +'@objectstack/lint': minor +--- + +feat(objectql): a validation rule's refusal fills its message's `{{ }}` holes with the judged record's values + +Clause-②: yes (widening) +Metadata-protocol: semantic + +A validation rule's `message`, and the translation of it a refusal shows, is now filled when a write is refused: `{{ record.FIELD }}` shows the merged record the rule judged and `{{ previous.FIELD }}` the stored row before an update, through the template formatters (`currency`, `number`, `percent`, `date`, `datetime`, `upper`, `lower`, `trim`, `truncate`, `default`, `json`). `Total {{ record.total_price | currency }} is below what was received ({{ record.received_amount | currency }})` now reads `Total $1,200.00 is below what was received ($1,500.00)`. Before, the sentence was returned as written, holes and all. A message with no `{{` is returned exactly as before. + +- **What a hole may show.** A hole shows a field only when the person the refusal is worded for may read it unmasked, as the security service answers for that person. On an ordinary write that is the person who wrote. On an elevated write made for a person (a `runAs: 'system'` flow they started, whose refusal reaches them as the run's `innerRefusal`; an action body; an approval decision), the security service is asked for that person, with their own permission sets, never for the system; if their grants cannot be read, every hole renders empty. Only an elevated write that names no person (a schedule, a platform sweep) is answered as the system, and its sentence reaches the server log alone. A field the reader cannot read, a field masked for them, a `secret` / `password` or `internal` field, a field the object does not declare, a read through a field (`{{ record.account.name }}`) and a hole over any other root render empty. If no security service is registered, or the one registered cannot answer, answers nothing or fails, every hole renders empty and the server log says why, once per write. The rule's verdict never depends on the sentence, and no value is added to the error's other fields. +- **Formatting.** The formatters render in the refusal's language. `| currency` with no argument formats in the organization's default currency (Setup → Localization, `localization.currency`); `| currency:EUR` names one. If no default currency reaches the write (the organization has none set, or the write carried none), a `| currency` hole with no argument renders empty, the rest of the sentence renders, and a warning in the server log names the rule and the setting to fill; the amount is never formatted in a currency nobody chose. `{{ previous.FIELD }}` renders empty on an insert. +- **Translations first.** The translation for the refusal's language is filled first. A translation that does not render (one stored before `objectstack validate` judged it) is replaced by the authored message, filled, and a warning in the server log names the translation. An authored message that does not render is shown as written, as before, and the log names the rule. + +What changes for a deployed app: a rule message that already carries a `{{ record.FIELD }}` hole shows the value from this release. A message stored before `objectstack validate` judged its holes may carry one no reader can ever see filled: a hole over another root (`{{ from }}`), a bare root (`{{ record }}`), a read through a field, or a field the object does not declare. Such a hole now renders empty where it used to be shown as written, and the server log names the rule and the hole on each write that renders it. Run `objectstack validate` and rewrite each hole it names. diff --git a/.changeset/37909-rule-message-template-holes.md b/.changeset/37909-rule-message-template-holes.md new file mode 100644 index 00000000000..59ff6e33dd9 --- /dev/null +++ b/.changeset/37909-rule-message-template-holes.md @@ -0,0 +1,32 @@ +--- +'@objectstack/lint': minor +'@objectstack/spec': minor +--- + +feat(lint)!: a validation rule's message is a `{{ }}` template over the judged record, and a single brace there is refused + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** accept-set narrowing, shipped as `minor`: a validation rule's `message`, and each `objects.OBJECT._validations.RULE.message` translation, that carries a single-brace `{…}` or `${…}` token was accepted before and is refused now by `objectstack validate`, `objectstack compile` and the runtime publish gate (rule `expression-invalid`, an error; `422` on an `object`, `object_extension` or `translation` write). The schema is unchanged: `message` stays a string and the parse does not judge it, so a stored rule or bundle keeps loading and is judged at its next save. + +The message is now a `{{ }}` template (ADR-0032 §3) over the record the rule judged. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or `previous` (the stored row before an update), with an optional whitelisted formatter: `{{ record.total_price | currency }}`. The doors judge every rule message (a nested `conditional` branch's and an `objectExtensions[]` entry's included) and every translation of one with `closedScopeTemplateRefusal`, then compile it as a `template`, and refuse: + +- a single-brace `{…}` or `${…}` token, with its `{{ }}` spelling where the token names a field under `record` or `previous`; +- a hole over any other root (`{{ amount }}`, `{{ current_user.name }}`); +- a hole naming the whole root (`{{ record }}`), reading through a field (`{{ record.account.name }}`), or naming a field the object does not declare (`{{ record.totl }}`, with the nearest field named); +- a hole holding logic or an unknown formatter. + +Filling the holes at run time is the next change on this card; until it lands, a hole that passes the doors is returned as written. + +- **Exports.** `@objectstack/spec/data` gains `VALIDATION_RULE_MESSAGE_TEMPLATE_ROOTS` (`['record', 'previous']`). The `message` describe of the six validation-rule variants and of the `_validations` translation entry now state the template. +- **The ADR-0087 ledger** gains the semantic entry `validation-rule-message-template-holes` under step 19. + +FROM → TO: + +- `message: 'Support Config must be { tier: standard|premium|enterprise, seats?: >=1 }.'` → `message: 'Support Config must name a tier (standard, premium or enterprise) and, if it sets seats, at least 1 seat.'` +- `message: 'Total {total_price} is below {received_amount}'` → `message: 'Total {{ record.total_price | currency }} is below {{ record.received_amount | currency }}'` + +One-line fix: run `objectstack validate`, then reword each refused message without braces or write each token as the `{{ record.FIELD }}` hole the finding names, in the authored message and in every translation of it. diff --git a/.changeset/37915-history-disabled-holder.md b/.changeset/37915-history-disabled-holder.md new file mode 100644 index 00000000000..abd6b248db3 --- /dev/null +++ b/.changeset/37915-history-disabled-holder.md @@ -0,0 +1,16 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/rest': patch +--- + +fix(metadata-protocol): the history of a name only disabled packages hold is not served + +Clause-②: no +Metadata-protocol: none + +`GET /api/v1/meta/:type/:name/history` naming no package, for a type stored per package (an `email_template`, a `flow`, an `agent`, …), now answers `404 RESOURCE_NOT_FOUND` for a name that only disabled packages hold. The body is the same one `GET /api/v1/meta/:type/:name` gives for that name. A disabled package holds no name, so the item read already answered not found, but the history door kept listing every version of the name, at any `?member=`. That included the history of a row stored under no package, which is that package's customization, and the history of a row that was deleted. In process, `historyMetaItem` throws the same `404`. + +- Enable the package again and the history is listed as before. +- The history naming the package (`?package=`) is unchanged. +- The rollback naming no package keeps its `409` refusal, which says to enable the package first. +- A name that an enabled package or the environment holds answers as before. diff --git a/.changeset/37926-object-picker-kept-refusal.md b/.changeset/37926-object-picker-kept-refusal.md new file mode 100644 index 00000000000..bf056eccea8 --- /dev/null +++ b/.changeset/37926-object-picker-kept-refusal.md @@ -0,0 +1,11 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +fix(app-shell): the object picker's refusal says the current object is kept when it is + +Clause-②: no +Metadata-protocol: none + +In Studio's field inspector, a Lookup's *Related object* or a roll-up's *Child object* that already has a target keeps it when the typed text names no object, but the refusal line still read "No object chosen". The line now reads "“{text}” is not an object; the current object is kept." (zh: 「“{text}”不是对象,已保留当前对象。」) whenever a stored target was kept; an empty field keeps the "No object chosen" line. `@object-ui/i18n` adds the `engine.inspector.objectPicker.notAnObjectKept` studio string in en and zh. diff --git a/.changeset/37936-depends-on-filter-key-tree.md b/.changeset/37936-depends-on-filter-key-tree.md new file mode 100644 index 00000000000..6e9c9ace553 --- /dev/null +++ b/.changeset/37936-depends-on-filter-key-tree.md @@ -0,0 +1,17 @@ +--- +'@objectstack/lint': minor +'@objectstack/spec': patch +--- + +fix(lint)!: a tree field's `dependsOn` filter key is judged like a lookup's + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + +An import scopes a reference cell by the field's `dependsOn` entries on `lookup`, `master_detail`, `user` and `tree` fields, the spec's reference types (`REFERENCE_VALUE_TYPES`, `@objectstack/spec/data`). Rule `object-field-ref-unknown` judged the filter half of a `dependsOn` entry (`param`, or the bare name) only on `lookup`, `master_detail` and `user`, so on a `tree` field a filter key that names no field, or names a field computed on read such as a `formula`, published clean and every import of the column failed its lookup. The rule now judges that position on all four types, reading the set from `@objectstack/spec/data` rather than restating it, so a tree field's filter key is refused at `error` on `os validate` and at the runtime publish gate, against the object that declares the tree. A tree field that names no `reference` is judged against its own object too, the self-reference the registry stamps on it, so the runtime publish gate refuses it on the raw body it receives. `lookupColumns` and `lookupFilters` are still judged only on the three picker types. + +To fix a refused entry, point `param` at a stored field of the object that declares the tree, written as `{ field: 'this_record_field', param: 'stored_field' }`, fix the misspelt name, or drop the entry. + +The `dependsOn` description in `@objectstack/spec` now names every reference type it scopes, and the ADR-0087 ledger gains the semantic entry `lookup-depends-on-param-computed-field-refused-on-tree`. + + diff --git a/.changeset/37958-studio-overview-full.md b/.changeset/37958-studio-overview-full.md index f710b14a4f2..e3f1b508ae6 100644 --- a/.changeset/37958-studio-overview-full.md +++ b/.changeset/37958-studio-overview-full.md @@ -13,7 +13,7 @@ A package's 概览 Overview in App Studio is now the full page. - **Export** is a button of the page header and has left the ⋯ menu. On a read-only package that has customizations (a `.custom` package paired with it), the button reads "Export customizations of NAME" (「导出 NAME 的定制」) and downloads that `.custom` package; the read-only package itself is no longer exported from this page. On any other package it reads "Export" and downloads the package, as before. - **Publish history** is a third tab (`?tab=history`): the package's publishes, newest first, each with what it was, when, how many items and who published it, by the user's name where the user directory has one. "Revert to last publish" is on this tab with the confirmation it always had, and has left the ⋯ menu. An entry has no revert of its own here. - On a read-only package with customizations, the history and the revert act on the `.custom` package, the same one Pending and Publish act on. The revert is greyed only where nothing can be published (a read-only package with no customizations) or nothing is pending, and it says which. -- The ⋯ menu keeps "Edit package info", "Duplicate as a new package", "Adopt loose items" and "Manage in Setup…". +- The ⋯ menu keeps "Edit package info", "Duplicate as a new package" and "Manage in Setup…". - **Opening a package lands on 概览.** The address `/studio/` and App Studio's return to the package last opened now open `/studio//overview`; both opened the object list before. `/studio//data` still opens the object list, and the other retired addresses keep their redirects. - The 「全部类型」 All types page says what is switched off beside what is customized: "3 customized · 2 switched off on HotCRM" (「HotCRM 已定制 3 项 · 已停用 2 项」). With nothing switched off the line is unchanged. - **Read-only reasons reach keyboard and screen-reader users.** The lock beside a read-only package's name in the package switcher is named by the reason, and the switcher button is described by it, in the collapsed column too. On a read-only package with nothing to publish, the Pending tab is described by the same reason and says it in words when opened. diff --git a/.changeset/38045-quick-actions-no-record.md b/.changeset/38045-quick-actions-no-record.md new file mode 100644 index 00000000000..c3cdf579701 --- /dev/null +++ b/.changeset/38045-quick-actions-no-record.md @@ -0,0 +1,27 @@ +--- +'@objectstack/spec': minor +'@object-ui/plugin-detail': minor +'@object-ui/app-shell': minor +'@object-ui/i18n': minor +--- + +**BREAKING** (unreleased protocol 19 only): a `record:quick_actions` bar's own `location` no longer accepts `record`. + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + +On an action, `record` says what the action acts on: one record, drawn on the record page and on each list row. A bar sits in one place and draws that place's actions, so a two-place word is no answer to "which place is this bar". A bar at `location: 'record'` matched only the actions that declare `record` literally, left out every `record_page` action and skipped the ⋯ fold a bar at `record_page` applies: an empty or wrong bar, with no message. + +- `@objectstack/spec`: `RecordQuickActionsProps.location` is `RecordQuickActionsLocationSchema`, every action location except `record`. `location: 'record'` on the bar is refused at parse with a prescription that names `record_page`. A retired word on the bar (`record_header`, `list_item`, `list_toolbar`, `record_more`, `global_nav`) gets a prescription written for a bar, naming the one place to write and never offering `record`. The protocol-19 upgrade step `action-locations-page-parts-retired` now says that a bar's own `location` takes one place only. New exports: `RecordQuickActionsLocationSchema` and its type `RecordQuickActionsLocation`. `record` on an action's own `locations` is unchanged, and so are `action:group` and `action:bar`. +- `@object-ui/plugin-detail`: the bar's registration publishes the same set as its `location` enum, so `sdui.manifest.json` and JSX page validation no longer offer `record` on the bar. +- Studio (`@object-ui/app-shell`): the bar's location dropdown is typed against `RecordQuickActionsLocation`, so it offers exactly the set the spec accepts. The `record` option is gone. +- `@object-ui/i18n`: the option's labels (`Record · page and rows`, 「记录 · 页面与行」) are removed from both catalogues. + +Migration — only a bar written against a 19.0.0 prerelease can carry the word; no protocol-18 source can, and the `action-locations-acted-on` conversion never writes it on a bar (it maps a bar's `record_header` to `record_page`, and leaves a bar at `record_more` as stored with a TODO): + +| Wrote | Write instead | +|---|---| +| `{ type: 'record:quick_actions', properties: { location: 'record' } }` on a record page | `location: 'record_page'`, or leave the key out (it is the bar's default). The bar draws the record page's actions, the ones placed at `record` included. | +| the same bar meant for the list rows | `location: 'record_row'` | + + diff --git a/.changeset/38120-kanban-text-lane-past-page.md b/.changeset/38120-kanban-text-lane-past-page.md new file mode 100644 index 00000000000..dece093780f --- /dev/null +++ b/.changeset/38120-kanban-text-lane-past-page.md @@ -0,0 +1,10 @@ +--- +'@object-ui/plugin-kanban': patch +--- + +fix(kanban): a list view board laned by a text field draws its "Uncategorized" lane when every record with no value sits past the first page, and loads the rest of a lane's cards with "Load more" + +Clause-②: no +Metadata-protocol: none + +A list view hands its kanban one page of the view's query, and on a board laned by a text field the grouped lane read already counts each whole lane. The trailing "Uncategorized" lane was drawn only by the cards it held, so when every record with no value, or an empty one, sat past the first page those records had no lane on the board; and a lane that counted 30 records while drawing the page's 13 offered no way to load the rest. Both now behave as on a board laned by a lookup: "Uncategorized" is drawn last from the read's count with the "Cards not loaded" line, and a lane that draws fewer cards than it counts offers "Load more", reading its next records under the view's filter, order and search ("Uncategorized" reads the records whose value is empty or blank). A source with no grouped door, or a read that is refused or cut, draws the page's cards as before. A text value whose records all sit past the page still draws no lane of its own. Boards laned by a field's options already page each lane under a list view and are unchanged. Nothing to migrate. diff --git a/.changeset/38150-adopt-orphans-door-retired.md b/.changeset/38150-adopt-orphans-door-retired.md new file mode 100644 index 00000000000..8c527b2ba0b --- /dev/null +++ b/.changeset/38150-adopt-orphans-door-retired.md @@ -0,0 +1,37 @@ +--- +'@objectstack/spec': major +'@objectstack/metadata-protocol': patch +'@objectstack/runtime': patch +'@objectstack/client': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(runtime)!: `POST /api/v1/packages/:id/adopt-orphans` is retired; loose items move by an explicit selection through `POST /api/v1/packages/:id/move-in` + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING.** The all-at-once adoption of every loose (package-less) item into one package is gone, with every surface that reached it. It rebound rows with a bare storage update and asked none of the save door's questions, so it could adopt into a package nothing installed, adopt an object its target's namespace prefix refuses, and leave the runtime serving the old address until a restart (#37468). ADR-0084's amendment of 2026-11-26 replaces it with one door that moves a selection, each item through the save door: `POST /api/v1/packages/:id/move-in`, shipped in the same release. + +What is removed: + +- the route `POST /api/v1/packages/:id/adopt-orphans` (it answers `404` now), and its route-ledger row; +- the client method `packages.adoptOrphans(id)` of `@objectstack/client`; +- the protocol method `reassignOrphanedMetadata` of `@objectstack/metadata-protocol`'s `ObjectStackProtocolImplementation`; +- `ReassignOrphanedMetadataResponseSchema` and its `ReassignOrphanedMetadataResponse` / `ReassignOrphanedMetadataResponseParsed` types from `@objectstack/spec/api`, and the published JSON schema `api/ReassignOrphanedMetadataResponse.json`; +- the operation-message key `packages_orphan_adoption_unsupported` (four locales); +- in the console, the Packages page's "Adopt loose items" button and its dialog, and the matching item of Studio's 「⋯」 package menu, with the `engine.packages.detail.adopt*` keys of `@object-ui/i18n`'s studio namespace (`adoptOrphans`, `adopting`, `adoptTitle`, `adoptDescription`, `adoptedOne`, `adoptedOther`). The console's door to move loose items is the move-in confirm step on Studio's cross-package list (`?source=loose`), which ships in the same release. + +How to move: + +| before | after | +|:--|:--| +| `POST /api/v1/packages/:id/adopt-orphans` | `POST /api/v1/packages/:id/move-in` with `{ "items": [{ "type": "flow", "name": "…" }, …] }` | +| `client.packages.adoptOrphans(id)` | `client.packages.moveIn(id, { items })` | +| `protocol.reassignOrphanedMetadata({ targetPackageId })` | `protocol.moveIntoPackage({ targetPackageId, items })` | +| `ReassignOrphanedMetadataResponseSchema` | `MoveIntoPackageResponseSchema` | + +The fix in one line: name the loose items to move; to move them all, list them and pass every one. The move is whole or nothing, and `dryRun: true` answers what it would do without writing. diff --git a/.changeset/38150-move-loose-items-console.md b/.changeset/38150-move-loose-items-console.md new file mode 100644 index 00000000000..c7d2e36a84f --- /dev/null +++ b/.changeset/38150-move-loose-items-console.md @@ -0,0 +1,16 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(app-shell): select loose items on Studio's cross-package list and move them into a package; the Packages page counts them + +Clause-②: yes (widening) +Metadata-protocol: none + +The console's half of the move door (`POST /api/v1/packages/:id/move-in`, ADR-0084's amendment of 2026-11-26: "Loose items stay where they are, and one door moves them"). + +- Studio's cross-package list of a type (`/studio/~all/metadata/TYPE`) offers a "Loose" source value (`?source=loose`): the items bound to no package, and only those. An item of a package's `.custom` pair and an overlay of a shipped item are not loose, though the list's "Modified and new" value holds them. +- Under "Loose", a person who may author metadata gets a select box per row, "Select all", and "Move into package…". The package is picked in the create's ask (the packages the server says they may write, or a new one), with nothing pre-selected. +- The confirm step reads the door's dry run. It shows each item and what its addresses become (`_env/NAME` → `NAMESPACE/NAME`, the name AI clients list it under), or each refused item with the door's own code and sentence. When a moved item uses a loose item the selection leaves behind, it offers to add that item and check again. Move makes the move, whole or nothing. The confirm says that a save check that runs only on the real move can still refuse an item, and that reverting the move's package commit takes the items out of the package rather than making them loose again. +- The Packages page (Setup → Packages, and its development face) shows "N items belong to no package" while there are any, counted per type, each count a link to that type's "Loose" list. It is drawn for a person who may author metadata. diff --git a/.changeset/38150-studio-org-entry-retired.md b/.changeset/38150-studio-org-entry-retired.md new file mode 100644 index 00000000000..55e051e814f --- /dev/null +++ b/.changeset/38150-studio-org-entry-retired.md @@ -0,0 +1,48 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +'@object-ui/i18n': patch +--- + +feat(app-shell)!: Studio's package-less scope (`/studio/~org`) is retired and its addresses land on the Loose list of flows; in the App Studio list an item of a package you can write reads "New" + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +Two changes to App Studio, both carrying out ADR-0084's amendment of 2026-11-26. + +**Studio's package-less scope is retired.** The scope listed the flows that belong to no package ("Organization flows", 「组织流程」) at `/studio/~org`. The amendment retires it once the door that moves a selection of loose items into a package has shipped. It has: the door is the "Loose" source value of Studio's cross-package list (`/studio/~all/metadata/TYPE?source=loose`), where a person selects loose items of any type and moves them into a package. The same amendment retired the all-at-once adoption of loose items; that went in a change of its own (objectstack#38545), with its own entry. With the scope gone too, an item that belongs to no package is listed, and moved into a package, on the Loose list. + +- Every `/studio/~org/…` address still opens. It lands on the Loose list of flows, `/studio/~all/metadata/flow?source=loose`. That is one target for the scope's list, a flow's own address and its `/history`, the old `/studio/~org/automations` deep links, and a `?package=~org` link on another address. The list's search (`q`) and sort (`sort`) are kept and every other query key is dropped. A flow's old address lands on the list, not on the flow. +- A flow that belongs to no package is found on that list, and its row opens the flow's page at `/studio/~all/metadata/flow/NAME`. It no longer opens in the flow designer; move it into a package to design it there. A package's address that names such a flow opens the same page. +- Studio's left menu has no "Organization flows" row any more (it sat under Automation, inside the Advanced fold on a package), and Studio's command palette no longer lists it. A package-less flow that the app's command palette finds opens its page. +- The scope's "Changes" row and the batch publish behind it are gone. A draft that belongs to no package is published by Home's "Publish all", or published or discarded on its own page. +- A person who can enter Studio but cannot open Setup → Packages, and has no recent package, lands on the Loose list of flows. They landed on the package-less scope before. Home's "New blank app" leads the same person to the same list. +- On the "package not found" page, the way out for a person who cannot open Setup → Packages reads "Open loose flows" (「打开散落的流程」) and opens that list. It read "Open organization flows" (「打开「组织流程」」). + +**In the App Studio list, an item of a package you can write reads "New" (「新建」).** The list's Source column drew an item of a package authored in Studio as "System-shipped" (「系统自带」), because such an item is served under its package's id, as an item a code package ships is. The list now also reads the package list's `writable` verdict, which the server computes: an item of a writable package reads "New". The source filter and its counts, and the previous / next order of an item's page, read the same classification, so "Modified and new" holds those items and "System-shipped" does not. An item of a read-only package still reads "System-shipped", and a customized one still reads "Modified". Setup's metadata list is unchanged: it shows the source as served. + +**BREAKING**: nine keys leave the `studio` namespace of `@object-ui/i18n`, in `en` and `zh`. The retired scope was their only reader. + +- `engine.studio.menu.orgFlows` +- `engine.studio.pkg.orgScope` +- `engine.studio.org.name` +- `engine.studio.org.hint` +- `engine.studio.org.description` +- `engine.studio.org.none` +- `engine.studio.publishedAllFlows` +- `engine.studio.publishedAllFlowsOne` +- `engine.studio.changes` + +If a deployment overrides one of these keys (in its own i18next resources, or a Studio catalogue it registers), the override no longer applies: nothing in the console or Studio asks for the key. Remove the override. `engine.studio.notFound.allMetadata` keeps its key and changes its text, as above; an override of it still applies, and now names the link to the Loose list. + +For a host that declares the `/studio` routes itself, the two names `@object-ui/app-shell` exported for the scope are replaced: + +| before | after | +|:--|:--| +| `STUDIO_ORG_SCOPE_SEGMENT` | `RETIRED_ORG_SCOPE_SEGMENT`. The segment `~org` stays reserved: it can name no package | +| `studioOrgScopePath()` | `retiredOrgScopeTarget(search)`, the one address every `/studio/~org/…` address lands on | + +The fix in one line: link to `/studio/~all/metadata/flow?source=loose` where a link opened `/studio/~org/…`. Old links keep working through the redirect. diff --git a/.changeset/38153-ui-skill-kanban-group-field-rule.md b/.changeset/38153-ui-skill-kanban-group-field-rule.md new file mode 100644 index 00000000000..16e96bb90d7 --- /dev/null +++ b/.changeset/38153-ui-skill-kanban-group-field-rule.md @@ -0,0 +1,10 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): the objectstack-ui kanban section names the rule that judges a board's group field + +Clause-②: no +Metadata-protocol: none + +`skills/objectstack-ui/rules/list-views.md`: the kanban example no longer carries the comment "a select field" beside `groupByField`. The note under the example now says to group by a single-valued `select`, boolean or lookup, and names the warning a text, number or date field or a multi-valued one gets, `list-view-kanban-group-field-uncategorical`. The sentence that listed `summary`, `showFieldLabels` and `hideEmptyFields` as optional is gone: the example's comments and the `summary` note already say so. No token ceiling moves. diff --git a/.changeset/38191-form-view-taxonomy-modal-size.md b/.changeset/38191-form-view-taxonomy-modal-size.md new file mode 100644 index 00000000000..d2cdc48f731 --- /dev/null +++ b/.changeset/38191-form-view-taxonomy-modal-size.md @@ -0,0 +1,10 @@ +--- +'@object-ui/types': patch +--- + +docs(types): the `ObjectFormSchema` key taxonomy lists `modalSize` as a tombstone on the spec form view + +Clause-②: no +Metadata-protocol: none + +The key taxonomy in the `ObjectFormSchema` doc comment, which ships in the package's `.d.ts`, listed `modalSize` among the keys that share a name and meaning with the spec `FormViewSchema`. `@objectstack/spec` 19.0.0 retires `modalSize` from the form view (ADR-0049), so the comment now lists it under the ObjectUI extensions, beside `drawerSide` and `drawerWidth`: a tombstone on the spec form view that the React `ObjectForm` block keeps as its own prop. No type changes. diff --git a/.changeset/38247-install-pending-suggestion.md b/.changeset/38247-install-pending-suggestion.md new file mode 100644 index 00000000000..0d31a9e1476 --- /dev/null +++ b/.changeset/38247-install-pending-suggestion.md @@ -0,0 +1,15 @@ +--- +'@objectstack/cloud-connection': patch +'@objectstack/cli': patch +--- + +fix(cloud-connection): the install-local answer names the pending Everyone suggestion an `isDefault` permission set leaves + +Clause-②: no +Metadata-protocol: none + +A managed `POST /api/v1/marketplace/install-local` of a package declaring a permission set with `isDefault: true` answered "App is now available in this runtime" and said nothing about the set being only suggested for every signed-in member. Installing never accepts the suggestion (ADR-0090 D5), so until a `manage_metadata` holder does, a member without a grant of the set is refused on what it grants. + +The answer now carries `pendingSuggestions`: one element per suggestion of the installed package (or of a member of the composed artifact it installed) that the deployment's record holds `pending` for the Everyone position. Each element has the advisory shape of `advisories` (`rule: 'audience-binding-suggestion-pending'`, `severity: 'warning'`, `where`, `path`, `message`, `hint`) plus `suggestionId`, `packageId`, `permissionSet` and `anchor`. The `hint` says where to accept it: Grant on the package's page in the console's Marketplace, or `POST /api/v1/security/suggested-bindings/:id/confirm`. The list is read through the security service's own suggestion listing, which reconciles the record before it reads, so an accepted, dismissed or baseline suggestion is never named. The install accepts nothing. The key is omitted when nothing is pending, when the body declares no `isDefault` set, and when the composition has no security service. A listing that throws is logged once at `warn` with its cause, and the install still succeeds. While a suggestion is pending, the answer's `note` says the app is available only to members holding one of its permission sets. + +`os package install` (and so `os deploy`) prints each pending set with its package and the `hint`, after the install summary. An answer without the list prints nothing new. diff --git a/.changeset/38249-inline-lines-hand-lock-edit-state.md b/.changeset/38249-inline-lines-hand-lock-edit-state.md new file mode 100644 index 00000000000..701b2421593 --- /dev/null +++ b/.changeset/38249-inline-lines-hand-lock-edit-state.md @@ -0,0 +1,12 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(app-shell): the record page greys Edit on a hand-locked document whose inline lines are locked too + +Clause-②: yes (widening) +Metadata-protocol: none + +The record page's Edit was always live on an object whose field groups place an inline child collection, because the edit form still edited its lines. Now that a parent's whole-record hand lock (`uiReadonlyWhen`) locks those lines as well, Edit goes off with the state-lock reason when the lock holds over the record, every header field the form draws is read-only, and no field of any placed child object owns a hand lock that could open a line cell. Without a child object's definition, or when a child field declares a `uiReadonlyWhen` of its own, Edit stays live as before. + +Additive: the exported `editFormLockedByState` takes an optional fourth argument, `childObjectDef` (a child object name to its served definition); callers that omit it behave as before. diff --git a/.changeset/38249-inline-lines-hand-lock-form.md b/.changeset/38249-inline-lines-hand-lock-form.md new file mode 100644 index 00000000000..54bbab75f31 --- /dev/null +++ b/.changeset/38249-inline-lines-hand-lock-form.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-form': patch +--- + +fix(plugin-form): a parent's whole-record hand lock locks its inline master-detail lines in the edit form + +Clause-②: yes (widening) +Metadata-protocol: none + +The master-detail edit form now reads the parent object's `uiReadonlyWhen` (the whole-record hand lock) over its lines too. While it holds over the parent record, a person adds, duplicates, removes or reorders no line, the per-row editor is not offered, and every line cell is locked unless its child field declares a hand lock of its own (`uiReadonly: true` or a `uiReadonlyWhen`), which then judges that cell instead — the same override the object level already reads. So a child field whose own `uiReadonlyWhen` is the constant `false` keeps that one cell editable on a confirmed order; `uiReadonly: false` is not such a declaration. A create is not judged. A fully configured entry (typed columns and the relationship field, so no child schema is read) has every line cell locked while the parent lock holds. REST, import, action and flow writes are unchanged: nothing on the server reads either key. + +New export `childLinesOpenUnderParentHandLock`, from the package root and from `@object-ui/plugin-form/core`: whether a child object's lines can still be edited under a locked parent (some child field owns a hand lock that is not static). diff --git a/.changeset/38256-semantic-entries-step-19.md b/.changeset/38256-semantic-entries-step-19.md new file mode 100644 index 00000000000..cb4aca1667d --- /dev/null +++ b/.changeset/38256-semantic-entries-step-19.md @@ -0,0 +1,12 @@ +--- +'@objectstack/spec': patch +--- + +fix(spec): 34 more upgrade-guide entries that first ship in protocol 19 are listed under 19, so `os migrate meta --from 18` shows them and runs their conversions + +Clause-②: no +Metadata-protocol: none + +Thirty-four ADR-0087 semantic entries were filed under protocol major 18 although none of them shipped in an 18.x release: each landed after `@objectstack/spec` 18.6.0 and first shipped in 19.0.0-next.0. The migration chain from 18 runs only the steps above 18, so an 18.x app upgraded with `os migrate meta --from 18` was never shown these notes. They now sit in the protocol 19 step, with ids and text unchanged, and the 18 → 19 upgrade lists them. + +Three of those retirements also carry a D2 conversion from the same window, and they move with their entries: `object-grid-single-click-edit-removed` (an `object-grid` component's `singleClickEdit`), `view-column-state-removed` (a view's `columnState`) and `field-inline-edit-boolean-removed` (a relationship field's boolean `inlineEdit`). Filed under 18, `os migrate meta --from 18` did not apply them, so an 18.x source that still wrote one of those keys came out of the migration with it and was then refused at parse. Under 19 the 18 → 19 migration deletes them. Stored rows already replayed them and are unaffected, and so are built artifacts that declare a protocol range below 19. A built artifact whose range is a bare `^19` and that still carries one of the three keys was refused at ingestion, because the artifact door replays a retired conversion for a `19.0.0` floor only when its step is 19; it is now converted on ingestion instead. The conversions run in the same order as before. The three keys' parse refusals now point at `os migrate meta --from 18` (was `--from 17`), the replay that applies them, and `KnowledgeChunk.metadata`'s tombstone now says it was removed in 19.0.0 (was 18). The four retired-key rows from the same window (`ai/KnowledgeChunk:metadata`, `ui/ObjectGridProps:singleClickEdit`, `ui/ViewItemWire:columnState`, `ui/ViewMetadata:columnState`) move to major 19 too, so those tombstones age from the major that first carries them, and the upgrade text for the four retirements moves from the protocol 18 section to the protocol 19 one. No schema, export or stored row changes. Nothing to migrate. diff --git a/.changeset/38270-upload-retry-transient-only.md b/.changeset/38270-upload-retry-transient-only.md new file mode 100644 index 00000000000..b44f5e686f1 --- /dev/null +++ b/.changeset/38270-upload-retry-transient-only.md @@ -0,0 +1,15 @@ +--- +'@object-ui/data-objectstack': patch +'@object-ui/types': patch +--- + +fix(data-objectstack): a byte upload the storage refuses for good fails at once instead of being re-sent whole three more times + +Clause-②: no +Metadata-protocol: none + +`createObjectStackUploadAdapter` retried every failure of the byte upload but an abort, so a refusal that cannot change on a resend (403 for an expired signature, 413 for a file too large, 401 `INVALID_TOKEN` for an expired local upload token) sent the whole file three more times and waited about 3.5 s before the same error reached the user. The byte upload is now retried only on a transient failure: no HTTP answer (a network error), or a status in `TRANSIENT_STATUS` from `@object-ui/types` (408, 425, 429, 502, 503, 504). Any other refusal throws at once, on both the fetch and the XHR path, and an abort is still never retried. A 500 is not retried either, as `TRANSIENT_STATUS` already decides, so an occasional S3 `500 InternalError` on a direct upload now fails at once rather than being re-sent. + +The refusal now carries the server's error `code` beside its `status` when the answer was the declared error envelope, as the presign and completion refusals already did, so `uploadFile` / `uploadFiles` report it as `serverCode`. + +`UploadOptions.maxRetries` in `@object-ui/types` now documents which failures it counts. No type changes. diff --git a/.changeset/38276-wizard-create-server-lock.md b/.changeset/38276-wizard-create-server-lock.md new file mode 100644 index 00000000000..9ac1af400c4 --- /dev/null +++ b/.changeset/38276-wizard-create-server-lock.md @@ -0,0 +1,10 @@ +--- +'@object-ui/plugin-form': patch +--- + +fix(plugin-form): a create wizard's final-submit required check no longer judges a field's server lock `readonlyWhen` + +Clause-②: no +Metadata-protocol: none + +On a CREATE wizard the final-submit gate now drops a field's `readonlyWhen`, as the form renderer already does on a create (ADR-0163, "The server lock": a conditional lock is not judged on a create). Before, a `readonlyWhen` that was TRUE over the new record's values made the gate skip that field's required check, so the wizard sent a create with the required field empty and the person met the server's refusal after the last step instead of the field's own required mark. An EDIT wizard still judges the lock: a locked field is not demanded. diff --git a/.changeset/38288-meta-etag-translation.md b/.changeset/38288-meta-etag-translation.md new file mode 100644 index 00000000000..cec0931fe53 --- /dev/null +++ b/.changeset/38288-meta-etag-translation.md @@ -0,0 +1,12 @@ +--- +'@objectstack/rest': patch +--- + +fix(rest): the cached `GET /meta/:type/:name` validator moves when the served translation moves + +Clause-②: no +Metadata-protocol: none + +The default by-name metadata read (the cached door, `metadata.enableCache: true`) computed its `ETag` from the stored document and the locale, and translated the item only after judging `If-None-Match` against it. A client revalidating after a translation edit was answered `304` and kept the old labels; a client that read the item during a translation fault was answered `304` after the fault cleared and kept the `translationWarning`. + +The door now translates the item on every request before it judges the request, and folds what the translation contributed (the translated item, and the `translationWarning` of a fault) into the validator. A translation edit, a fault that begins and a fault that clears each answer `200` under a new `ETag`; an unchanged translation still revalidates to `304`. A read whose translation changes nothing keeps the `ETag` it had before. The translated answer itself is not cached. diff --git a/.changeset/38290-longest-passage-setting-label.md b/.changeset/38290-longest-passage-setting-label.md new file mode 100644 index 00000000000..436dae1b9a3 --- /dev/null +++ b/.changeset/38290-longest-passage-setting-label.md @@ -0,0 +1,12 @@ +--- +'@objectstack/service-settings': patch +--- + +fix(service-settings): the Knowledge page names `chunk_target` for what it is, the longest passage + +Clause-②: no +Metadata-protocol: none + +The Knowledge settings page labelled `knowledge.chunk_target` **Target chunk size**, while its help text, and the splitter that reads it, treat it as a maximum: no passage is longer, and many are shorter (under the `markdown` split, a section that fits is one passage of whatever length it has). The label now reads **Longest passage (characters)**, and the help text adds that passages can be shorter, in every locale the page ships (en, zh-CN, zh-Hant, ja-JP, ko, de, es-ES, fr, pt-BR, ru, ar). Earlier notes that name **Target chunk size** (the splitter, the knowledge skill) mean this same setting under its old label. The key, its default (800), its bounds and what reads it are unchanged. + +What to do: nothing. A script or seed that writes `knowledge.chunk_target` keeps working. diff --git a/.changeset/38302-ai-draft-discard-never-published.md b/.changeset/38302-ai-draft-discard-never-published.md new file mode 100644 index 00000000000..115f9793789 --- /dev/null +++ b/.changeset/38302-ai-draft-discard-never-published.md @@ -0,0 +1,11 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +fix(app-shell): the AI-draft line's discard says it deletes an item that was never published + +Clause-②: no +Metadata-protocol: none + +Studio's AI-draft line (「放弃 AI 的改动」) titled its discard "go back to the live version" on every item. An item that was never published has no live version, and dropping its draft deletes it. The line now takes a `published` reading from its host and, for an item with none, titles the discard and words the unsaved-edit confirm as a delete (`engine.studio.aiDraft.discardTitleUnpublished`, `engine.studio.aiDraft.discardConfirmUnsavedUnpublished`, en and zh). A host that cannot tell keeps the live-version wording. diff --git a/.changeset/38316-rest-write-refusal-vary.md b/.changeset/38316-rest-write-refusal-vary.md new file mode 100644 index 00000000000..1325f85077d --- /dev/null +++ b/.changeset/38316-rest-write-refusal-vary.md @@ -0,0 +1,9 @@ +--- +"@objectstack/rest": patch +"@objectstack/types": patch +--- + +Clause-②: no +Metadata-protocol: none + +A `/data` create, update, delete or query refusal that carries a `userMessage` now sends `Vary: Accept-Language`, as the `/data` reads and the runtime dispatcher already did. A shared cache in front of those routes can no longer hand one caller's refusal sentence, in its language, to a caller asking in another. Status, code and body are unchanged. In `@objectstack/types`, the `answerVariesByLanguage` module note now names the `/data` CRUD and query routes as asking it (comment only). diff --git a/.changeset/38319-migrate-helper-refusal-names.md b/.changeset/38319-migrate-helper-refusal-names.md new file mode 100644 index 00000000000..8da3b405daa --- /dev/null +++ b/.changeset/38319-migrate-helper-refusal-names.md @@ -0,0 +1,12 @@ +--- +'@objectstack/cli': patch +--- + +fix(cli): `os migrate meta --write` names the input that blocks a composed package, and the items a site sits in + +Clause-②: no +Metadata-protocol: none + +In a `composeStacks([…])` project, a site in package N is written only while every input before it is a stack literal, because only then can the command count which input built package N. When an earlier input is built by a helper, the site is still refused (`not written [helper]`), but the reason used to be that earlier input's own one ("the value is built by `createServiceStack(…)`, not written as a literal"), which read as if that input had built the site. It now says which input of `composeStacks(…)` built package N is unknown, names the earlier input that blocks the count and why, and keeps the refusal kind. A site in a package whose own input is helper-built still names that input's builder, as before. + +Each mechanical change left for the author is also printed with the items its path indexes into, by name, in a line such as: where packages[6] is `com.acme.sales`, permissions[3] is `sales_rep`. The path itself, the `--json` output and which sites are written do not change. diff --git a/.changeset/38322-console-pending-confirmation.md b/.changeset/38322-console-pending-confirmation.md new file mode 100644 index 00000000000..bc3bbfea6cc --- /dev/null +++ b/.changeset/38322-console-pending-confirmation.md @@ -0,0 +1,15 @@ +--- +'@object-ui/plugin-chatbot': patch +'@object-ui/app-shell': patch +--- + +feat(console): the chat reads the in-app `pending_confirmation` answer beside the stored `pending_approval` one + +Clause-②: yes (widening) +Metadata-protocol: none + +The in-app assistant's pending answer is moving from `{ status: 'pending_approval', pendingActionId }` to `{ status: 'pending_confirmation', pendingId }` (`ActionConfirmationPending` in `@objectstack/spec/contracts`). The console now draws the approval card for either answer: `detectPendingApproval` is the one recogniser for both, and each status pairs with its own id key only, so `pending_confirmation` with `pendingActionId` (or `pending_approval` with `pendingId`) is not read as a pending answer. A conversation stored with the old answer still shows its approval card, and Approve and Reject still reach its item. The id still arrives on the tool invocation as `pendingActionId`. + +The chat's local message cache keeps the shape it writes for a pending approval; a live `pending_confirmation` answer goes through it and back to an approval card unchanged. + +What widens: the public `detectPendingApproval` export of `@object-ui/plugin-chatbot` (and `@object-ui/plugin-chatbot/core`) now also recognises `{ status: 'pending_confirmation', pendingId }`, an input it refused before; its signature and return type are unchanged. Nothing changes on the server, in the routes or in the spec, and no export is added or removed. diff --git a/.changeset/38337-moved-reference-links.md b/.changeset/38337-moved-reference-links.md new file mode 100644 index 00000000000..0b9b4be7788 --- /dev/null +++ b/.changeset/38337-moved-reference-links.md @@ -0,0 +1,13 @@ +--- +'@objectstack/core': patch +'@objectstack/runtime': patch +'@objectstack/rest': patch +'@objectstack/cli': patch +--- + +docs: README links and the `os test` error point at the platform reference tables' new home + +Clause-②: no +Metadata-protocol: none + +The platform and wire-contract reference tables (kernel, api, qa and six others) are no longer pages on objectstack.ai. They are published as markdown in the repository, under `packages/spec/docs/references/`. The "API Reference" links in the `@objectstack/core`, `@objectstack/runtime` and `@objectstack/rest` READMEs now open those folders directly, without the redirect hop. When `os test` refuses a file that is not a valid Quality Protocol suite, its `Reference:` line now names the suite table's URL, `packages/spec/docs/references/qa/testing.md` on GitHub. Before, it named a docs file that no longer exists. Nothing an author can write changed. diff --git a/.changeset/38340-studio-help-strings.md b/.changeset/38340-studio-help-strings.md new file mode 100644 index 00000000000..3121a6b995d --- /dev/null +++ b/.changeset/38340-studio-help-strings.md @@ -0,0 +1,11 @@ +--- +'@objectstack/spec': patch +'@objectstack/platform-objects': patch +--- + +fix(i18n): help text that names Studio reads App Studio, and 应用搭建 in Chinese + +Clause-②: no +Metadata-protocol: none + +Five help texts in App Studio's own forms still named the surface "Studio": the object form's Related Lists help, the tool form's Label help, the email template form's Variables help, and the email template object's Label and Managed By help. They now say "App Studio" in English and 应用搭建 in the Chinese bundles (zh-CN, and 應用搭建 in zh-Hant), the name ADR-0084's 2026-11-26 amendment gives the surface. The capability registry's `studio.access` row now carries the label "App Studio Access" and says "App Studio" in its description, the same label the Console's own language packs already show. Only display text changes: the `studio.access` name, the `/studio` address and every identifier stay as they were. Other locales keep their current text. diff --git a/.changeset/38344-restored-card-end-states.md b/.changeset/38344-restored-card-end-states.md new file mode 100644 index 00000000000..81598470986 --- /dev/null +++ b/.changeset/38344-restored-card-end-states.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-chatbot': patch +--- + +fix(plugin-chatbot): a restored chat approval card whose action was approved, executed, failed or held elsewhere shows that outcome instead of Approve and Reject + +Clause-②: no +Metadata-protocol: none + +A chat approval card restored from a saved conversation now reads every settled row the way the card reads the same outcome after its own press, with no buttons: an `executed` row reads "Approved — action executed.", a `held` row reads "Waiting for approval", a `failed` row reads the row's `error` (or "Action approved but execution failed."), and an `approved` row with no outcome recorded yet reads "Approving…", never as a write that happened. A lapsed row still reads "Expired" and a row a person rejected still reads as that rejection; a row still `pending`, or a read that gets no answer, keeps the buttons; a decision made on the card meanwhile is never overwritten. + +The row reads are bounded per conversation: `useHitlInChat` reads the first awaiting card's row by id (`GET …/pending-actions/:id`), then the other cards' rows through one list read filtered to that row's `conversation_id` (`GET …/pending-actions?conversationId=…`, the filter the AI Approvals inbox sends). A card the list does not answer falls back to its own item read. A host whose tests script `fetch` in call order sees, for a conversation with two or more awaiting cards, the item read of the first card followed by one list read. diff --git a/.changeset/38351-markdown-fitting-section.md b/.changeset/38351-markdown-fitting-section.md new file mode 100644 index 00000000000..64126637c38 --- /dev/null +++ b/.changeset/38351-markdown-fitting-section.md @@ -0,0 +1,21 @@ +--- +'@objectstack/service-knowledge': minor +'@objectstack/spec': minor +'@objectstack/platform-objects': minor +--- + +feat(service-knowledge): under the `markdown` split, a section that fits is one passage + +Clause-②: no +Metadata-protocol: semantic +Skills-docs: follow-up owed — skills/objectstack-ai/SKILL.md + +On `split.strategy: 'markdown'`, a section was cut as `recursive` cuts, and its pieces were merged only while the merged piece stayed shorter than `minChars` (default 200). A section that fit `maxChars` but held several paragraphs of 200 characters or more was therefore cut into several passages, so a search hit only part of an article. + +Now a section whose text, together with the heading path it is given, fits the effective `maxChars` and the embedder's token budget is one passage, whatever `minChars` is (`minChars: 0` included). Only a section that does not fit is cut as before, with `minChars` merging its short pieces; such a section gives exactly the passages it gave before. The text before the first heading, and a heading's text before its first sub-heading, are sections and follow the same rule. `recursive` and `whole` are unchanged. The `@objectstack/spec` docblocks, the `minChars` description and the knowledge source form's help text now say this, and the Setup bundles in `@objectstack/platform-objects` carry the new help text (regenerated for en, re-translated for zh-CN, ja-JP and es-ES); no key, value or default changes. + +Which passages change: on `markdown` sources only, the passages of sections that fit but were cut. Each such section becomes one passage, so a table and its note inside a fitting section are always one passage. + +The `markdown` split algorithm version stays 2: this change rides the version move to 2 that the body-less heading fix already makes in this release train, so every `markdown` source rebuilds once for both, not twice. + +What to do: nothing. diff --git a/.changeset/38363-mcp-asker.md b/.changeset/38363-mcp-asker.md new file mode 100644 index 00000000000..209fa805149 --- /dev/null +++ b/.changeset/38363-mcp-asker.md @@ -0,0 +1,13 @@ +--- +'@objectstack/mcp': patch +'@objectstack/runtime': patch +--- + +feat(mcp): `get_current_user` tells an MCP client's model who is signed in + +Clause-②: yes (widening) +Metadata-protocol: none + +The `/mcp` route lists a new read-only tool, `get_current_user`, for an API key, a session and an OAuth token that grants `data:read`. It answers the caller's own facts: their user id and name, their active organization, and their primary business unit (`sys_user.primary_business_unit_id`) followed by each parent unit up to the top of the tree, each with its `name` and `kind`. Every read runs as the caller through the data API's permissions, row-level security and field masking, so a unit the caller may not read is left out (never named) and `businessUnitNote` says where the chain stops, or that no primary unit is recorded; a read that fails for any other reason fails the call with its coded error rather than reading as a permission limit. It takes no argument and answers nothing about any other user. A deployment with no business units answers the user and organization. + +Where the tool registers and neither the host nor the operator writes the `initialize` text, that text gains one sentence pointing the model to the tool; the sentence is the same for every caller. `@objectstack/mcp` exports the answer's types, `McpCurrentUser` and `McpBusinessUnitFact`, for a host that implements `McpDataBridge.currentUser`. The stdio transport does not list the tool. The identity is resolved by one runtime function that any later door needing the asker's identity can reuse. diff --git a/.changeset/38369-knowledge-held-without-embedder-or-store.md b/.changeset/38369-knowledge-held-without-embedder-or-store.md new file mode 100644 index 00000000000..8b776b1b964 --- /dev/null +++ b/.changeset/38369-knowledge-held-without-embedder-or-store.md @@ -0,0 +1,28 @@ +--- +'@objectstack/service-knowledge': minor +'@objectstack/core': patch +'@objectstack/mcp': patch +'@objectstack/spec': patch +--- + +feat(service-knowledge)!: a knowledge service the runtime mounts holds its sources without an embedder or its deployment store + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for a self-hosted deployment whose knowledge service the runtime mounts (the stack declares `requires: ['knowledge']` or ships a `knowledgeSources` entry) and which, at boot, has no embedder or no deployment knowledge store mounted. Such a deployment used to start its boot build, record sync and reconcile job, list `search_knowledge` on MCP, and answer every build and search with an error from a stand-in embedder; a source on a store the application registered was built and searched with no embedder saved. Mounted is not enabled now (ADR-0161 K8, the dated note on item 12): the service is enabled by configuration, read once at `kernel:bootstrapped`, and without both halves every source is held, whichever store it names. + +- **`@objectstack/service-knowledge`.** `KnowledgeServicePlugin` takes `runtimeComposed: { declared }`. When set, the plugin reads the embedder and the deployment store at `kernel:bootstrapped`; without both, `KnowledgeService` holds every source: loaded and listed, never built, synced, reconciled or searched. It hands out no `search_knowledge` definition while the reading is pending or held; `search`, `rebuildSource` and `reindexSource` answer `503` with code `SERVICE_UNAVAILABLE` and a message naming the missing half and the fix; a dropped source keeps its index and no store is called. No lifecycle reap guard registers until the reading is enabled, so a retention sweep deletes rows on time. The boot logs one line: info when only a shipped source mounted the service and nothing was saved, warn when the stack declares `requires: ['knowledge']`, a saved embedder provider builds nothing (a provider saved without its key), or the store is missing. Never a boot refusal. +- **`@objectstack/core`.** The capability composition passes `runtimeComposed: { declared }` with the knowledge service's deployment adapter; `declared` is true only when the stack lists `knowledge` in `requires`. +- **`@objectstack/mcp`.** The stdio transport registers `search_knowledge` at `kernel:listening`, after the reading, only when the service hands out its definition; clients are told by `notifications/tools/list_changed`. A held service is never listed on either transport. +- **`@objectstack/spec`.** The upgrade guide carries the `knowledge-service-held-without-embedder-or-store` entry. + +Unchanged: a knowledge service a host mounts itself (`KnowledgeServicePlugin` in `plugins[]`, no `runtimeComposed`) boots, builds and serves as before; a deployment with both halves builds, syncs and serves as before; stored sources are not rewritten or refused. + +## FROM → TO + +- A deployment with knowledge sources and no embedder → save an embedder provider on the AI settings page (or register an `embedder` service from a plugin), then restart. +- A deployment whose boot says its knowledge store is not mounted → mount that store, then restart. +- An application whose own store embeds without the kernel's embedder → mount `KnowledgeServicePlugin` itself in `plugins[]`. diff --git a/.changeset/38369-knowledge-save-refused-while-held.md b/.changeset/38369-knowledge-save-refused-while-held.md new file mode 100644 index 00000000000..49338060b9c --- /dev/null +++ b/.changeset/38369-knowledge-save-refused-while-held.md @@ -0,0 +1,26 @@ +--- +'@objectstack/service-knowledge': minor +'@objectstack/metadata-core': patch +'@objectstack/spec': patch +--- + +feat(service-knowledge)!: an author's knowledge source save is refused while the knowledge service is not enabled + +Clause-②: no (narrowing) — a save door that answered 200 while the service was held now refuses with 503 naming each missing half; no key added +Metadata-protocol: narrowed + + + +**BREAKING** for an author saving a `knowledge_source` on a self-hosted deployment whose knowledge service the runtime mounts (the stack declares `requires: ['knowledge']` or ships a `knowledgeSources` entry) and which, at boot, has no embedder or no deployment knowledge store mounted. Such a save used to be accepted while every source was held (ADR-0161 K8, the dated note on item 12): kept, listed, and never built, synced or searched. It is now refused where it is made, naming the half that is missing. + +- **`@objectstack/service-knowledge`.** While the boot read the service as not enabled, `KnowledgeService.admitAuthoredSource` refuses an author's save `503` with code `SERVICE_UNAVAILABLE`, ahead of every other gate. With no embedder the remedy is "save an embedder provider, restart, then save the source" (a provider saved without its key names that cause beside it); where the deployment's store is not mounted it says so, that the boot's log names the reason, and "mount the deployment's knowledge store, restart, then save the source"; with both missing it names both. Every door that saves one answers it: `PUT /meta/knowledge_source/:name` on both transports, the MCP `save_metadata_draft` tool, and `POST /packages/:id/move-in` of a package-less source. Nothing is written. The package duplicate (`door: 'duplicate'`) is not refused for it, and the engine's own write (a package install, a seed, a migration) is admitted, so a shipped source still installs and is held. +- **`@objectstack/metadata-core`.** On a deployment that runs no knowledge service, the save's refusal now also says to save an embedder provider after the restart that mounts the service, and to restart again, before saving the source: the service `requires: ['knowledge']` mounts serves only once an embedder is configured. The package duplicate's sentence is unchanged. +- **`@objectstack/spec`.** The upgrade guide carries the `knowledge-source-save-refused-while-knowledge-service-not-enabled` entry. + +Unchanged: a knowledge service a host mounts itself (`KnowledgeServicePlugin` in `plugins[]`, no `runtimeComposed`) and a deployment with both halves admit a save as before; stored sources are not rewritten or refused. + +## FROM → TO + +- An author's source save refused because no embedder is configured → save an embedder provider on the AI settings page (or register an `embedder` service from a plugin), restart, then save the source. +- Refused because the deployment's knowledge store is not mounted → mount the store the boot log names, restart, then save the source. +- Refused because the deployment runs no knowledge service → add `requires: ['knowledge']`, restart, save an embedder provider, restart again, then save the source. diff --git a/.changeset/38371-starter-namespace-biz.md b/.changeset/38371-starter-namespace-biz.md new file mode 100644 index 00000000000..a62808494dd --- /dev/null +++ b/.changeset/38371-starter-namespace-biz.md @@ -0,0 +1,10 @@ +--- +'@objectstack/example-starter': patch +--- + +refactor(example-starter): the Starter app's namespace is now `biz` (was `starter`) + +Clause-②: no +Metadata-protocol: none + +Every API name that carried the `starter_` prefix now carries `biz_`: the objects `starter_company` → `biz_company` and `starter_contact` → `biz_contact`, the app `starter_app` → `biz_app`, the dashboard `starter_overview_dashboard` → `biz_overview_dashboard`, and the datasets `starter_company_metrics` → `biz_company_metrics` and `starter_contact_metrics` → `biz_contact_metrics`, with their translation keys in both locales. The manifest id stays `com.example.starter`, and the package name and display name are unchanged. No alias is kept: the Starter installs unmanaged, as a copy the organization owns, so an environment that already installed it keeps its `starter_*` objects as they are. diff --git a/.changeset/38372-starter-help-articles.md b/.changeset/38372-starter-help-articles.md new file mode 100644 index 00000000000..87ebf5c5688 --- /dev/null +++ b/.changeset/38372-starter-help-articles.md @@ -0,0 +1,11 @@ +--- +'@objectstack/example-starter': patch +'create-objectstack': patch +--- + +feat(example-starter, create-objectstack): help articles in the Starter app and the blank template + +Clause-②: no +Metadata-protocol: none + +The Starter app and the project `npm create objectstack` scaffolds now start with help articles: an Article object (`biz_article` in the Starter, `_article` in a new project) with a title, a Markdown body, a category (How-to, FAQ, Reference) and a status (Draft by default, Published), a grid of every article, an Articles entry in the menu between Contacts and Tasks, and four sample articles of generic office help (setting up a laptop, a Wi-Fi and printing FAQ, a meeting rooms reference, and a draft on sharing files). Each sample body opens with the article's title as a `#` heading, then one `##` section per topic. The Starter labels the articles in English and Simplified Chinese; a new project's labels are the English ones in its source. A new project also gains `src/data/`, the sample rows seeded on each boot, listed by name in `data` in `objectstack.config.ts`. Neither app declares a knowledge source. diff --git a/.changeset/38377-retire-split-algorithm-version.md b/.changeset/38377-retire-split-algorithm-version.md new file mode 100644 index 00000000000..6aa53e77b76 --- /dev/null +++ b/.changeset/38377-retire-split-algorithm-version.md @@ -0,0 +1,24 @@ +--- +'@objectstack/service-knowledge': patch +--- + +refactor(service-knowledge)!: `SPLIT_ALGORITHM_VERSION` is retired — the index fingerprint reads the split version per strategy + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a host that imports `SPLIT_ALGORITHM_VERSION` from `@objectstack/service-knowledge`. It leaves at once, with no alias. The index fingerprint (ADR-0161 K7) stopped reading it when the split version became per strategy: each strategy (`whole`, `recursive`, `markdown`) carries its own version inside the splitter, and the fingerprint reads the version of the source's resolved strategy. The constant changed nothing a host could observe, and bumping it rebuilt nothing. + +This retirement replaces the earlier note in this same release that `SPLIT_ALGORITHM_VERSION` keeps its name and its value: it is removed. + +No fingerprint changes and no index is rebuilt when this lands. + +## What leaves, and what to write instead + +| FROM | TO | +|:--|:--| +| `SPLIT_ALGORITHM_VERSION` | delete the import from `@objectstack/service-knowledge`; to tell whether a stored index is current, compare its fingerprint with `computeIndexFingerprint` or `indexExpectation`, which read the per-strategy version | + +What to do: delete the import where a host has one. Nothing else. diff --git a/.changeset/38385-action-runner-features-root.md b/.changeset/38385-action-runner-features-root.md new file mode 100644 index 00000000000..f3a9a3f3173 --- /dev/null +++ b/.changeset/38385-action-runner-features-root.md @@ -0,0 +1,10 @@ +--- +'@object-ui/react': patch +--- + +fix(react): an action gated on a deployment feature shows when that feature is on + +Clause-②: no +Metadata-protocol: none + +An action declared with `requiresFeature` (its `visible` gets a `features.` conjunct at parse time), or with a hand-written `features.*` gate, was hidden in the Console even when the feature was on: the action runner evaluated it without the deployment's `features` flags, so the predicate faulted and the action hid fail-closed, with an `[ActionEngine] … predicate threw` warning in the browser console. On a deployment with two-factor sign-in on, "Enable Two-Factor Auth" never appeared on a user's own record. `useActionEngine` and `ActionProvider` now bind the predicate scope's `features` onto the runner beside `current_user`, so these gates answer from the served flags: the action shows while its feature is on and stays hidden while it is off. Nothing changes for an action with no feature gate. diff --git a/.changeset/38392-studio-doors-overview.md b/.changeset/38392-studio-doors-overview.md new file mode 100644 index 00000000000..02b599caec6 --- /dev/null +++ b/.changeset/38392-studio-doors-overview.md @@ -0,0 +1,10 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(app-shell): every door into a package's Studio opens its 概览 Overview + +Clause-②: no +Metadata-protocol: none + +Opening a package's Studio now lands on its 概览 Overview page from every door, the way the bare package address and Studio's own entry already did. The doors that still opened the object list now open the Overview: the command palette's (⌘K) package entries, an app's Design in Studio (the app header's bridge where the page is the app's root, a system page or an interface list with none chosen), the "Open in App Studio" of an app whose menu is empty, and in Setup → Packages the detail sheet's "Open in Studio", the landing after New Package and the customizations section's "Customize in Studio". The object list keeps its address, `/studio//data`, for anyone who wants it. diff --git a/.changeset/38411-cjk-keyword-pieces.md b/.changeset/38411-cjk-keyword-pieces.md new file mode 100644 index 00000000000..85462be9043 --- /dev/null +++ b/.changeset/38411-cjk-keyword-pieces.md @@ -0,0 +1,16 @@ +--- +'@objectstack/knowledge-turso': patch +'@objectstack/knowledge-pgvector': patch +'@objectstack/service-knowledge': patch +--- + +fix(knowledge): the keyword leg of hybrid search ranks passages for a Chinese, Japanese or Korean question written without spaces + +Clause-②: yes (widening) +Metadata-protocol: none + +Before, the keyword leg split a query only at white space and punctuation, so an unspaced question such as 「出差住宿费2000元以下需要审批吗」 was one term. A passage matched only if it held the whole question, so the keyword leg ranked nothing and hybrid search answered from the vector leg alone. + +Now `keywordTerms` in `@objectstack/knowledge-turso` and `@objectstack/knowledge-pgvector` (one rule, kept identical) cuts a run of Han, kana or Hangul inside a term into overlapping pieces of three characters and of two. A run of two characters is one piece, and a run of one is dropped. Figures and codes next to a run stay whole terms (`2000`, `X-200`). Latin-script queries get exactly the terms they had before. The cap stays at 16 terms, filled in this order: figures, codes and words; then pieces of three characters and runs of two; then pieces of two characters. Each piece is matched as before: a piece of three characters through the libSQL trigram index or `ILIKE`, a piece of two through `LIKE` / `ILIKE`. The per-term inverse document frequency weights pieces that most passages hold low. Nothing changes in the index or the fingerprint, and no reindex is needed. On PostgreSQL, a substring term without a cased letter (a Han, kana or Hangul piece, a figure) is now matched by `LIKE` instead of `ILIKE`. Case folding could find nothing more for such a term, and `LIKE` returns the same rankings at a fraction of the cost. + +`@objectstack/service-knowledge/testing`: `KnowledgeAdapterContractOptions.implements` gains an optional `keywordLeg` member (absent means `false`). When an adapter declares it, the shared contract suite asks an unspaced question and expects the passage holding the question's figure and exception words to be ranked. Existing callers need no change. diff --git a/.changeset/38411-cjk-separator-marks.md b/.changeset/38411-cjk-separator-marks.md new file mode 100644 index 00000000000..073029d4cf6 --- /dev/null +++ b/.changeset/38411-cjk-separator-marks.md @@ -0,0 +1,11 @@ +--- +'@objectstack/knowledge-turso': patch +'@objectstack/knowledge-pgvector': patch +--- + +fix(knowledge): the keyword leg keeps 々, 〆 and 〇 inside an unspaced run + +Clause-②: no +Metadata-protocol: none + +`keywordTerms` in `@objectstack/knowledge-turso` and `@objectstack/knowledge-pgvector` split a query at the whole CJK symbols block, so the iteration mark 々 (U+3005), the closing mark 〆 (U+3006) and the ideographic zero 〇 (U+3007) cut a run of Han text. With a run of one character dropped, 「人々」 gave no keyword term, and 「二〇二四年」 lost the pieces holding its first figure. The three marks now belong to an unspaced run: 「人々」 is one piece, 「二〇二四年」 gives 「二〇二」, 「〇二四」 and the rest. 「、」, 「。」 and the brackets still split terms. Matching is unchanged. On libSQL a piece is matched by the trigram index (three characters) or `LIKE` (two). On PostgreSQL a piece is matched as a substring, by `LIKE` when it holds no cased letter and by `ILIKE` otherwise. A piece made only of 〆 also counts as a substring term there, never as a `tsvector` word. No index or fingerprint change, no reindex. diff --git a/.changeset/38411-cjk-symbol-block-letters.md b/.changeset/38411-cjk-symbol-block-letters.md new file mode 100644 index 00000000000..73bc57c5d1f --- /dev/null +++ b/.changeset/38411-cjk-symbol-block-letters.md @@ -0,0 +1,11 @@ +--- +'@objectstack/knowledge-turso': patch +'@objectstack/knowledge-pgvector': patch +--- + +fix(knowledge): the keyword leg keeps the letters and numbers of the CJK symbols block inside a term + +Clause-②: no +Metadata-protocol: none + +`keywordTerms` in `@objectstack/knowledge-turso` and `@objectstack/knowledge-pgvector` split a query at every character of the CJK symbols block (U+3000–303F) except 々, 〆 and 〇. The block also holds other letters and numbers: the vertical iteration mark 〻 (U+303B), the kana repeat marks 〱–〵 (U+3031–3035), the mark 〼 (U+303C) and the Hangzhou numerals 〡–〩 and 〸–〺 (U+3021–3029, U+3038–303A). Each of them cut the term it sat in, and a run of one character is dropped, so 「人〻」 gave no keyword term. Now only the members of the block that are neither a letter nor a number split terms: 「人〻」 is one piece, and 「第〢〣号」 gives 「第〢〣」, 「〢〣号」 and the pieces of two. 「、」, 「。」 and the brackets still split terms. The two stores keep one identical split class. Matching is unchanged. No index or fingerprint change, no reindex. diff --git a/.changeset/38413-knowledge-batch-sync.md b/.changeset/38413-knowledge-batch-sync.md new file mode 100644 index 00000000000..caeb075efe2 --- /dev/null +++ b/.changeset/38413-knowledge-batch-sync.md @@ -0,0 +1,14 @@ +--- +'@objectstack/service-knowledge': patch +--- + +fix(service-knowledge): a bulk import or bulk update reaches search in batches, and a large backlog is reconciled instead of chased + +Clause-②: yes (widening) +Metadata-protocol: none + +Record sync used to read, embed and write one record per queue message, and the database queue handed those messages over ten a second, one at a time, so search trailed a bulk import of tens of thousands of records by hours. Where the composed queue has `IQueueService.subscribeBatch` (the platform's database queue does), the record-sync worker now takes up to 100 messages per call: the messages of one source are synced with one re-read of their rows under the source's `where`, one split, one store `upsert` (the embedder splits it into its provider's requests) and one `delete` for the records no row matches, under one index fingerprint. Several messages for one record sync it once. If a batch's write fails, its records are synced again one by one, so a record that cannot be synced is retried and dead-lettered alone while its neighbours are indexed. A queue without `subscribeBatch` keeps per-message delivery, unchanged. Messages stay identifiers only. + +When a source's estimated backlog reaches 5,000 waiting record syncs and 5 % of the source's rows (the estimate is the queue's waiting count times the source's share of the batch in hand), the worker schedules one reconcile of that source (the complete build with skip and purge) and keeps syncing while it walks; it never waits for it. Once a complete build of the source (that reconcile or any other) ends `done` with its purge run, a waiting message published more than 5 seconds before it began completes without a read, as `covered`. A build that ended `done` without purging (a store that does not list its documents, or a listing that failed) covers no message, so a waiting delete is still synced. After a backlog reconcile ends `done`, the next one for that source waits at least 10 minutes; after one that does not, the next waits 5 minutes, doubling to an hour. A source whose store does not list its documents is never reconciled for a backlog. `KnowledgeRecordSyncOutcome` gains `covered`, also answered by the per-message path. `KnowledgeService` gains `processRecordSyncBatch` (the worker's batch body), and `processRecordSync` takes the message's publish time as an optional second argument. The batch item and result types, `KnowledgeRecordSyncBatchItem` and `KnowledgeRecordSyncBatchResult`, are exported. + +The waiting count the `index_status` action and `os knowledge status` show is now exact above 10,000 messages (the database queue's `getQueueSize`). diff --git a/.changeset/38413-queue-batch-consume.md b/.changeset/38413-queue-batch-consume.md new file mode 100644 index 00000000000..d6cfe93a57e --- /dev/null +++ b/.changeset/38413-queue-batch-consume.md @@ -0,0 +1,15 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-queue': patch +--- + +feat(queue): an optional batch-consume member on `IQueueService`, implemented by the database queue + +Clause-②: yes (widening) +Metadata-protocol: none + +`IQueueService` gains an optional `subscribeBatch(queue, handler, { maxBatch })`, with the new exported types `QueueBatchHandler`, `QueueBatchOutcome` and `QueueBatchSubscribeOptions`. The handler receives up to `maxBatch` messages of one queue in one call and answers one outcome per message (`{ ok: true }`, or `{ ok: false, error }`), so a message that fails takes the retry and dead-letter path alone while its neighbours complete. A queue takes either per-message handlers or one batch handler. The member is optional: a consumer that finds it absent subscribes per message with `subscribe`, which stays correct, only slower. No existing member changes, and an `IQueueService` implementation that does not add the member keeps compiling and working. + +`DbQueueAdapter` implements it. A batch-consumed queue is drained by a loop of its own: each tick claims up to `maxBatch` due rows, renews every claimed row's lease in one write while the handler runs, settles each row by its own outcome (a settling write that fails does not stop the others), and ticks again at once while a claim comes back full. A row the lease reclaim returns to a batch-consumed queue wakes that queue's loop. Every per-message queue keeps the main loop exactly as before: one message per handler call, at most `batchSize` per `pollIntervalMs`. A publish wakes only the loop of its own queue. `DbQueueAdapter.pollBatchOnce(queue)` is the test-friendly poll of one batch queue, like `pollOnce`. + +`DbQueueAdapter.getQueueSize` now counts pending rows through the engine's `count` when the engine has one (the ObjectQL engine does), so a backlog larger than 10,000 messages is answered exactly instead of stopping at 10,000. An engine without `count` is read as before. diff --git a/.changeset/38418-knowledge-sync-state-build-start.md b/.changeset/38418-knowledge-sync-state-build-start.md new file mode 100644 index 00000000000..da041c8f209 --- /dev/null +++ b/.changeset/38418-knowledge-sync-state-build-start.md @@ -0,0 +1,14 @@ +--- +'@objectstack/service-knowledge': patch +--- + +fix(service-knowledge): a build's start onto a source's existing sync-state row is recorded without a false error + +Clause-②: no +Metadata-protocol: none + +Every boot that built a knowledge source logged `[knowledge] the start of the build of source '…' was not recorded` at error, after the engine's `Insert operation failed … UNIQUE constraint failed: sys_knowledge_sync_state.id` warning, although the row was written. An operator rebuild failed the same way. The start was written by the row's id alone, which the engine runs as a by-id update answering the record, not a count; the record read as "no row changed", and the fallback insert hit the primary key. + +The start is now written by id and read by the by-id answer: the record means the row was updated, and `RECORD_NOT_FOUND` means there is no row yet, so it is inserted. A build start onto an existing row is one update and logs nothing; onto no row it is one insert. The once-per-process sync-state error report is no longer spent on this, so a real sync-state write failure is reported again. + +Nothing to change in an app or its configuration. diff --git a/.changeset/38419-knowledge-source-save-absent-reference.md b/.changeset/38419-knowledge-source-save-absent-reference.md new file mode 100644 index 00000000000..2ee07815ea4 --- /dev/null +++ b/.changeset/38419-knowledge-source-save-absent-reference.md @@ -0,0 +1,22 @@ +--- +'@objectstack/service-knowledge': patch +--- + +fix(service-knowledge): the knowledge-source save door names an absent object or field as such + +Clause-②: no +Metadata-protocol: none + +Saving a `knowledge_source` whose `source.object` names no object, or whose `source.content` / +`source.metadataFields` names no field of its object, is now refused `400 VALIDATION_ERROR` with the rule +`os validate` reports: `knowledge-source-object-unknown` or `knowledge-source-field-unknown`. The refusal names +the object, and the field. Before, the same save was answered `503 SERVICE_UNAVAILABLE` ("could not be judged ... +try again") for an absent object, `403` "is a system object that does not opt into AI reads" for an absent `sys_` +object, and `403` "you may not query field ... hidden from you" for an absent field. With no security service, it +was admitted. + +The check reads only the object's registered definition. `id` and the system columns the registry injects count +as fields of the object. Every door that asks it admits only a `manage_metadata` holder, and that caller is already +served every object definition whole. So for an object or a field that exists, every refusal stays as it was: a +hidden field, a system object without `enable.aiReadable`, a disabled package, a security service that cannot +answer, and a registry that throws. The fields a `where` reads are not checked for existence, as in `os validate`. diff --git a/.changeset/38420-unset-switch-shows-default.md b/.changeset/38420-unset-switch-shows-default.md new file mode 100644 index 00000000000..09ab9b1a530 --- /dev/null +++ b/.changeset/38420-unset-switch-shows-default.md @@ -0,0 +1,13 @@ +--- +'@object-ui/app-shell': patch +'@objectstack/console': patch +--- + +fix(app-shell): an unset switch on a Studio metadata form shows the default its schema declares + +Clause-②: no +Metadata-protocol: none + +A switch on a Studio metadata form drew every unset value as off. Where the schema gives the key a default of `true`, that is the opposite of what runs: a knowledge source that stores neither `aiExposed` nor `refresh.onRecordChange` is searched by AI agents and kept in step with its records, while both switches read off beside help text saying "On by default". Such a switch now draws the default in effect, in edit and in read-only mode. It holds for every boolean row of a form whose schema default is `true`, among them an agent's, skill's, app's and email template's `active`, an object's capability switches such as `enable.apiEnabled`, and a dashboard header's `showTitle`. + +Nothing is written for it: an item you open and save without touching the switch still stores no value for the key and keeps following the default. Toggling the switch stores an explicit `true` or `false`, as before. A boolean with no declared default still draws off when unset, and a stored `false` draws off. diff --git a/.changeset/38433-kanban-group-hint.md b/.changeset/38433-kanban-group-hint.md new file mode 100644 index 00000000000..fdb3126ad69 --- /dev/null +++ b/.changeset/38433-kanban-group-hint.md @@ -0,0 +1,8 @@ +--- +'@objectstack/lint': patch +--- + +Clause-②: no +Metadata-protocol: none + +`list-view-kanban-group-field-uncategorical`: the hint offers a grid grouping only for a stored, single-valued field. A board grouped by a multi-valued field, a JSON-stored field (`json`, `address`, `composite` and the like) or a `formula` field is now pointed at a grid column instead, because the engine refuses to group a list by one of those (`400 INVALID_FIELD`); following the old hint produced a grid that passed `os validate` and opened on that error. `os explain` for the rule says the same, branch by branch. diff --git a/.changeset/38433-list-view-group-field-ungroupable.md b/.changeset/38433-list-view-group-field-ungroupable.md new file mode 100644 index 00000000000..35b5fcfcc71 --- /dev/null +++ b/.changeset/38433-list-view-group-field-ungroupable.md @@ -0,0 +1,23 @@ +--- +'@objectstack/lint': minor +'@objectstack/spec': patch +--- + +fix(lint)!: refuse a list view grouped by a field the engine does not group by + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: follow-up #38655 + + + +**BREAKING** for a `grid` list view (or one with no `type`, which defaults to `grid`) whose `grouping.fields[].field` names a multi-valued, JSON-stored or `formula` field: it was accepted before and is refused now, with the fix named in the finding. The schema is unchanged and stored metadata is not rewritten or refused at boot; the refusal comes at the next publish of the view (a `view` write, or an `object` write through the object's own `listViews`), and from `os validate` / `lint` / `compile` / `build`. + +- `list-view-group-field-ungroupable` (error): a grid list view's grouping level over a multi-valued field (`multiselect`, `checkboxes`, `tags`, or a `multiple` select or reference), a JSON-stored field (`json`, `address`, `composite` and the like) or a field computed on read (`formula`). A grid sends its grouping as the group header query, and the engine refuses a `groupBy` over each of these (`400 INVALID_FIELD`), so the view saved, then opened on that error and rendered no group. The verdict asks the same spec predicates the engine's two doors ask, so it refuses exactly the three storage classes the engine refuses. A dotted name is refused by the engine on another ground, which this verdict does not report (#38654). Not judged: any other list-view kind (`kanban`, `gallery`, `calendar`, `timeline`, `gantt`, `map`, `chart`, `tree`, `timesheet`), whose grouping was not measured to reach the engine, and an unknown name (`list-view-field-unknown`). + +## FROM → TO + +- FROM: a `grid` list view with `grouping: { fields: [{ field: 'labels' }] }` where `labels` is a `multiselect`, a JSON-stored or a `formula` field — saved, then the grid opened on `400 INVALID_FIELD`. +- TO: group by a stored single-valued field (`grouping: { fields: [{ field: 'status' }] }`, a single-valued `select`, a boolean, a single-valued lookup, or a text, number or date field), or drop the grouping and show the field as a grid column (`columns: [..., 'labels']`). + +`@objectstack/lint` exports the rule id constant `LIST_VIEW_GROUP_FIELD_UNGROUPABLE`, so `os explain list-view-group-field-ungroupable` carries an entry. `@objectstack/spec` adds only the upgrade-guide entry `publish-refuses-list-view-grouping-the-engine-does-not-group-by`. diff --git a/.changeset/38437-form-layered-old-shape.md b/.changeset/38437-form-layered-old-shape.md new file mode 100644 index 00000000000..1576f9bf678 --- /dev/null +++ b/.changeset/38437-form-layered-old-shape.md @@ -0,0 +1,18 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): the `form` layered and per-package reads serve a form a package still ships as an old shape + +Clause-②: no +Metadata-protocol: none + +The by-name read and the list of `form` already serve a form a package ships in its `views:` (a container's `formViews` entry or a `viewKind: 'form'` item), through the projection (`projectViewForms`, ADR-0159 D5). Two reads did not: `getMetaItemLayered` (`GET /meta/form/:name/layers`) answered `code: null`, and `effective: null` while only a stored `view` row stood over the form, and `getMetaItemsPerPackage` answered no item. So nothing could read an installed app's own document of its form while that form is still an old shape, which is every first-party form today. + +What moves (each line FROM → TO): + +- `getMetaItemLayered({ type: 'form' })`, `code`: FROM `null` when the address ships the form as an old shape TO that address's `view` code, projected (marked `_formDefinedIn: 'view'`, its `requiredPermissions` carried). +- `getMetaItemLayered({ type: 'form' })`, `effective`: FROM `null` when no `form` layer answers TO the same address's `view` effective, projected: the stored `view` row that still replaces the form, or the base's own body. A stored `form` row or an authored `form` item keeps its answer. `overlay` is unchanged: it is the stored `form` row. +- `getMetaItemsPerPackage({ type: 'form' })`: FROM the `form` items only TO those items plus the projection of the same request's per-package `view` items; an authored item shadows the projection of the same package and name. + +Response shapes are unchanged: only fields that answered `null` or `[]` now carry the item the by-name read already serves. The anonymous form doors read the per-package layer for withdrawals only, so they answer as before. Nothing to do for an upgrader. diff --git a/.changeset/38442-skill-markdown-fitting-section.md b/.changeset/38442-skill-markdown-fitting-section.md new file mode 100644 index 00000000000..79871ef0207 --- /dev/null +++ b/.changeset/38442-skill-markdown-fitting-section.md @@ -0,0 +1,18 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): `objectstack-ai` teaches that a `markdown` section that fits `maxChars` is one passage + +Clause-②: no +Metadata-protocol: none + +`skills/objectstack-ai` § Knowledge Sources (RAG), the **Splitting (`split`)** block now follows the splitter: + +- The `markdown` bullet says that a section that fits `maxChars` together with its heading path is one passage, and that a section that does not fit is cut as `recursive` cuts. +- The `minChars` sentence says that pieces shorter than `minChars` are merged in `recursive` text and in a `markdown` section that does not fit, and that a section that fits stays whole whatever `minChars` is. An author no longer sets `minChars` equal to `maxChars` to keep a short clause, or a table with its note, in one passage. +- The block's last sentence said that a changed `split` re-splits a document only when it next changes. That was wrong. It now says that changing `split` rebuilds the source's whole index, and that the source's searches are refused until the rebuild finishes. + +Cut in the same block, with no fact dropped: "For documents with headings" (the bullet's "one section per heading" says it), "once `split` is written" (the signature and the omitted-`split` clause say it) "never truncated" (the `whole` bullet's "removed from the index and reported" says it) and the "and refused" of "Retired and refused" (the `400 UNKNOWN_KEY` and the parse error beside it say it). + +The same block names the `knowledge.chunk_target` setting by its settings-page label "Longest passage", the label that setting takes in this release. diff --git a/.changeset/38445-package-docs-contents.md b/.changeset/38445-package-docs-contents.md new file mode 100644 index 00000000000..a8f0952774d --- /dev/null +++ b/.changeset/38445-package-docs-contents.md @@ -0,0 +1,18 @@ +--- +'@objectstack/mcp': patch +'@objectstack/runtime': patch +--- + +feat(mcp): a `search_package_docs` answer with no hit lists the manual pages the caller may read, so the agent can pick one by its title + +Clause-②: yes (widening) +Metadata-protocol: none + +The manual search matches words, not meanings: a user's paraphrase of a word the manual uses ("潜在客户" for a manual that says "线索") found nothing, and the agent then said the manuals do not cover it. Now an answer with no hit also carries two optional members: + +- `contents`: the pages this connection may read, within `package` when it was sent, each as the address a hit carries (`name` and `title`; `package`, `book` and `url` where the page has a package), with no excerpt. The order is the Console's: manuals in display order (authored ones first, then each package's implicit manual), and each manual's pages in the order its tree lists them. Titles and manual names are in the request's locale, as `read_package_doc` serves them. +- `contentsTruncated`: `true` when more readable pages exist than the 50 `contents` lists (`PACKAGE_DOC_CONTENTS_MAX_ENTRIES`); send `package` to narrow. + +The list is built from the same docs-audience read the search uses (ADR-0046 §6.7), so a page the caller cannot read adds no entry, no count and no flag. An answer with a hit is unchanged and carries neither member. The tool's description and the server's `initialize` answer-order rule (`packageDocAnswerRule`) now say to read the page whose title fits the question, and only when none fits to say the manuals do not cover it. No embedder is used and no manual text leaves the deployment. + +For a host implementing `McpDataBridge.searchPackageDocs` itself: the tool layer now passes `{ maxResults, maxContents }`; a member that ignores `maxContents` keeps working and answers no `contents`. The runtime's own member caps `contents` at the same 50 when a caller sends no `maxContents`, so the list is never uncapped. diff --git a/.changeset/38457-chat-steps-one-group.md b/.changeset/38457-chat-steps-one-group.md new file mode 100644 index 00000000000..cfa97e1b10c --- /dev/null +++ b/.changeset/38457-chat-steps-one-group.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-chatbot': patch +--- + +fix(plugin-chatbot): the steps of one AI answer read as one answer, with one "How this was computed" block + +Clause-②: no +Metadata-protocol: none + +The conversation store keeps each step of an agent answer as its own assistant message, so a reloaded answer that called several tools showed several prose-less messages in a row: each only a step line, some with their own "How this was computed" block. Each was spaced like a separate reply. Adjacent assistant messages with no body (no prose, chart, question, record citations or draft review) are now drawn as one group: their step lines sit at the spacing used inside a message, and the group shows one "How this was computed" block holding every step's sources in call order. A user message or an assistant message with prose ends the group, so the gap between separate turns is unchanged, and a single prose-less message renders as before. + +Nothing to migrate. diff --git a/.changeset/38458-platform-eval-case-20.md b/.changeset/38458-platform-eval-case-20.md new file mode 100644 index 00000000000..1473570efd6 --- /dev/null +++ b/.changeset/38458-platform-eval-case-20.md @@ -0,0 +1,10 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): the `objectstack-platform` always-on capabilities eval no longer fails an answer for showing the `--preset minimal` form + +Clause-②: no +Metadata-protocol: none + +`skills/objectstack-platform/evals/config-plugins-ops.json`, eval 20 (must `storage` and `settings` be listed in `requires:`?): the expected answer says the two are always-on and that under `--preset minimal` "they must be listed", while `must_not_contain` forbade `requires: ['storage', 'settings']`, the spelling of exactly that listing. An answer that got the question right and showed the minimal-preset form was graded a fail. The forbidden literal is dropped; `must_contain: ["--preset minimal"]` still requires the answer to scope the listing to that preset. The case has a new case hash, so `skill-evals --regrade` sets it apart from a round recorded before this change: compare it across rounds only after a re-run. The prompt, the expected answer and every other eval are unchanged. diff --git a/.changeset/38483-scaffold-names-articles.md b/.changeset/38483-scaffold-names-articles.md new file mode 100644 index 00000000000..609b6e845cc --- /dev/null +++ b/.changeset/38483-scaffold-names-articles.md @@ -0,0 +1,11 @@ +--- +'create-objectstack': patch +'@objectstack/example-starter': patch +--- + +fix(create-objectstack, example-starter): the scaffold summary and the descriptions name the help articles + +Clause-②: no +Metadata-protocol: none + +`npm create objectstack` now lists the help articles in the "Your project starts with:" block it prints after creating a project: an Articles line beside Companies and Contacts, pointing at `src/objects/` and `src/views/` and at the sample articles in `src/data/`. The `Template: blank — …` line it prints first, the template table and the "What you get" tree in this package's README (the tree now lists `article.object.ts` and the `src/data/` seed), the blank template's description in `objectstack.config.ts` and in `objectstack.manifest.json`, and the Starter's package description (in English and in Simplified Chinese), its app description (in English and in Simplified Chinese) and its `package.json` description now read companies, contacts and help articles, with tasks and notes from the platform in the menu. A scaffolded project still drops the template's description from its own files. diff --git a/.changeset/38503-knowledge-affinity.md b/.changeset/38503-knowledge-affinity.md new file mode 100644 index 00000000000..4065b1ebfb4 --- /dev/null +++ b/.changeset/38503-knowledge-affinity.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-knowledge': minor +'@objectstack/platform-objects': minor +'@objectstack/core': minor +'@objectstack/runtime': patch +--- + +feat(knowledge): a knowledge source orders its hits for the person asking, `source.affinity` (`nearest` by business unit, `boost` by places) + +Clause-②: yes (widening) +Metadata-protocol: added + +A `knowledge_source` may now declare how its hits are ordered for the caller: `affinity: [{ field: 'business_unit', caller: 'business_unit', mode: 'nearest' }, { field: 'owner', caller: 'user', mode: 'boost', places: 3 }]`. `nearest` puts the hits of the caller's own primary business unit first, then those of each parent unit in order, then every other hit. `boost` lets a hit whose field holds the caller's user id (`caller: 'user'`) or one of their units (`caller: 'business_unit'`) pass up to `places` hits that match nothing; `places` is a whole number from 1 to 20 (`KNOWLEDGE_AFFINITY_MAX_PLACES`, the most hits one `search_knowledge` answer carries). Several entries add. + +It re-orders by position and never by score: each hit keeps the `score` its store answered, only that source's hits move among the places they hold, nothing is dropped or added, and the move happens before the cut to `topK` (inside the refill cap, under chunk and record granularity alike). A source without `affinity`, and every search by the system identity, answers exactly as before. The caller's facts are resolved at most once per search, only when a hit in the list belongs to a source that declares an entry, and only the facts its entries read: `user` is the search's own user id and reads no row; `business_unit` reads the caller's user row and each unit up the chain as the caller may read them (a unit they may not read ends the chain), and no organization row. A fault reading the units leaves them out and keeps the `user` fact. A fact is never a tool argument or a value a client supplies. `affinity` enters neither the index fingerprint nor the recipe hash, so it rebuilds nothing (listing a new field in `metadataFields` for it does). + +The parse refuses, each with the fix: a `field` not listed in `metadataFields`; a `mode` other than `boost` or `nearest` (`filter` is answered that narrowing is the search scope and who may read a record is sharing); a `caller` other than `user` or `business_unit`; a second `nearest`; `nearest` with `caller: 'user'`; `places` missing on a `boost`, present on a `nearest`, or outside 1 to 20. Saving a source through Studio, the metadata API or MCP also refuses a `field` that does not point at `sys_user` (for `user`) or `sys_business_unit` (for `business_unit`). Studio's knowledge source form offers the key as an "Order for the asker" JSON field. + +`@objectstack/core` now exports `resolveCallerIdentity` (with `CallerIdentity`, `CallerBusinessUnit`, `CallerRecordReader` and `CALLER_UNIT_CHAIN_MAX_DEPTH`), the one resolver of the caller's own user, organization and business-unit chain that the MCP door's `get_current_user` already used; `@objectstack/runtime` now imports it from there, with no change in behaviour; through the runtime's wildcard re-export of `@objectstack/core`, the same five names are now also reachable from the root of `@objectstack/runtime`. diff --git a/.changeset/38506-kanban-text-value-past-page.md b/.changeset/38506-kanban-text-value-past-page.md new file mode 100644 index 00000000000..c0dbce94a5c --- /dev/null +++ b/.changeset/38506-kanban-text-value-past-page.md @@ -0,0 +1,10 @@ +--- +'@object-ui/plugin-kanban': patch +--- + +fix(kanban): a list view board laned by a text field draws a lane for a value whose records all sit past the first page + +Clause-②: no +Metadata-protocol: none + +A list view hands its kanban one page of the view's query. On a board laned by a text field, the grouped lane read already counted every value, but a value whose records all sat past the page got no lane: its records were counted and could not be found on the board. The board now draws that lane after the page's lanes, as it does for a lookup field, titled by the stored value itself, with its whole count, the "Cards not loaded" line and "Load more". A source with no grouped door, or a read that is refused or cut, draws the page's lanes only, as before. Boards laned by a number, boolean or date field still draw the page's lanes only. Nothing to migrate. diff --git a/.changeset/38507-rest-refusal-vary-rest.md b/.changeset/38507-rest-refusal-vary-rest.md new file mode 100644 index 00000000000..bbd0ba213bb --- /dev/null +++ b/.changeset/38507-rest-refusal-vary-rest.md @@ -0,0 +1,9 @@ +--- +'@objectstack/rest': patch +'@objectstack/types': patch +--- + +Clause-②: no +Metadata-protocol: none + +A refusal carrying a `userMessage` now says it varies by `Accept-Language` on four more REST routes: the record field projection (`GET /data/:object/:id/field-access`), the record page (`POST /data/:object/:id/page`), the global search (`GET /search`) and the public form submit (`POST /forms/:slug/submit`). The status, code and body are unchanged; the header is added in the multi-value form the hosts append, so a `Vary` another layer sets keeps its tokens. Before, a shared cache in front of these routes could serve one caller's localized sentence (the localized `404 RECORD_NOT_FOUND`, a hook refusal's own message) to a caller asking in another language. The API-key credential refusal on `sys_api_key` writes carries no `userMessage` and is unchanged. In `@objectstack/types`, the `answerVariesByLanguage` docblock now names these exits among the ones that ask it. diff --git a/.changeset/38510-keyword-idf-once.md b/.changeset/38510-keyword-idf-once.md new file mode 100644 index 00000000000..cda9bd8fa32 --- /dev/null +++ b/.changeset/38510-keyword-idf-once.md @@ -0,0 +1,10 @@ +--- +'@objectstack/knowledge-pgvector': patch +--- + +perf(knowledge-pgvector): the keyword leg computes each term's IDF once per search, not once per candidate row + +Clause-②: no +Metadata-protocol: none + +The keyword score evaluated `ln(1.0 + (n - d + 0.5) / (d + 0.5))` for every term on every candidate row. A Chinese, Japanese or Korean question carries up to 16 pieces, and a piece that most passages hold makes nearly every row a candidate, so most of a search went to those `ln()` calls. Each term's weight is now computed once, in a materialized step, and a candidate's score multiplies its hits by those weights. The arithmetic stays `numeric`, so every score, and every tie, is the one the per-row form gave: search results and their order do not change. On a 67,447-passage bench of 218 unspaced Chinese questions, keyword-leg p95 went from about 3.9 s to about 1.6 s. No extension, no index and no fingerprint change; nothing to do on upgrade. diff --git a/.changeset/38521-line-panels-parent-hand-lock.md b/.changeset/38521-line-panels-parent-hand-lock.md new file mode 100644 index 00000000000..b63b6ba52a9 --- /dev/null +++ b/.changeset/38521-line-panels-parent-hand-lock.md @@ -0,0 +1,10 @@ +--- +'@object-ui/plugin-form': patch +--- + +fix(plugin-form): a parent's whole-record hand lock locks the record page's line panels too + +Clause-②: no +Metadata-protocol: none + +The record page has two hand surfaces over a document's lines besides the edit form: the `record:line_items` panel, and the body-table editor its edit state draws. Both now read the parent object's `uiReadonlyWhen` (the whole-record hand lock), as the edit form already does. While it holds over the parent record, a person adds, duplicates, removes or reorders no line there, and every line cell is locked unless its child field declares a hand lock of its own (`uiReadonly: true` or a `uiReadonlyWhen`), which then judges that cell instead. So a child field whose own `uiReadonlyWhen` is the constant `false` keeps that one cell editable on a confirmed order; `uiReadonly: false` is not such a declaration. The panel judges the lock when the record page it sits on is its parent; until that record's row has loaded, its lines stay locked. The edit state judges the record as the user has it in the open edit. REST, import, action and flow writes are unchanged: nothing on the server reads either key. diff --git a/.changeset/38537-knowledge-document-by-validate.md b/.changeset/38537-knowledge-document-by-validate.md new file mode 100644 index 00000000000..49809a598f3 --- /dev/null +++ b/.changeset/38537-knowledge-document-by-validate.md @@ -0,0 +1,12 @@ +--- +'@objectstack/lint': patch +--- + +fix(lint): `os validate` and the publish gate refuse a knowledge source whose `documentBy` is not a single-valued parent link + +Clause-②: no +Metadata-protocol: none + +A knowledge source's `source.documentBy` (its document unit, new in this release) must name a `lookup` or `master_detail` field of the indexed object that points at each record's parent record: declared by the object, with a readable `reference`, not `multiple: true`, and neither credential-class nor `internal`. The metadata API's save door already refused any other field. New rule `knowledge-source-document-by-not-parent-link` (`error`) now refuses it in `os validate`, `os build` and `os lint`, and at the runtime publish gate, which is what judges a source a package ships or code registers. The message names the field, why it cannot be the document unit, and the fix: name the parent lookup, or remove `documentBy`. + +A `documentBy` that `metadataFields` does not list is still refused by the schema, and a field the object does not have is still reported once, as `knowledge-source-field-unknown`. `os explain knowledge-source-document-by-not-parent-link` describes the rule. diff --git a/.changeset/38537-knowledge-document-by.md b/.changeset/38537-knowledge-document-by.md new file mode 100644 index 00000000000..020e42641c7 --- /dev/null +++ b/.changeset/38537-knowledge-document-by.md @@ -0,0 +1,18 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-knowledge': minor +'@objectstack/platform-objects': minor +--- + +feat(knowledge): a knowledge source declares its document unit, `source.documentBy`; record-level search answers one hit per parent for it + +Clause-②: yes (widening) +Metadata-protocol: added + +A `knowledge_source` may now name the field that links each indexed record to the parent record it is part of: `source: { kind: 'object', object: 'policy_clause', content: ['body'], metadataFields: ['policy'], documentBy: 'policy' }`. For such a source, `search` / `search_knowledge` with `granularity: 'record'` and no `groupBy` returns one hit per parent (that parent's best passage) instead of one per record. The parent id is in the hit's `metadata[documentBy]` on `search`, and also in `groupValue` on a `search_knowledge` hit. A record with no parent is still its own hit, and two sources never share a parent. An explicit `groupBy`, `granularity: 'chunk'`, and every source without `documentBy` answer exactly as before. + +The index does not change: still one document per record. `documentBy` enters neither the index fingerprint nor the recipe hash, so setting it rebuilds nothing (listing the parent field in `metadataFields` for the first time does, as any new metadata field does). + +`documentBy` must be listed in `metadataFields`, or the parse refuses it and says to add it there. Saving a source through Studio, the metadata API or MCP also refuses a field that is not a single-valued parent link: it must be a `lookup` or `master_detail` field, not `multiple: true`, and neither a credential nor an `internal` field. A `text` or `user` field is refused, with a message naming the fix. + +Studio's knowledge source form offers the key as a "Document unit" field picker beside the filter fields (its label and help translated in the platform's metadata-form bundles). diff --git a/.changeset/38542-handle-route-error-vary.md b/.changeset/38542-handle-route-error-vary.md new file mode 100644 index 00000000000..d5c10deb7c5 --- /dev/null +++ b/.changeset/38542-handle-route-error-vary.md @@ -0,0 +1,11 @@ +--- +'@objectstack/rest': patch +'@objectstack/types': patch +--- + +Clause-②: no +Metadata-protocol: none + +A refusal carrying a `userMessage` now says it varies by `Accept-Language` on every REST route that answers its errors through the shared route error exit: the metadata reads and writes, the batch and bulk writes (`/batch`, `createMany`, `updateMany`, `deleteMany`), the data actions (clone, import, export), the approval and UI routes. The status, code and body are unchanged; the header is added in the multi-value form the hosts append, so a `Vary` another layer sets keeps its tokens. Before, a shared cache in front of these routes could serve one caller's localized sentence (the localized `404 RECORD_NOT_FOUND`, a hook refusal's own message) to a caller asking in another language. A refusal with no `userMessage` gets no `Vary` from this exit. + +In `@objectstack/types`, the who-asks note beside `LOCALIZED_ANSWER_VARY` now names the shared REST route error exit (`handleRouteError`) among the exits that ask the body; the note is documentation only, with no change to an export or its behaviour. diff --git a/.changeset/38548-db-queue-batch-writes.md b/.changeset/38548-db-queue-batch-writes.md new file mode 100644 index 00000000000..e62eb4528b7 --- /dev/null +++ b/.changeset/38548-db-queue-batch-writes.md @@ -0,0 +1,14 @@ +--- +'@objectstack/service-queue': patch +--- + +perf(service-queue): the database queue claims and settles a batch with set writes + +Clause-②: no +Metadata-protocol: none + +A queue consumed with `subscribeBatch` on the database adapter used to cost two single-row writes per message: one claim write and one settling write. It now claims each batch with one compare-and-set write over the selected ids, and marks the completed messages done with one write (one per attempt count when retried messages are mixed in). Draining 50,000 messages on a local SQLite store went from 100,000 queue writes to 1,000, and from about 64 s to about 8 s; on a remote store the saving is a network round trip per write. + +The claim now matches the rows' unclaimed state as well as their ids. Before, two nodes draining the same batch queue could both claim a message they had both read as pending, and both ran it. Now the second node's write matches nothing and each message is handled once. + +A failed message still settles alone: it keeps its own error, its own backoff and its own dead letter. A settling write for a message whose lease was lost while the handler ran no longer overwrites the state its new holder gave it. Per-message queues (`subscribe`) are unchanged. diff --git a/.changeset/38556-sync-cover-margin.md b/.changeset/38556-sync-cover-margin.md new file mode 100644 index 00000000000..f8b5d7e7bea --- /dev/null +++ b/.changeset/38556-sync-cover-margin.md @@ -0,0 +1,8 @@ +--- +'@objectstack/service-knowledge': patch +--- + +Clause-②: no +Metadata-protocol: none + +A record-sync message now completes as `covered` only when the complete build that covers it began at least 30 s (the queue adapter's default message lease) after the message was published, up from 5 s. The margin guards a sync still in flight as well as clock skew: a sync that re-read a record before a later write, and whose store write landed after the build's walk, could leave the older document in the index while the later write's message was answered `covered`. A message inside the margin is synced as usual, which is the only cost. A sync in flight for longer than the margin stays uncovered until the next build that purges. diff --git a/.changeset/38558-kanban-footer-count.md b/.changeset/38558-kanban-footer-count.md new file mode 100644 index 00000000000..ebddb26c6d8 --- /dev/null +++ b/.changeset/38558-kanban-footer-count.md @@ -0,0 +1,8 @@ +--- +'@object-ui/plugin-list': patch +--- + +Clause-②: no +Metadata-protocol: none + +A kanban board under a list view whose lanes come from the data (a lookup or text lane field) now shows the view's full record count in its footer, the same count its lanes add up to. Before, the footer counted only the first page handed to the board ("25 records" plus "Showing first 25 records") while the lanes counted every record (70). The "Showing first N" line now appears only on boards that draw only the first page's lanes (number, boolean or date lane fields, declared lanes, swimlanes, or a source with no grouped read). diff --git a/.changeset/38567-send-error-vary.md b/.changeset/38567-send-error-vary.md new file mode 100644 index 00000000000..9473eabb326 --- /dev/null +++ b/.changeset/38567-send-error-vary.md @@ -0,0 +1,10 @@ +--- +'@objectstack/types': patch +--- + +Clause-②: yes (widening) +Metadata-protocol: none + +`sendError` now says `Vary: Accept-Language` when the nested error envelope it writes carries a `userMessage`, so every REST door that re-sends a classified, localized refusal through it says its answer varies by language: Change Owner (single and bulk, including the missing record's localized `404 RECORD_NOT_FOUND`), the recycle bin, the packages routes and the analytics batch (whose house-envelope wrapper now forwards headers to the response). Before, a shared cache in front of these doors could serve one caller's localized sentence to a caller asking in another language. The status, code and body are unchanged; the header is added in the multi-value form the hosts append, so a `Vary` another layer sets keeps its tokens. A refusal with no `userMessage` gets no `Vary`. + +`EnvelopeResponse` gains an optional `header(name, value)` member, the shape `IHttpResponse.header` already has; a response object without it still satisfies the interface and simply gets no header. diff --git a/.changeset/38573-merged-list-row-binding.md b/.changeset/38573-merged-list-row-binding.md new file mode 100644 index 00000000000..545001ad0ef --- /dev/null +++ b/.changeset/38573-merged-list-row-binding.md @@ -0,0 +1,12 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): the merged metadata list files a stored row's copy under the row's package column, never under the package its body names + +Clause-②: no +Metadata-protocol: none + +`getMetaItems` (`GET /api/v1/meta/:type`) lays the stored rows over the items the `metadata` service lists. On a hosted kernel that service holds a copy of each stored row it read, and its `list` answers that copy's body, so a body whose `_packageId` named another package than the row's package column put the copy in that package's slot: the row was listed twice (once under its column, once under the body's package), a list scoped to the body's package (`?package=`) served it as that package's item, and a row with no package column was listed as the body's package's. A skill bound to one app could be listed as another app's skill. + +The merge now reads the service's items through `listPackageBindings` when the service offers it, and files each item a stored row holds under that row's column, as the stored rows themselves are served: a row bound to one package is listed once, under it, and a row with an empty column is listed under no package. An item no stored row holds keeps the package its registration files it under. A `metadata` service without `listPackageBindings` is read as before. The binding read is kept on the footing the service keeps `list` on: one answer per type, served again while the service's change counter (`revision`) stands and for no longer than the service memoizes `list`, so a read inside an open transaction (a flow re-sync during a package move) does not wait on the stored rows each time. diff --git a/.changeset/38591-reconcile-skips-pending-sync.md b/.changeset/38591-reconcile-skips-pending-sync.md new file mode 100644 index 00000000000..d3c6cdd97a3 --- /dev/null +++ b/.changeset/38591-reconcile-skips-pending-sync.md @@ -0,0 +1,10 @@ +--- +'@objectstack/service-knowledge': patch +--- + +fix(service-knowledge): a backlog reconcile asked for during a bulk import waits until the import's record syncs have drained + +Clause-②: no +Metadata-protocol: none + +When the record-sync backlog of a source is no larger than the source's rows (a bulk import or bulk update: about one message per record), the reconcile the batch worker schedules for it now starts only once that backlog has drained, and then writes only the rows no record sync reached. Before, it walked beside the drain, and since a message is covered only when it was published 30 s before the walk began, every imported record was embedded and written twice: about twice the embedding requests and twice the vector writes of a rebuild. A backlog that outnumbers the source's rows (repeated saves, rows deleted or moved out of `where`) is still walked beside the drain, as before. A queue that does not drain within an hour starts the walk anyway. No option, setting or error code changes. diff --git a/.changeset/38595-rename-flow-references.md b/.changeset/38595-rename-flow-references.md new file mode 100644 index 00000000000..ef2d07556e4 --- /dev/null +++ b/.changeset/38595-rename-flow-references.md @@ -0,0 +1,12 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): a package copied under a new namespace calls its own flows + +Clause-②: no +Metadata-protocol: none + +A package copy under a new namespace (an `unmanaged` install with `targetNamespace`, or `duplicatePackage`) renames the package's flows, `crm_child` to `crm2_child`. The names that call those flows now follow them: a `subflow` step's `config.flowName`, a translation's `flows` keys, and an action's `target` when its executor is `flow` (`type: 'flow'` on an action or an API endpoint, `actionType: 'flow'` on an `action:button` or `action:icon` page block). Before, the copy kept the source's name: its step failed on every run with "Flow not found", or, with the source package still installed, ran the source's flow. + +A value is rewritten only when it is exactly the name of a flow the copy renames. A flow the package does not hold keeps its name, and so does a `target` beside any other executor. A renamed name that meets a name the item already holds there (a translation's `flows` keyed by both `crm_child` and `crm2_child`) refuses that item, as the same meeting does for an object name. A `duplicatePackage` whose stored rows hold a calling flow before the flow it calls now copies both: the publish gate is told the flows the copy plans to write, as it already was on the `unmanaged` install, where before it refused the caller with `flow-subflow-unknown` and only the called flow was copied. When a planned flow is not copied after all (it lands in `failed[]`), every copied flow that calls it is withdrawn with it, transitively, into `failed[]` with an error naming that flow, so no copied flow calls a flow that exists nowhere. Nothing an author writes changes. diff --git a/.changeset/38609-chat-continue-turn.md b/.changeset/38609-chat-continue-turn.md new file mode 100644 index 00000000000..3ef81d37fa9 --- /dev/null +++ b/.changeset/38609-chat-continue-turn.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': minor +'@object-ui/plugin-chatbot': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(chat): a Continue control under an answer whose stopped turn the server can carry on + +Clause-②: yes (widening) +Metadata-protocol: added + +An ask turn that stops on a limit answers with what it read so far. When the server can carry that turn on, the chat now offers Continue under the answer; pressing it streams the rest of the answer into the same turn, with no new user message. + +- `@objectstack/spec`: `TurnEndSchema` and `TURN_END_PART_TYPE` (`data-turn-end`) in `/ai` — `{ reason, wrapUp, resumable, resumesLeft, turnId }`, closed. The chat request (`AiChatRequestSchema`) gains an optional `resume: { turnId }`, closed (a resume names its turn itself, so the request's top-level `turnId` is not read on it, and the resume stream's `start` carries the request's `messageId` or none), and a stored conversation message (`AiConversationMessageSchema`) an optional, nullable `turnEnd`. All three are additions; nothing an existing producer or caller sends changes meaning. +- `@object-ui/plugin-chatbot`: the message mapper reads the `data-turn-end` part through `TurnEndSchema` onto `ChatbotEnhancedMessage.turnEnd` (a part the schema refuses is no turn end; the newest part wins). `ChatbotEnhanced` takes `onResumeTurn(turnId)` and draws Continue under the conversation's last answer when its turn end is resumable with resumes left, nothing streams and the view is interactive. `useObjectChat` returns `resumeTurn(turnId)` in API mode, which sends `resume: { turnId }` with the conversation as it stands and no top-level `turnId`. The turn end is a kept data part (`STORED_ANSWER_DATA_PARTS.turnEnd`), so it survives the store rebuild. +- `@object-ui/app-shell`: the console's ask chat passes `resumeTurn` through, and a reload keeps Continue — from server history (the message's stored `turnEnd`) and from the message cache. +- `@object-ui/i18n`: the `chatbot.continueTurn.*` strings, in every locale. + +The server half — accepting `resume`, rebuilding the turn and sending `data-turn-end` — is the AI service's; until it sends the part, nothing is drawn. diff --git a/.changeset/38620-loose-prev-next-no-package-list.md b/.changeset/38620-loose-prev-next-no-package-list.md new file mode 100644 index 00000000000..d13cb9fc064 --- /dev/null +++ b/.changeset/38620-loose-prev-next-no-package-list.md @@ -0,0 +1,10 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(app-shell): Studio's record page ‹ › under the "Loose" source filter no longer ask for the package list or wait on it + +Clause-②: no +Metadata-protocol: none + +The record page's ‹ › on an item opened from the Studio list filtered to "Loose" (`source=loose`) asked for the package list and waited for its answer before they were ready, though the Loose filter reads only whether a row names a package. They now ask for it, and wait on it, only under the two source values that read a row's package verdict ("modified and new", "system-shipped"). The order ‹ › walk is unchanged. diff --git a/.changeset/38621-studio-form-followups.md b/.changeset/38621-studio-form-followups.md new file mode 100644 index 00000000000..b83b95f5624 --- /dev/null +++ b/.changeset/38621-studio-form-followups.md @@ -0,0 +1,10 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(app-shell): Studio's form row draws the form icon, and an address-clash message names the other form by its title + +Clause-②: no +Metadata-protocol: none + +Studio's menu drew the UI group's default icon on its `form` row; the row now has its own icon. The form designer's message for an address another form already uses named that form by its internal item name; it now names it by its title, as Setup's Public forms refusal does. When the other form carries the same title as the one being edited, both messages add the name of the other form's package (its id only when no name can be read), and neither shows an item name any more (Setup's refusal used to add the item name in that case). diff --git a/.changeset/38623-translation-target-door.md b/.changeset/38623-translation-target-door.md new file mode 100644 index 00000000000..56713d91cf2 --- /dev/null +++ b/.changeset/38623-translation-target-door.md @@ -0,0 +1,14 @@ +--- +'@objectstack/lint': patch +--- + +feat(lint): the metadata save door advises on a translation key nothing declares + +Clause-②: no +Metadata-protocol: none + +A `translation` item saved or published over the metadata API (Studio, REST `/meta`, an MCP or AI author) that names a key nothing declares now gets a `translation-target-unknown` advisory on the save and publish answer (`advisories`, severity `warning`). Before this, no rule ran on a `translation` write: the item was accepted as valid while `os validate` refused the same key. + +The door never refuses such a write. A published item that names a key an upgrade removed still loads and saves, and `os validate` keeps reporting it at `error`. + +The door judges only the families its per-write snapshot carries: `objects.NAME` (not when the write's package closure narrowed the objects), `objects.NAME.fields.FIELD` and the field's inline `options`, `objects.NAME._validations.RULE`, `objects.NAME._milestones.FIELD.VALUE`, and `permissions.NAME`. Every other family is not judged at the door, because the snapshot carries no collection to resolve it against. That covers apps and their navigation (platform-contributed items included), views, sections, tabs, related lists, actions, dashboards, forms, pages, picklists, positions, reports, mappings, books, flows and hooks. `os validate` still judges all of them. diff --git a/.changeset/38626-form-address-holder-details.md b/.changeset/38626-form-address-holder-details.md new file mode 100644 index 00000000000..5c894fbf59d --- /dev/null +++ b/.changeset/38626-form-address-holder-details.md @@ -0,0 +1,14 @@ +--- +'@objectstack/types': patch +'@objectstack/metadata-protocol': patch +'@objectstack/rest': patch +--- + +fix: a `409 FORM_ADDRESS_TAKEN` refusal names the form that holds the address as data, in `details.holder` + +Clause-②: yes (widening) +Metadata-protocol: none + +A `form` write left open on a public address another form holds is refused `409 FORM_ADDRESS_TAKEN`, as before, and the refusal now carries the holding form beside its message: `details.holder` is `{ name, packageId }` (`packageId` is `null` for a form bound to no package). Both doors that answer a metadata save carry it: `RestServer`'s `PUT /meta/:type/:name` in its flat body (`details.holder`) and the runtime dispatcher's `/meta` door in the nested envelope (`error.details.holder`). `@objectstack/types` exports the one recogniser, `formAddressRefusalHolder(error)`, and `resolveThrownHttpError` answers it in `details`. Setup's Public forms page names the holder from the refusal, so a list read before another form took the address no longer names the wrong form. + +Widening: `@objectstack/types` gains two exports, `formAddressRefusalHolder` and the `FormAddressRefusalHolder` type, and the `409 FORM_ADDRESS_TAKEN` body of both doors gains the `details.holder` member. diff --git a/.changeset/38630-sandbox-update-by-id.md b/.changeset/38630-sandbox-update-by-id.md new file mode 100644 index 00000000000..820ed9c7bf6 --- /dev/null +++ b/.changeset/38630-sandbox-update-by-id.md @@ -0,0 +1,28 @@ +--- +'@objectstack/runtime': patch +'@objectstack/cli': patch +'@objectstack/lint': minor +'@objectstack/spec': minor +--- + +fix(runtime,cli,lint,spec)!: a sandboxed body's `ctx.api.object(X).updateById(id, patch)` writes the row + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for two authoring doors, which now refuse at save and in `os validate` a body that calls `updateById` where they already refused the same write spelled any other way: + +| FROM | TO | +|:--|:--| +| a `type: 'script'` action whose body calls `ctx.api.object(X).updateById(…)` without `api.write` in `body.capabilities`: saved, then threw at every run | refused as `action-body-write-capability-undeclared`; declare `api.write` in the action's `body.capabilities` | +| a `runAs: 'system'` hook, or a `type: 'script'` action, whose body calls `ctx.api.object('sys_user_position' \| 'sys_user_permission_set' \| 'sys_invitation' \| 'sys_member').updateById(…)`: saved, then threw `TypeError: not a function` at every run | refused at `body.source` with the existing prescription (a `runAs: 'user'` hook or flow, or the organization endpoints) | + +Neither body ever worked: before this change both threw `TypeError: not a function`, because the sandbox did not install `updateById`. Now that the call is installed, the first is refused for its missing `api.write` (INSUFFICIENT_PRIVILEGES) and the second by the run-time security middleware, and both are also refused at save. Stored metadata is not rewritten or refused at boot; the next save of such a body is refused with the fix named. + +An action body or hook body that called `ctx.api.object(X).updateById(id, patch)` threw `TypeError: not a function` and wrote nothing, although `HookObjectApi.updateById` and `IScopedObjectRepository.updateById` declare the member, the in-process repository serves it, and the hook-bodies guide teaches it as the way an action body persists. The QuickJS sandbox now installs `updateById` beside the other write leaves, behind the same `api.write` capability, so the call writes the record the id names and answers it. `update({ id, … })` is unchanged. + +The id is judged before the host is called: anything but a non-empty string or a non-zero number (an object, an array, `null`, `undefined`, `''`, `0`) is refused with `VALIDATION_ERROR` / 400 naming the call, and nothing is written. Such ids were already refused one layer down, with messages about filters; the refusal now names the argument. To write every row a filter matches, call `update(data, { where, multi: true })`. + +`objectstack build` now infers `api.write` for a lowered handler whose only write is `updateById`, so the body it produces is granted the call. The explanation of `action-body-write-capability-undeclared` and the build's `.create()` refusal list `updateById` among the sandbox's write leaves. diff --git a/.changeset/38647-blank-scaffold-data.md b/.changeset/38647-blank-scaffold-data.md new file mode 100644 index 00000000000..1378ec3ca41 --- /dev/null +++ b/.changeset/38647-blank-scaffold-data.md @@ -0,0 +1,12 @@ +--- +'@objectstack/scenarios': patch +--- + +fix(scenarios): the gallery export no longer refuses a build that kept the `blank` scaffold's `data:` list + +Clause-②: yes (widening) +Metadata-protocol: none + +The `blank` template of `create-objectstack` declares its own sample rows in `objectstack.config.ts` (`data: [articles]`), and the gallery export refused any config that declared `data:`, so every build that kept the scaffold's config could not become a trial package. When the default-exported `defineStack({ … })` literal already declares `data:` as a list written in place, the export now keeps that list and spreads the card's seed rows in after its last item (`data: [articles, ...gallerySampleData]`): the package arrives with the scaffold's rows the build kept and the card's seed rows, and every other byte of the config is as the AI wrote it. A config with no `data:` gains the `data: gallerySampleData` property as before. + +The export still refuses, with its reason, the shapes it cannot read safely: a spread in the literal, a default export that is not `defineStack` with an object literal, a `data:` that is not an array literal (a shorthand `data`, a binding or a call), a `data:` declared more than once, and a config that already uses the import's name. diff --git a/.changeset/38649-translation-apps-door.md b/.changeset/38649-translation-apps-door.md new file mode 100644 index 00000000000..fba205f6774 --- /dev/null +++ b/.changeset/38649-translation-apps-door.md @@ -0,0 +1,19 @@ +--- +'@objectstack/lint': patch +'@objectstack/metadata-protocol': patch +--- + +fix(lint): the metadata save door judges a translation's app and navigation keys against the apps the environment serves + +Clause-②: yes (widening) +Metadata-protocol: none + +A `translation` item saved (active) or published over the metadata API now has its `apps.APP` and `apps.APP.navigation.ID` keys judged at the runtime publish gate. A key naming an app the environment does not serve, or a navigation item the served app does not have, comes back as a `translation-target-unknown` advisory (severity `warning`) on the save and publish answer. Before, the gate carried no apps, so the family was not judged at all: such an item saved with no word while `os validate` refused the same key. + +Never a refusal: every finding on a translation write is an advisory, never a 422, and no write accepted before is refused now. `os validate` keeps reporting the same key at `error`. + +The apps are the served ones: the registry's apps and the stored app rows, each with every navigation contribution folded in, the same answer `GET /meta/app` gives. So a translation of a platform app's item resolves exactly when the deployment serves that app, and a translation naming an app this deployment does not serve (Studio, in a stock boot) is reported, since nothing reads its key. A package publish judges a translation against the app drafts in the same batch. + +Only a translation write reads the apps: `runRuntimeAuthoringRules` (`@objectstack/lint/runtime`) and `evaluateRuntimeAuthoringGate` take them as a new optional `servedApps` argument, an additive widening of what those functions accept, and a batch collects its app drafts only when it carries a translation draft. Every other write type is judged exactly as before. + +Still not judged at the door, as before: views, sections, tabs, related lists, actions, dashboards, forms, pages, picklists, positions, reports, mappings, flows, hooks, and books (the implicit per-package book is named by a package id the snapshot never sees). diff --git a/.changeset/38653-extractor-transaction-handle-read.md b/.changeset/38653-extractor-transaction-handle-read.md new file mode 100644 index 00000000000..78f5c5980d7 --- /dev/null +++ b/.changeset/38653-extractor-transaction-handle-read.md @@ -0,0 +1,15 @@ +--- +'@objectstack/cli': patch +--- + +feat(cli): a lowered hook or action handler is granted `api.transaction` when it calls `ctx.api.transaction(…)`, and `api.read` when it reads through a bound object handle + +Clause-②: yes (widening) +Metadata-protocol: none + +`os build` lowers an inline hook `handler` or action `target` function to a `js` body and infers the body's `capabilities` from the calls in its source. Two calls the sandbox gates were never inferred, so a lowered handler making them was refused at the call (403 INSUFFICIENT_PRIVILEGES) on every run: + +- `ctx.api.transaction(fn)` — now infers `api.transaction`, whether it is called on `ctx.api`, on a local bound to `ctx.api` (`const api = ctx.api`), with `?.`, or after destructuring the member (`const { transaction } = ctx.api`). `api.write` stays its own grant, inferred from the writes inside the callback. +- a read through a bound handle — `const rows = ctx.api.object('x'); … rows.find(…)` — now infers `api.read`, the same way a write through a bound handle already inferred `api.write`. The other read shapes the direct pattern missed (`?.` before the leaf, an object argument holding a call) are read too. + +`ExtractedBody.capabilities`, published from `@objectstack/cli/hook-body`, widens to include `'api.transaction'` (seven tokens, the `HookBodyCapability` set of `@objectstack/spec`). A dependent with an exhaustive `switch` over the union gains one case to handle; nothing that was accepted before is refused. diff --git a/.changeset/38660-knowledge-service-split.md b/.changeset/38660-knowledge-service-split.md new file mode 100644 index 00000000000..a084aa2049e --- /dev/null +++ b/.changeset/38660-knowledge-service-split.md @@ -0,0 +1,13 @@ +--- +'@objectstack/service-knowledge': patch +'@objectstack/spec': patch +--- + +refactor(service-knowledge): `KnowledgeService` keeps its members and forwards each to the module that owns its concern + +Clause-②: no +Metadata-protocol: none + +An internal move with no behaviour change. The bodies of `KnowledgeService` now live in five modules beside it (adapters and sources; build, index state and reconcile; record sync; search; save admission and scoping), and each member of the class forwards to its body in one call. Every member keeps its name, signature and docblock, so the package's public declaration is unchanged and nothing is added to or removed from the package entry. The published bundle's code moves between chunks; the published declaration file loses only the comments of private members and lists its declarations in another order. + +`@objectstack/spec`'s `knowledge_source` liveness ledger cites each body at the module that now holds it. diff --git a/.changeset/38675-scoped-search-one-pass.md b/.changeset/38675-scoped-search-one-pass.md new file mode 100644 index 00000000000..3f6e7d3452c --- /dev/null +++ b/.changeset/38675-scoped-search-one-pass.md @@ -0,0 +1,14 @@ +--- +'@objectstack/knowledge-turso': patch +--- + +fix(knowledge-turso): a scoped search reads its passage table once a statement, and a request past its bound answers TIMEOUT, not "not ready" + +Clause-②: no +Metadata-protocol: none + +Before, a search with a record scope or a metadata filter ran its `WHERE` row by row in every part of the statement: the vector leg, the keyword leg's candidates, and the count of passages in scope behind the keyword weights. A metadata scope term reads each passage's JSON, so each of those was a pass over the whole passage table. The keyword leg's candidates were also computed twice in one statement, once for the weights and once for the ranks. On 59,621 one-passage records of 1,024 dimensions, a statement scoped to 3 policies took about 1.0 s locally, and a scoped search ran two or three such statements. On a remote libSQL (Turso) database each pass reads the table's pages over the network, and one statement went past the 10 s request bound. + +Now a scoped or filtered statement reads its `WHERE` once, into the set of the passages in scope, and every other read of the passage table is a lookup by chunk id. The keyword leg's candidates are read once. The same measurement takes about 80 ms for 3 policies and 250 to 450 ms for a unit holding 10% of the passages, and an unscoped statement about 650 ms instead of 1.2 s. The hits are unchanged. + +Any request that takes longer than `requestTimeoutMs` now answers `TIMEOUT` (504): a search, and also a write, a listing, a build step or a commit. Its message is "The knowledge store (libSQL) did not answer in time: a request to its database took longer than N ms." Before, it answered `SERVICE_UNAVAILABLE` (503) with "The knowledge store (libSQL) is not ready", which told a caller the store was down when one statement was slow. The operator text in `remedy` still names `requestTimeoutMs`. diff --git a/.changeset/38676-keyword-once-narrow-exact.md b/.changeset/38676-keyword-once-narrow-exact.md new file mode 100644 index 00000000000..eea6bd5e98a --- /dev/null +++ b/.changeset/38676-keyword-once-narrow-exact.md @@ -0,0 +1,14 @@ +--- +'@objectstack/knowledge-turso': patch +--- + +perf(knowledge-turso): the keyword leg is computed once a search, and a scope too narrow for the approximate pass goes straight to the exact scan + +Clause-②: no +Metadata-protocol: none + +Before, every vector statement of one search carried the keyword leg. When the approximate pass fell short and a wider pass or the exact scan followed, the keyword terms (up to 16, the two-character ones matched by `LIKE` over every row in scope) were matched again in each statement. Only a scope of record ids alone was checked for being too narrow for the approximate pass. A scope with a parent (metadata) term or a metadata filter always took the one-bit pass first, then often a pass over 10 times the candidates, then the exact scan. + +Now the first statement of a search computes the keyword leg, and a statement after it binds the ranks the first one answered. A scope with a parent term, or a metadata filter, has its share of the passages estimated from 256 rows of the table, read by rowid (no pass over the table). Under the same cut as a record scope (25% of the passages at the default over-fetch), it goes straight to the exact scan. On 59,621 one-passage records of 1,024 dimensions (`topK` 40, a 16-term Chinese question), a search scoped to 3 policies took about 80 ms instead of 190 ms, one scoped to a unit holding 1.7% of the passages about 150 ms instead of 310 to 680 ms, and one holding 10% about 240 ms instead of 570 to 700 ms. The hits are those of the exact scan, as before. + +The question is still embedded once per call to the adapter. The knowledge service's second round makes a second call, so it embeds the question again. diff --git a/.changeset/38685-duplicate-flow-action-withdraw.md b/.changeset/38685-duplicate-flow-action-withdraw.md new file mode 100644 index 00000000000..71e43ace759 --- /dev/null +++ b/.changeset/38685-duplicate-flow-action-withdraw.md @@ -0,0 +1,14 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): a package duplicate withdraws a copied flow action whose target flow it did not write + +Clause-②: no +Metadata-protocol: none + +`duplicatePackage` points every flow reference in a copied item at the copy's flow (a `subflow` / `map` step's `flowName`, a flow action's `target`, an `action:button` block whose `actionType` is `'flow'`). When that flow was not written — it is in `failed[]`, or it was taken back because a flow it calls failed — the close after the copy loop took back only the copied flows that called it. A copied flow action, or a page whose button runs that flow, stayed in `copied[]`, stored running a flow that exists nowhere, and answered 404 "flow not found" at run time. + +Now every copied item that names such a flow at a flow reference site is taken back the same way: its address is put back as it was, it leaves `copied[]`, and it is reported in `failed[]` naming the flow and the site (for an action, "runs flow '...' through its flow action `target`"). The sites are the rename engine's own (one internal predicate the rename and the close share), so the close withdraws exactly what the rename rewrote as a flow name. A non-flow action whose `target` happens to spell the flow's name is not a flow reference and stays copied. Two consequences of "every site": a copied translation bundle whose `flows` labels name such a flow is taken back whole, its other labels with it; and a copied object whose inline flow action runs such a flow is taken back whole, while items that name that object (a view of it) stay copied, as they do today when the registry refuses a copied object. The unmanaged import with `targetNamespace` is all-or-nothing and is unchanged. + +The fix for a caller: fix the flow named in `failed[]`, then duplicate again. diff --git a/.changeset/38690-extractor-local-alias.md b/.changeset/38690-extractor-local-alias.md new file mode 100644 index 00000000000..bbf070baaac --- /dev/null +++ b/.changeset/38690-extractor-local-alias.md @@ -0,0 +1,17 @@ +--- +'@objectstack/cli': patch +--- + +fix(cli): a lowered hook or action handler is granted the member capability it calls through a body-local alias of `ctx.log`, `ctx.crypto`, `ctx.email`, `ctx.activity` or `ctx.title` + +Clause-②: no +Metadata-protocol: none + +`os build` lowers an inline hook `handler` or action `target` function to a `js` body and infers the body's `capabilities` from the calls in its source. The member calls were inferred only when spelled off `ctx` itself (`ctx.log.info(…)`), so a handler that first took the member into a local was lowered without the token and refused by the sandbox at the call on every run, while `os validate` read the same body as granted. Now the extractor reads the same two alias shapes the publish check reads: + +- a local bound once to the member: `const l = ctx.log; l.info(…)`; +- a plain destructure off `ctx`: `const { log } = ctx`, `const { log: l } = ctx`. + +Through either, a call of `info`/`warn`/`error`/`debug` infers `log`, `randomUUID()` infers `crypto.uuid`, `send(…)` infers `email.send`, `append(…)` infers `activity.append`, and on a hook a `title(FIELD)` call with an argument infers `api.read`. A field read that is not a call, a local reassigned after its declaration, and a destructure with a default infer nothing. The `ExtractedBody.capabilities` union published from `@objectstack/cli/hook-body` is unchanged. + +As with `ctx.email.send(…)` spelled directly, a hook handler that calls `send(…)` through such an alias now carries `email.send` and is refused by the hook's parse at build time (a hook body is never granted mail), instead of shipping and failing at the call. Send mail on a record change from an action, a job or a flow. diff --git a/.changeset/38690-lint-lowered-bodies.md b/.changeset/38690-lint-lowered-bodies.md new file mode 100644 index 00000000000..a265996aed3 --- /dev/null +++ b/.changeset/38690-lint-lowered-bodies.md @@ -0,0 +1,24 @@ +--- +'@objectstack/lint': minor +'@objectstack/cli': patch +'@objectstack/spec': patch +--- + +feat(lint)!: a hook or action body beside a string `handler` or `target` is judged for every capability it calls, like any other body + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for the publish of a hook or action whose body sits beside a string `handler` or `target`, lowered by the build or written by hand, when that body calls a member the QuickJS sandbox gates without the member's token in `body.capabilities`. The rules took such a body for one the build lowered and skipped it: `hook-body-capability-undeclared` did not judge a hook body the build lowered, nor any hook body beside a string `handler` at the runtime publish doors, and `action-body-capability-undeclared` did not judge an action body beside a string `target` (its writes were judged, under `action-body-write-capability-undeclared`). Both judge it now, at the runtime publish doors and in `os validate` / `lint` / `compile` / `build`, with the token named. Such a body never worked: the sandbox refused the call with `403 INSUFFICIENT_PRIVILEGES` every time the body reached it. A body written by hand declares the token in `body.capabilities`; a build artifact is rebuilt. + +An inline `handler` or `target` function needs no change: `os build` infers the grant from each gated call the rule reads, in each spelling the rule reads. That is every gate of the rule's census through `ctx.MEMBER`, a local bound once to it, a destructure off `ctx`, a handle bound once to `ctx.api.object(…)` and a hook handler's destructured context parameter (and, past the rule, a renamed one), with `?.` or whitespace on either side of a step, the optional call `LEAF?.(…)`, and a comment between steps. Before this release `os build` read `ctx.log?.info(…)`, `ctx?.crypto.randomUUID()`, `ctx.activity?.append(…)`, `ctx.email?.send(…)`, `ctx.title?.(field)`, the same calls with whitespace or a comment between steps, and their rebound siblings as no call at all, so the handler lowered without the token and failed at the call; it now lowers with it. A hook handler that calls `ctx.email.send` in any of those spellings is refused by the hook parse at build, as `ctx.email.send(…)` already was: a hook body is never granted `email.send`. The build's reading is pinned against the rule's, spelling by spelling, by judging each one both ungranted (a finding) and lowered (none); it is a superset of the rule's reading by that enumeration, not by proof. Measured over the first-party example and connector apps, loaded, normalized and lowered as `os validate` does: no body newly refused. + +## FROM → TO + +- A hook body beside a string `handler`, written by hand or left by a build artifact. FROM: `hooks: [{ …, handler: 'my_hook_fn', body: { language: 'js', source: "const l = ctx.log; l.info('x')", capabilities: [] } }]` published clean and threw at every run. TO: refused with `hook-body-capability-undeclared` naming `log`; declare `capabilities: ['log']`, or rebuild the artifact (the build grants `log`). +- An action body beside a string `target`, written by hand or left by a build artifact. FROM: `actions: [{ …, target: 'my_action_fn', body: { language: 'js', source: 'await ctx.api.transaction(async () => { … })', capabilities: ['api.write'] } }]` published clean and threw at every run. TO: refused with `action-body-capability-undeclared` naming `api.transaction`; declare `capabilities: ['api.write', 'api.transaction']`, or rebuild it. +- An inline handler that spells a gated call with `?.`. FROM: `handler: async (ctx) => { ctx.log?.info('x'); }` lowered to `capabilities: []` and failed at the call. TO: it lowers to `capabilities: ['log']` and runs. + +`os explain hook-body-capability-undeclared` and `os explain action-body-capability-undeclared` no longer say a lowered body is exempt. `@objectstack/lint` now exports `SANDBOX_CAPABILITY_GATES` and its `SandboxCapabilityGate` type, the sandbox's gate census the rule judges by. `@objectstack/spec` adds only the upgrade-guide entry `lowered-hook-and-action-bodies-capabilities-judged`. diff --git a/.changeset/38692-knowledge-pgvector-retrieval-modes.md b/.changeset/38692-knowledge-pgvector-retrieval-modes.md new file mode 100644 index 00000000000..927460236e5 --- /dev/null +++ b/.changeset/38692-knowledge-pgvector-retrieval-modes.md @@ -0,0 +1,10 @@ +--- +'@objectstack/knowledge-pgvector': patch +--- + +feat(knowledge-pgvector): the store runs the vector leg alone, the keyword leg alone, or both, as a source's retrieval mode says + +Clause-②: yes (widening) +Metadata-protocol: none + +`knowledge-pgvector` now reports the retrieval modes it runs (`capabilities.retrieval`: `vector`, `keyword` and `hybrid`, with `hybrid` by default) and honours the mode the knowledge service hands it on each search (`AdapterSearchOptions.retrieval`). `hybrid`, and a search that carries no mode, run exactly as before: both legs, merged by reciprocal rank fusion, with every score unchanged to the last bit. `vector` runs the cosine scan alone and `keyword` the keyword match alone; the other leg is not written into the statement, and a hit's score is `61 / (60 + rank)`, so the first is 1. `keyword` does not embed the question, ranks passages of equal keyword score by chunk id, and answers nothing for a question with no term to match. A mode it does not list is refused (`400 VALIDATION_ERROR`), never run. The keyword index is kept whatever the mode, so changing a source's mode rebuilds nothing. diff --git a/.changeset/38692-knowledge-retrieval-mode-service.md b/.changeset/38692-knowledge-retrieval-mode-service.md new file mode 100644 index 00000000000..8630e1cd1c3 --- /dev/null +++ b/.changeset/38692-knowledge-retrieval-mode-service.md @@ -0,0 +1,28 @@ +--- +'@objectstack/service-knowledge': patch +'@objectstack/spec': patch +--- + +feat(service-knowledge): the knowledge service reads a source's retrieval mode + +A search of a knowledge source now runs in its effective retrieval mode: the +mode the source declares (`source.retrieval.mode`), else its store's default +(`capabilities.retrieval.default`). The mode is handed to the store on every +search and logged at `debug` with where it came from; it is not in what a +search answers the caller. `index_status` carries each source's `retrieval` +(the mode, its origin, the store's modes, a refusal) and each mounted store's +modes. + +A source that declares a mode its store does not run is never searched +another way. It is refused at its save (`400 VALIDATION_ERROR`, listing the +modes the store runs), at registration in code (`registerSource`) when its +store is already registered, +once after boot at `error` (`reportUnsupportedRetrieval`), and on every search, +where it is listed in `refused` with `SERVICE_UNAVAILABLE` (503). It still +builds and syncs its index: a published item (a package install, the stack's +`knowledgeSources`) meets no save and is registered and indexed as usual, and +the boot's reading and every search refuse it. A store that reports no modes (knowledge-memory) +takes only a source that leaves the mode out. + +Clause-②: no +Metadata-protocol: none diff --git a/.changeset/38692-knowledge-retrieval-mode-spec.md b/.changeset/38692-knowledge-retrieval-mode-spec.md new file mode 100644 index 00000000000..754d85822e2 --- /dev/null +++ b/.changeset/38692-knowledge-retrieval-mode-spec.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-knowledge': minor +'@objectstack/platform-objects': patch +--- + +feat(spec): a knowledge source may declare its retrieval mode, `source.retrieval.mode` (`vector`, `keyword` or `hybrid`), and a knowledge adapter reports the modes it runs + +Clause-②: yes (widening) +Metadata-protocol: added + +A `knowledge_source` may now declare how it is searched: `source: { …, retrieval: { mode: 'vector' } }`. `vector` runs only the vector leg (ranking passages by meaning), `keyword` only the keyword leg (ranking passages by the words they hold, with no call to the embedder), and `hybrid` both, merged by the store's fusion. Leaving `mode` out, or writing `retrieval: {}`, keeps the store's default, which is today's behaviour. The key is read on every search and by no build, so it enters neither the index fingerprint nor the recipe hash: changing it rebuilds nothing. The parse refuses a mode outside the three, and any other key under `retrieval`, each with the fix. Studio's knowledge source form offers the key as a "Retrieval mode" select under "Search". + +`IKnowledgeAdapter` gains two optional members. `capabilities.retrieval: { modes, default }` is the adapter's report of the modes it runs and the one it runs when a source declares none; it is a report, not configuration. `AdapterSearchOptions.retrieval: { mode }` carries the mode a search runs, a per-request parameter like `topK`. An adapter that reports no modes keeps working unchanged; a source that names it may only leave `mode` out. + +The adapter contract suite (`@objectstack/service-knowledge/testing`) takes a new optional declaration, `implements.retrieval`: it checks the adapter's report (each mode one of the three, none twice, the default listed), searches a fixed set of passages under each listed mode (`vector` leaves out the passage only the keyword leg ranks, `keyword` answers that passage alone and nothing for a query with no word any passage holds), and checks that the default mode handed explicitly answers exactly what a search without the member answers. An adapter that does not declare it is checked to report no modes. + +The Studio metadata-form translations (`@objectstack/platform-objects`) name the "Search" group and the "Retrieval mode" select and its three choices in every locale. + +The knowledge service's reading of the mode (and its refusal of a mode the source's store does not run) and the turso and pgvector stores' support for it ship as separate changes. diff --git a/.changeset/38692-knowledge-turso-retrieval-modes.md b/.changeset/38692-knowledge-turso-retrieval-modes.md new file mode 100644 index 00000000000..65e0c8f627e --- /dev/null +++ b/.changeset/38692-knowledge-turso-retrieval-modes.md @@ -0,0 +1,10 @@ +--- +'@objectstack/knowledge-turso': patch +--- + +feat(knowledge-turso): the store runs the vector leg alone, the keyword leg alone, or both, as a source's retrieval mode says + +Clause-②: yes (widening) +Metadata-protocol: none + +`knowledge-turso` now reports the retrieval modes it runs (`capabilities.retrieval`: `vector`, `keyword` and `hybrid`, with `hybrid` by default) and honours the mode the knowledge service hands it on each search (`AdapterSearchOptions.retrieval`). `hybrid`, and a search that carries no mode, run exactly as before: both legs, merged by reciprocal rank fusion, with every score unchanged to the last bit. `vector` runs the vector leg alone (the exact scan, or the approximate index as before) and `keyword` the keyword match alone; the other leg is not written into any statement, and a hit's score is `61 / (60 + rank)`, so the first is 1. `keyword` does not embed the question or read the approximate index, ranks passages of equal keyword score by chunk id, and answers nothing for a question with no term to match. A mode it does not list is refused (`400 VALIDATION_ERROR`), never run. The keyword index is kept whatever the mode, so changing a source's mode rebuilds nothing. diff --git a/.changeset/38692-search-knowledge-score-text.md b/.changeset/38692-search-knowledge-score-text.md new file mode 100644 index 00000000000..f0f615845aa --- /dev/null +++ b/.changeset/38692-search-knowledge-score-text.md @@ -0,0 +1,11 @@ +--- +'@objectstack/service-knowledge': patch +'@objectstack/skills': patch +--- + +docs(knowledge): `search_knowledge` says what a hit's score means, and the AI skill documents `source.retrieval.mode` + +Clause-②: no +Metadata-protocol: none + +The `search_knowledge` description now says that a hit's `score` gives only its order among the hits of its own source, not how relevant it is, and the `score` member says the same: under a one-leg retrieval mode the first hit scores 1, and scores of sources searched in different modes are not comparable. The `objectstack-ai` skill lists `source.retrieval.mode` (vector, keyword or hybrid; omitted means the store's default; a mode the store does not run is refused at a run-time save, and a shipped source's every search answers 503), paid for by shortening two of its own sentences. diff --git a/.changeset/38692-studio-retrieval-mode-picker.md b/.changeset/38692-studio-retrieval-mode-picker.md new file mode 100644 index 00000000000..8408ce427d8 --- /dev/null +++ b/.changeset/38692-studio-retrieval-mode-picker.md @@ -0,0 +1,12 @@ +--- +'@objectstack/spec': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(studio): a knowledge source's retrieval-mode picker offers the modes its store runs + +Clause-②: no +Metadata-protocol: none + +The `source.retrieval.mode` row of the knowledge source form names a new picker, `knowledge-retrieval-mode`. Studio reads the source's store (the one its `adapter` names, else the deployment's) and its modes from the knowledge service's `index_status` answer, offers those modes, and names which mode the blank choice means ("Store default (Hybrid (both))"). A store that reports no modes, such as memory, is said to declare none ("驱动未声明检索方式"), and a mode already written there is kept and flagged. When the store's modes cannot be read (an author who is not a platform administrator, a store not mounted), the picker offers the three modes and the save judges the choice, as before. diff --git a/.changeset/38702-markdown-table-scroll.md b/.changeset/38702-markdown-table-scroll.md new file mode 100644 index 00000000000..c750a9ba0d0 --- /dev/null +++ b/.changeset/38702-markdown-table-scroll.md @@ -0,0 +1,17 @@ +--- +'@object-ui/fields': patch +'@object-ui/plugin-markdown': patch +--- + +fix(ui): a wide markdown table scrolls inside its own box instead of squeezing its cells or scrolling the page + +Clause-②: no +Metadata-protocol: none + +A GFM table in a `markdown` field on a record page (the document face, e.g. through `record:details`) and in the `markdown` component of `@object-ui/plugin-markdown` was drawn straight into the prose box. A table with many columns was squeezed to the text column, so CJK cells broke one character per line; a wider one overflowed the prose box and scrolled the whole page sideways, header and tab bar included. + +- Each table is now drawn in its own `overflow-x-auto` box bounded by the text column (`max-w-full`), so a table wider than the column scrolls inside that box. +- Every header and body cell keeps a minimum width of `6em` (four CJK characters after the cell padding), so a short phrase stays on one line and a many-column table scrolls instead of breaking its cells. Longer cell text still wraps; paragraphs keep `break-words`. +- A markdown value in a grid cell (the cell face) is drawn as before. + +Nothing to migrate. diff --git a/.changeset/38709-extension-copy-name.md b/.changeset/38709-extension-copy-name.md new file mode 100644 index 00000000000..407657f9807 --- /dev/null +++ b/.changeset/38709-extension-copy-name.md @@ -0,0 +1,12 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): a duplicated or namespace-imported package copies its `object_extension` rows without a `name` key, and each copy extends the copied object + +Clause-②: no +Metadata-protocol: none + +The namespace rename that `duplicatePackage` and `importUnmanagedPackage` (with `targetNamespace`) run on every copied item set `name` on each rewritten body. An `object_extension` body is keyed by `extend`, and the strict extension schema refuses `name`, so every copied extension landed in `failed[]` with "Unrecognized key(s) on this object extension: `name`", a key the author never wrote. The rewrite now leaves `name` off an `object_extension` body. + +A copied extension now follows the copied object: when its `extend` names an object the copy renames, the copy extends the copy's object and its row is named by it, for a bare object name too (`ticket` copied as `acme_ticket`), so it never extends the source package's object. An `extend` naming an object the copy does not hold (a platform object, another package's object) keeps its name. Every other type still takes its copy name. diff --git a/.changeset/38717-html-table-scroll.md b/.changeset/38717-html-table-scroll.md new file mode 100644 index 00000000000..04bac46e827 --- /dev/null +++ b/.changeset/38717-html-table-scroll.md @@ -0,0 +1,17 @@ +--- +'@object-ui/fields': patch +--- + +fix(ui): a wide table in an html or richtext field scrolls inside its own box instead of squeezing its cells or scrolling the page + +Clause-②: no +Metadata-protocol: none + +A table stored in an `html` or `richtext` field and shown on a record page (the document face, e.g. through `record:details`, or a readonly form field) was drawn straight into the prose box. A table with many columns was squeezed to the text column, so CJK cells broke one character per line; a wider one overflowed the prose box and scrolled the whole page sideways. + +- Each table is now drawn in the same box the `markdown` field's document face draws: its own `overflow-x-auto` box bounded by the text column (`max-w-full`), so a table wider than the column scrolls inside that box. +- Every header and body cell keeps a minimum width of `6em`, so a short phrase stays on one line and a many-column table scrolls instead of breaking its cells. +- The box is drawn after the sanitizer has run: what a stored table may carry is unchanged. +- An `html` / `richtext` value in a grid cell (the cell face) is drawn as before. + +Nothing to migrate. diff --git a/.changeset/38728-uncoded-search-throw.md b/.changeset/38728-uncoded-search-throw.md new file mode 100644 index 00000000000..304e05112e8 --- /dev/null +++ b/.changeset/38728-uncoded-search-throw.md @@ -0,0 +1,24 @@ +--- +'@objectstack/service-knowledge': patch +'@objectstack/spec': patch +--- + +fix(service-knowledge)!: a source whose adapter's search throws without a code is refused, never answered as no hits + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a caller of a knowledge search (the `search_knowledge` tool, its MCP HTTP and stdio faces, and in-process `KnowledgeService.search` / `searchWithRefusals`) when a source's adapter throws from `search` with an error that does not carry both an ADR-0112 `code` and `status` (an embedder that cannot be reached, a timeout outside the store). The search now names that source in `refused`, coded `SERVICE_UNAVAILABLE` (503), with a platform sentence naming the source; before, the source read as if it had matched nothing. The thrown message is not shown to the caller (it can carry hosts, SQL or keys); the operator's `error` log line keeps it, as before. Sources that answer are still served beside the refusal. A source that matches nothing is unchanged, and so is a coded refusal's own `refused` entry; a whole rejection that also names an uncoded throw may take that throw's top-level code (cell 2 below). + +## FROM → TO + +- No searched source answers and at least one threw without a code — two cells: + 1. Every searched source throws without a code (one source, or several failing on the same embedder outage). FROM: the search succeeded with `{ hits: [] }`. TO: the search is rejected `SERVICE_UNAVAILABLE` / 503 with `refused` naming each source (the `search_knowledge` executor and in-process `search` reject with `refused`; MCP answers an error result whose envelope is `code`, `message` and `status`, the sources named in the message). + 2. A source throws without a code beside a source refused with a code, none answering. FROM: rejected with the coded source's `code` / `status` and `refused` naming it alone. TO: `refused` names both, and the rejection's top-level `code` / `status` are the first refusal's in source order, so a 409 `KNOWLEDGE_REBUILD_REQUIRED` rejection may now read 503 `SERVICE_UNAVAILABLE`. +- A refill fails without a code. FROM: the source's round-one survivors were served. TO: they are dropped and the source is refused for the whole search, as a coded refusal of the refill already was. + +A caller reads `refused` (each source's own `code`, not only the top-level one) and the 503 instead of treating an empty answer as no match. An operator repairs the adapter or embedder the `error` line names. + +`@objectstack/spec` adds only the upgrade-guide entry `knowledge-search-uncoded-adapter-throw-refused`. diff --git a/.changeset/38747-knowledge-pgvector-scope-gin.md b/.changeset/38747-knowledge-pgvector-scope-gin.md new file mode 100644 index 00000000000..53ae22825bf --- /dev/null +++ b/.changeset/38747-knowledge-pgvector-scope-gin.md @@ -0,0 +1,11 @@ +--- +'@objectstack/knowledge-pgvector': patch +--- + +fix(knowledge-pgvector): a search narrowed by a metadata scope term reads only the passages in scope, through a GIN index on `metadata` + +Clause-②: no +Metadata-protocol: none + +- The passage table of each width now has a GIN index on `metadata` (`jsonb_path_ops`), named `knowledge_vec_d_metadata`. A new table is made with it. A table made by an earlier release gets it at its first search with a `metadata` scope term: the store looks the index up and creates it when absent (`CREATE INDEX IF NOT EXISTS`, not `CONCURRENTLY`), which holds the table's writes, not its reads, while it builds — on 58,500 passages of 1024 dimensions it took about 32 ms, then about 0.26 s of `ANALYZE`. When the database role may not create it, the scoped search is not refused: it answers as before, by a scan of the source's passages, and the store logs one warning naming the `CREATE INDEX` statement to run as a database owner, then does not try again in that process; once an owner runs it, the next search reads through it, with no restart. +- A `metadata` scope term is now written as containment the index serves — for each id, `{field: id}` and `{field: [id]}`, and the same two as a number when the id is how PostgreSQL prints a number — ANDed with the exact match it had before. So the vector leg, the keyword leg's candidates and its passage count read the passages in scope through the index instead of computing the distance of every passage of the generation; on a seeded table of 58,500 passages, one scoped vector-leg statement went from about 300 ms (sequential scan) to about 2 ms (bitmap index scan). Results are unchanged for every kind of stored value: a string, a number, a list of strings or numbers, a missing value, `null`, an object, a boolean. diff --git a/.changeset/38772-reranker-contract.md b/.changeset/38772-reranker-contract.md new file mode 100644 index 00000000000..8d445ba6fdf --- /dev/null +++ b/.changeset/38772-reranker-contract.md @@ -0,0 +1,12 @@ +--- +'@objectstack/spec': patch +--- + +feat(spec): `IReranker` and `RERANKER_SERVICE`, the reranker contract in `@objectstack/spec/contracts` + +Clause-②: yes (widening) +Metadata-protocol: none + +`@objectstack/spec/contracts` now exports `IReranker`, the contract for a provider that scores passages against a query, and its service token `RERANKER_SERVICE = 'reranker'`, mirroring `IEmbedder` and `EMBEDDER_SERVICE`. `IReranker` has a stable `id` and one method, `rerank(query, documents, opts?: { signal })`, which resolves to an array of `{ index, score }`: `index` is the document's position in `documents`, `score` the reranker's score for it. A higher `score` means the document matches the query better. The caller ranks by `score`; the order of the returned array carries no meaning. The model always comes from the deployment, never from a knowledge source; the knowledge service is to resolve the reranker per search, as knowledge adapters resolve the embedder, and that reader lands with `retrieval.rerank` (#38750, row 2); the caller makes one call per search and sends at most 50 documents; the caller passes an `AbortSignal` for its time limit. + +Nothing reads the contract yet, and no runtime behaviour changes. diff --git a/.changeset/auth-declared-defaults-every-key.md b/.changeset/auth-declared-defaults-every-key.md new file mode 100644 index 00000000000..ca61d79d7b9 --- /dev/null +++ b/.changeset/auth-declared-defaults-every-key.md @@ -0,0 +1,25 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(plugin-auth)!: Setup → Authentication shows what the deployment runs for every auth setting it declares, and says when sign-up is forced off over a value saved on + +Clause-②: yes (narrowing) — with nothing stored, 24 more `auth` keys answer the deployment's declaration where they answered the manifest default, so a published response changes for an existing reader, and a save of a key a declaration now shows or bounds can be refused where it was stored +Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches the auth settings page, these keys or the settings cascade's bottom rung. + + + +What narrows: with nothing stored, `SettingsService.get('auth', …)` and `GET /api/settings/auth` answer 24 more `auth` keys with the deployment's declaration (still `source: 'default'`) where they answered the manifest default: `password_min_length`, `password_max_length`, `membership_policy`, `password_reject_breached`, `password_require_complexity`, `password_min_classes`, `password_history_count`, `password_expiry_days`, `mfa_required`, `mfa_grace_period_days`, `api_key_default_expiry_days`, `api_key_max_expiry_days`, `api_key_inactivity_days`, `session_expiry_days`, `session_refresh_days`, `session_idle_timeout_minutes`, `session_absolute_max_hours`, `max_concurrent_sessions_per_user`, `allowed_ip_ranges`, `lockout_threshold`, `lockout_duration_minutes`, `audience_posture`, `audience_allowed_email_domains`, `audience_self_registration_permission_set`; so a published response's value changes for an existing reader on any deployment whose own configuration differs from the manifest default for one of them. Four keys gate another key's visibility, so with nothing stored a declaration now shows a key that was hidden, and a save that touches it or its gate is judged for its options and bounds where it was not: `lockout_duration_minutes` under a declared `lockoutThreshold` above 0 (for example `lockout_duration_minutes: 5000` is now refused `400 SETTINGS_VALIDATION` where it was stored), `mfa_grace_period_days` under a declared `mfaRequirement` other than `off`, `password_min_classes` under a declared `passwordRequireComplexity: true`, and `audience_allowed_email_domains` / `audience_self_registration_permission_set` under a declared `audience.posture` of `email_domain` or `open`. A save that sets one of these keys to its manifest default where the declaration differs now asks the key's write predicates. Widened: a save that sets one of these keys to the declaration with nothing stored is no change and asks no predicate. The Setup → Authentication live-status banner adds a `warning` for `signup_enabled` stored on where the deployment forces sign-up off (SSO-only, cloud-managed, `OS_DISABLE_SIGNUP`), in all 11 languages; where both that and the cloud-managed email-and-password hold apply, one banner carries both statements. + +A declared value outside its specifier's own bounds or options is answered as declared, because it is what runs, and is then judged whenever the key is touched without a value of its own: a clear of that key beside any other key in one patch, or a save of `email_password_enabled`, which gates the visibility of eight of these keys (the password keys and `mfa_required`). For example a declared `session.expiresIn` under one day reads below `session_expiry_days`'s minimum of 1, and a declared `minPasswordLength` under 6 below `password_min_length`'s; such a save is refused `400 SETTINGS_VALIDATION` at that key, where the manifest default sat in the slot and passed. Save the key within its bounds in the same patch, or clear it alone. + +The audience trio is one declaration the auth manager replaces whole. Once any of the three is stored, the settings pass now composes the audience from the three as the page reads them: each as stored, else as the deployment declares it. A domain list or permission set saved alone under a declared posture now runs, where it was stored and ignored; a posture saved beside a declared permission set the console did not resend now runs with that set, where it was refused. A saved audience the merged-result validation refuses is still refused, and the standing audience keeps ruling. A sibling saved where the deployment declares no audience is still ignored, with no posture to read it under. + +**BREAKING** for a reader of `GET /api/settings/auth` or `SettingsService.get('auth', …)` on a deployment whose own configuration differs from the manifest default for one of these keys, with nothing saved: the value answered is now what runs (for example `lockout_threshold: { value: 5, source: 'default' }` where the deployment declares `lockoutThreshold: 5`), not the manifest default. A saved value and an `OS_AUTH_*` override still win, and a clear returns to the declaration. A deployment that declares none of these reads exactly as before. + +**BREAKING** also for a deployment that declares an audience (`audience` in its auth configuration) and holds a stored `audience_allowed_email_domains` or `audience_self_registration_permission_set` with no stored `audience_posture` (left by clearing the posture alone, or set through that key's `OS_AUTH_*` override alone). Every earlier release ignored such a value with an `error` line; from this release it takes effect under the declared posture, so it can change which email domains may self-register, or which permission set a self-registered user receives. + +Each answer takes the key's own shape: session lifetimes in days (the declared seconds divided by 86 400), allowed IP ranges and email domains one per line, and a select's value only when it is one of its options (an off-vocabulary `membershipPolicy` or `mfaRequirement` leaves the manifest default). Not stated, by design: `rate_limit_max` and `rate_limit_window_seconds` (with nothing stored, the auth library's own per-path rules run, or, under a declared `rateLimit`, that declared global pair; neither is the per-endpoint cap the setting writes, so no one number states what runs), `api_key_policy_started_at` (recorded into the store at first boot), and the Google keys (the toggle's runtime default is the manifest default, and a declared credential outranks a saved one). + +What to do: before upgrading a deployment that declares an audience, look for `audience_allowed_email_domains` or `audience_self_registration_permission_set` stored while `audience_posture` is not (on `GET /api/settings/auth`, either key with a `source` other than `default` while `audience_posture` reads `source: 'default'`), including one set through its `OS_AUTH_*` override alone; clear it, or confirm it is the value to enforce. Nothing else to migrate. A client that read `source: 'default'` as "the manifest default" should read it as "nothing is saved; this is the deployment's default". diff --git a/.changeset/knowledge-pgvector-coded-search-refusals.md b/.changeset/knowledge-pgvector-coded-search-refusals.md new file mode 100644 index 00000000000..6673e4822e1 --- /dev/null +++ b/.changeset/knowledge-pgvector-coded-search-refusals.md @@ -0,0 +1,12 @@ +--- +'@objectstack/knowledge-pgvector': patch +--- + +fix(knowledge-pgvector): a search the database fails is a coded refusal, never an empty answer; its statement has a time limit; the pool size is a setting + +Clause-②: yes +Metadata-protocol: none + +- A search the store's database fails is now refused with an ADR-0112 code, chosen by the error's SQLSTATE: a statement past its time limit or cancelled (`57014`) is `TIMEOUT` (504); a full pool whose wait timed out, a dropped or refused connection, or a database out of capacity (`too_many_connections`) is `SERVICE_UNAVAILABLE` (503); any other database error is `DATABASE_ERROR` (500). Before, these errors carried no code, so the knowledge service logged them and skipped the source, and the caller was answered as if nothing matched. The message is one sentence naming the source; the SQLSTATE, the driver's text and the setting to change are in `remedy`. +- A search's ranking statement now runs under PostgreSQL's `statement_timeout`, set with `SET LOCAL` in the statement's own transaction (no session state, so it holds behind a transaction-mode pooler). Default 10000 ms: the plugin option `statementTimeoutMs`, else the setting `OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS`. Before, a search statement had no limit. +- The store's pool size is read from the setting `OS_KNOWLEDGE_POOL_MAX` when the plugin option `poolMax` is not given, and its default rises from 4 to 20: over 59,949 indexed passages with hybrid search, a pool of 4 left a third of the searches at 20 concurrent callers waiting past the connect timeout, and a pool of 20 left none. **A deployment with `OS_KNOWLEDGE_POOL_MAX` unset may now open up to 20 store connections per replica instead of 4.** It is a ceiling reached under load, not a count opened at boot: the pool opens a connection only when a search finds none idle. Against `max_connections=200` with 20 kept as headroom, the platform pool at 5 and one build, a replica reaches up to 26, so up to 6 replicas fit (60 store connections with 3). With more replicas or a smaller server, set `OS_KNOWLEDGE_POOL_MAX` lower (`4` keeps the old size) or raise `max_connections`; otherwise the server refuses connections (`too_many_connections`, class 53) and those searches are refused `SERVICE_UNAVAILABLE`. A setting that is not a positive integer stops the boot, naming it. The README states how to size it across replicas. diff --git a/.changeset/locked-record-refusal-readable-title.md b/.changeset/locked-record-refusal-readable-title.md new file mode 100644 index 00000000000..e3204e7c109 --- /dev/null +++ b/.changeset/locked-record-refusal-readable-title.md @@ -0,0 +1,10 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +fix(plugin-approvals): a locked record's refusal names it only by a field the writer may read + +Clause-②: no +Metadata-protocol: none + +The `RECORD_LOCKED` refusal raised while an approval holds a record names that record by its display field only when the field is one a caller can be served: a display field declared `internal: true`, or of a credential type (`secret`, `password`), never titles it. When the field-visibility source cannot answer, the refusal names no title. In both cases the refusal keeps its code (`RECORD_LOCKED`), its status (409) and its sentence, naming the object's label: "This Opportunity is locked while an approval is in progress, …". An ordinary display field still names the record as before. diff --git a/.changeset/organizations-pending-invitations.md b/.changeset/organizations-pending-invitations.md new file mode 100644 index 00000000000..64d1f482a93 --- /dev/null +++ b/.changeset/organizations-pending-invitations.md @@ -0,0 +1,9 @@ +--- +"@object-ui/app-shell": patch +"@object-ui/i18n": patch +--- + +Clause-②: no +Metadata-protocol: none + +Console 「Your Organizations」 page now lists the signed-in user's pending invitations (organization, role, expiry), each opening the existing accept page. While one is pending, the single-organization auto-skip and the zero-organization create dialog no longer carry the user past it; an inbox refused for an unverified address shows no section. diff --git a/.changeset/pre/36055-view-all-stops-voting-on-fields.md b/.changeset/pre/36055-view-all-stops-voting-on-fields.md index 10b971faaf2..e9fdbf923cf 100644 --- a/.changeset/pre/36055-view-all-stops-voting-on-fields.md +++ b/.changeset/pre/36055-view-all-stops-voting-on-fields.md @@ -27,7 +27,7 @@ FROM → TO: **Check your permission sets in one step.** A permission set is affected when one of its `objects` entries, the `'*'` entry included, has `viewAllRecords: true` or `modifyAllRecords: true` and does not have `viewAllFields: true`. For each such entry, add `viewAllFields: true` to it if the set should still read every field of that object. Beside View All that is all the read needs: with the bit, the set reads what View All read before. Beside Modify All it is not: the set's own `readable: false` rows now bind (before, Modify All overrode them), so a field such a row hides stays hidden from the set's holders until you delete the row. For the edit, Modify All no longer grants one: where its holders must still edit a field another set locks, or a field the set's own field row names without `editable: true`, add an explicit `editable: true` row in the set that should edit it. - Sets in your source: `os migrate meta --from 18 --write` adds `viewAllFields: true` beside every such bit (ADR-0087 conversion `permission-view-all-fields-beside-record-bypass`). -- Sets saved in a running deployment (Studio-saved, stored in `sys_metadata`): they are **not** rewritten on upgrade, and from 19 they are read with the new meaning. Studio's permission matrix has no control for `viewAllFields` today (it keeps the key when it saves a set that already carries it), so add it to the set's entry through the metadata API. No command lists the affected stored sets yet; a review list is follow-up #37375. +- Sets saved in a running deployment (Studio-saved, stored in `sys_metadata`): they are **not** rewritten on upgrade, and from 19 they are read with the new meaning. Studio's permission matrix has no control for `viewAllFields` today (it keeps the key when it saves a set that already carries it), so add it to the set's entry through the metadata API. To find them, run `os migrate meta --stored`: it lists each affected entry of a stored set under `viewAllFieldsReview` (read-only), and you fix each listed entry by adding `viewAllFields: true` to it through the metadata API. The protocol-19 upgrade guide carries the same check as the semantic entry `permission-view-all-modify-all-cast-no-field-vote`. diff --git a/.changeset/sec2-wf9p-f12.md b/.changeset/sec2-wf9p-f12.md new file mode 100644 index 00000000000..ad5952e1000 --- /dev/null +++ b/.changeset/sec2-wf9p-f12.md @@ -0,0 +1,28 @@ +--- +'@objectstack/plugin-security': patch +'@objectstack/objectql': patch +--- + +fix(plugin-security)!: an elevation's write is judged as it will be stored, and its option bag never widens it past its caller's organization wall + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +The rule: an app-authored elevation (an action body, a hook that runs as system, a flow that runs as system) is held to its caller's organization wall on the row as it will be stored and on the tenant scope its option bag asks for (ADR-0095 D1, ADR-0123 D2). + +**BREAKING** for an action body, a system hook or a system flow run for a signed-in caller. + +- FROM: the organization a write's before-hooks left on the row, and the `tenantId` / `tenantIds` an operation's option bag named, were not judged against the caller's organization wall. +- TO: + - a write is judged again on the rows its before-hooks leave: a row stored in an organization outside the caller's wall, or an update that leaves a row in no organization, is refused with `403 PERMISSION_DENIED`; + - a write (`insert`, `update`, `delete`, `purge`) whose option bag names an organization outside the caller's wall, or clears `tenantId`, is refused with `403 PERMISSION_DENIED`; + - a read (`find`, `findOne`) whose option bag names or clears an organization scope is answered by the read rule: the caller's wall is composed onto its predicate, so it reads only rows the wall admits; + - the option bag a before-hook leaves (a key it sets, a bag it replaces or hands back) is judged by the same rule where the engine builds the driver's options: a write's is refused with `403 PERMISSION_DENIED`, a read's is narrowed to the organizations the wall admits. A bag naming only organizations inside the scope the engine itself projects for the caller (its active organization, or under `group` its memberships) is not judged further: under `group` a member's hook-left bag naming another of its organizations is admitted, as at the plain door. A bag beyond that scope, or one that clears a key, is judged against the caller's wall where a verdict is worked out for the operation, and against the caller's active organization alone where none is. + +**Not moved.** A write whose stored rows stay in organizations the caller's wall admits, and an option bag the operation is handed that names only such organizations, behave as before; an operation that names no tenant key keeps its reach, under `group` the union of the caller's memberships included. A bag a before-hook leaves that names only organizations inside that projected scope behaves as before too, under `group` any of the caller's memberships included. Objects outside tenancy, objects with no organization column, and a platform operator crossing the wall on an object whose posture permits it are answered as the caller's own requests answer them. System work that runs for no caller (a scheduled run, a platform plugin's own system context, the seeders) is unchanged, its option bag included. + +Also in this change: `@objectstack/objectql`'s `OperationContext` gains `driverTenantScopeCheck` (type `DriverTenantScopeCheck`), an enforcement layer's bound on the explicit `tenantId` / `tenantIds` of an operation's option bag. The engine asks it, at each driver bag it builds for that operation after every before-hook, about the explicit keys that ask beyond the scope it projects for the call or clear it, and hands it a plain copy of `tenantIds`; keys inside that scope reach the driver unjudged; absent, nothing changes. + +The fix for a body or hook: write only into organizations the caller may write in, and leave `tenantId` / `tenantIds` off the option bag, or name an organization the caller's wall admits. A row that must land in another organization is written by a member of that organization, through its own request. diff --git a/.claude/agents/os-dev.md b/.claude/agents/os-dev.md index 59148e5a309..f490ac06750 100644 --- a/.claude/agents/os-dev.md +++ b/.claude/agents/os-dev.md @@ -28,11 +28,10 @@ model: opus - 认领带 `Resume-from: BRANCH@SHA` ⇒ 从 `origin/BRANCH` 建同名分支续写,先合 `origin/main`。 - ⛔ 永不编辑共享检出;修复横跨姊妹仓时一仓一 worktree。 - 动笔前记下基点 `BASE=$(git rev-parse HEAD)`,它是标准条款节里家族规则的锚。 - - 建好分支后先推空分支(任何编辑前 `dev-worktree.sh --probe`):落地标记兼写路由探针。 + - 先推空分支(任何编辑前 `dev-worktree.sh --branch=BRANCH --probe`):落地标记兼写路由探针。 - 卡线程分支由平台指定、harness 推送,⛔ 不推空分支;探针规则只对自建分支。 - 探针遇 403 ⇒ 停下报 `blocked`,⛔ 不进重试循环;只有网络错误才退避重试。 - Scratchpad 按 issue 隔离:在 scratchpad 目录下建 `issue-/` 子目录,临时文件全写进去。 - - 同批 agents 共用一个 scratchpad 目录,自然命名的文件会被彼此静默覆盖。 2. **卡 assignee 归 PM。** 派发原子对已把它设好;共享身份下该字段答不了是谁。 - 你的身份位是认领评论里的分支;仓 CLAUDE.md 的 claim-first 已由 PM 的认领满足。 - 恒不写卡的 assignee(空也开工,报 `summary`);PR 派认领 `Account:`(`pr_create` 带),交棒归席位。 @@ -72,6 +71,7 @@ model: opus - 就地修欠两样:认领申报的文件面同轮增补;PR 正文点名该修复并附证据。 - 优先扩展一个守卫关掉整个类;任一条不成立 ⇒ 回默认:报告列出交席位立单、不碰。 - 本轮改动令其变假或触碰的已发布缺陷必修;其余立卡并记明已发布面,PR 照常落地。 + - 源文件超 1,000 行 ⇒ 新关注点(新操作、新规则族、新子流程)写进同级新模块,原文件只加调用;既有函数内的修复留原处;⛔ 不为腾位搬既有代码:那是拆分卡。 4. ⛔ 永不推 `main`、合并任何 PR、在代码 PR 里改 `content/docs/releases/`;改错另开 docs-only PR。 - force-push 按落地仓 AGENTS.md:cloud 绝对禁;objectstack §3 五条全立才 `--force-with-lease`。 5. **Contract-first。** 修复若诱使你在消费端加宽容回退(`??` 别名、宽松解析),缺陷在上游。 @@ -85,9 +85,9 @@ model: opus 1. **重活串行,共享验证锁只有一个入口。** 每次 build/test 都从这里走。 - `bash scripts/pm/os-verify-lock.sh -c ''`(或 `-- `);⛔ 永不手搓 `flock`/lockfile。 - - 一次前台调用领全部等待预算,阻塞到拿锁或 99;⛔ 不轮询重试,恒设 `OS_VERIFY_LOCK_SLOT`。 + - 一次前台调用领全部等待预算,阻塞到拿锁或 99;⛔ 不轮询重试。 - 它不保证机器空闲:`check:*` 门禁、install、dev server 不走它,与持锁同核并跑。 - - 超前台上限者(`check:pm-dispatch-gates`、全量 dogfood):`nohup … > LOG 2>&1 &` 后 `tail --pid`。 + - 前台上限内跑不完者 ⛔ 不转后台(任何拼法):`--ran` 记 `NOT-MEASURED :: <实测原因>`,归 CI。 - 锁下墙钟绝对值是共享盒读数;只包命令本身,不包你的阅读与判断。 - 结论读它印的 `VERDICT command-exit` 行,⛔ 不读裸 `$?`;按到达序授予。 2. **压住堆**:重命令前缀 `NODE_OPTIONS=--max-old-space-size=4096`,要抬需给理由。 @@ -137,24 +137,21 @@ model: opus - 推导用 `node scripts/pm/dispatch-gates.mjs --commands` 不传路径,脚本自己从 merge-base 取变更集。 - 变更集含未提交与未跟踪;跑完把已跑清单交给 `--ran ` 对账,未跑的本地族它会点名。 - ⛔ 别自己 `git diff` 出一份清单喂它:两点 `origin/main..HEAD` 按此刻的 origin/main 求值。 -- 分支切出后落地的姊妹 PR 文件会算到你头上:退出码 0、门禁只多不少,报告的清单却假。 - 浅检出上脚本响亮拒绝而非给错清单,照它说的加深。 - 派生点名却不在 PR check-runs 的族(选择器跳过或仅 push/schedule):本地读数即证据,报告标明。 - 本地独有族(CI 只跑其 `--self-test`,不跑扫描):`check:dev-prereqs`、`check:skill-frame-freshness`。 - 二者判本机状态(`packages/spec/dist` 过期否、检出对 origin/main 新鲜否),CI 新检出无可判。 - 派生不点名二者;触 `packages/spec` 构建或四轴框架文件时本地跑,读数只进报告,留在本地。 - ⑤ diff 编辑了门禁/工具脚本 ⇒ 该脚本自己的测试套件在派生族之外另欠。 -- 派生答哪些门禁读你改的文件,不答哪些测试测这个脚本。 - 跑同目录点名它的 `*.test.ts`,加同包 tests 下 `git grep` 该脚本文件名的全部命中。 - 该脚本只住在 objectstack,答案只关于它所在的树:每次推导第一行(stderr)点名仓与 commit。 - 读之前先核对;姊妹仓未必有 `scripts/pm/dispatch-gates.mjs`:hotcrm 就没有。 -- 把它们的路径喂进 objectstack 检出,得到的是 objectstack 的门禁族:形态完整、退出 0、全错。 - 那边的清单从该仓自己的 `package.json` 与 `.github/workflows/` 手工推导。 - 加 `--repo /` 申报本次答案该属于哪个仓,不匹配即拒绝并同时点名两个仓。 - 仓级扫描(以 `pnpm lint` = `eslint . --no-inline-config` 为首)是 CI 拥有的运行,永不是你欠的。 - 并集在最终 commit 之后跑,并从那次运行引用 `git rev-parse --short HEAD`。 - 报告的 `tests` 字段和 PR 正文两处都要引;门禁日志不带 sha,最后 commit 前的并集量的旧树。 -- 迟到的 commit 挪动的恰是 ratchet 读数;复核后任何一次 push,都在新 head 上重跑并集。 +- 复核后任何一次 push,都在新 head 上重跑并集。 - 至少重跑 ratchet 族,然后才更新报告或 PR 正文。 - 收窄引 `turbo ls --affected` 须同句写明盲区:集出自包依赖图,盲于读盘取别包源码的测试。 - 仓根包不在 `turbo ls` 里,根级套件整个在图外;故只称「不在图上」,永不称「动不了」。 @@ -177,13 +174,11 @@ model: opus - 派发词与本文件冲突时以本文件为准:无条件条款住这里,错了也在这里改。 - 遇到冲突在报告里点明,⛔ 不悄悄选边;下列条款无论 prompt 提没提都生效,沉默不是许可。 - 判断任何事之前先 build:过期的 `dist/*.d.ts` 两个方向都撒谎。 -- 假红让你追不存在的问题;假绿把收窄后的导出类型读成消费者干净,而消费者没见过它。 - 消费者清扫的 filter 方向是前缀:`pnpm --filter '...@objectstack/'` = 下游消费者。 - 后缀形式是上游依赖,方向相反;契约收紧永远落在下游。 - 报告里写 N 个包全绿必须说方向,否则这句话无法复核。 - 退役键的清扫默认走退役 playbook 的 tree-scoped 缺席 pin,不为一次缺席检查重建消费者闭包。 - 跨包类型改动需要一次反向验证:贴进一个新类型会拒绝的键,确认转红,再恢复。 -- 这证明你读的是重建后的 `.d.ts`,不是缓存。 - `packages/spec`:`authorable-surface.base.json` 只由 `gen:authorable-surface-base` 写,普通构建从不写。 - ⛔ 永不回退它、永不为凑某个相等手改它;作数的断言是 `check:authorable-surface` 绿。 - `baseRev` 允许滞后,一行信息不是错误;普通构建下该文件动了是 finding,不是产物。 @@ -218,9 +213,9 @@ model: opus - 范围按本地验证范围节圈定;`packages/cli` 的卡本地只欠 `unit` 层,`integration` 层声明给 CI。 - `packages/cli` 卡与 driver/kernel 启动路径的分层跑法住 pm-dispatch `references/dev-traps.md`,碰到才读。 - Draft PR 指向 `main`,正文首行 `Fixes #`;合并不应关卡时用 `Part of #`,并说明留下哪一半。 -- 全量 dogfood 只在终 head 跑一次,仅当标题带 `!` 或 `Clause-②:` 带 `(narrowing)` 臂(yes/no 皆算)。 -- 命令同 CI:按 ① 建闭包,锁下 `pnpm --filter @objectstack/dogfood test`;⛔ 无 `OS_TEST_SHARD`、无路径。 -- 红 = 本改动的后果(陈旧 fixture)同 PR 修,余照报;⛔ 永不跳过或收窄;计数记 `dogfood_battery`。 +- 全量 dogfood ⛔ 不在本地跑:标题带 `!` 或 `Clause-②:` 带 `(narrowing)` 臂(yes/no 皆算)⇒ 席位给 PR 挂 `needs:dogfood-battery`,CI 在其 head 跑三段。 +- 落地门只读该 head 上 `Dogfood battery (opt-in)` 的 success,⛔ 不读报告;每次 push 换 head 即欠新一轮,dev 不自挂该标签。 +- 红 = 本改动的后果(陈旧 fixture)同 PR 修,余照报;⛔ 该类 PR 不改 `.github/workflows/dogfood-optin.yml`:不能自证。 - 认领的 `Clause-②:`、`Metadata-protocol:` 两行照抄进 PR 正文行首;无则零写,⛔ 不自造。 - 两行同抄进 changeset 正文行首;`Check Changeset` 读 PR 正文:kind 即 `minor`,`none` 即 `patch`。 - 种类非 `none` 或带 `(narrowing)` ⇒ 按 diff 加写 `Skills-docs:` 行;拼法与分工住认领模板。 @@ -270,7 +265,7 @@ model: opus - 全文 ⛔ 不出现 HTML 注释:sanitizer 落库后吃短尖括号片段,连反引号里的也吃。 - 例外二:harness 自写 PR 正文首行归属注释原样留、只报,`Fixes #` 紧随;派发令要求才独占 - 末个非空行写 ``(`PR_BODY_TRAILER_SHAPE`);其余 dev 自写仍禁。 + 末个非空行写 ``(`PR_BODY_TRAILER_SHAPE`,读方亦认 `LANE#N`);其余 dev 自写仍禁。 - 凡要上 GitHub 的文本,尖括号形状片段一律改占位词拼写(`FIELD`、`IDENT.MEMBER` 一类)。 - 各派发模式(`mode:subagent`、`mode:cloud`、`mode:thread`)下 GitHub 都是报告的权威源。 - 评论、PR 正文都读回到尾:只认首行标记保不住正文,sanitizer 可从首个 tag 形片段吃到尾。 @@ -290,7 +285,7 @@ model: opus - 两条合法出路:在轮内同步等它(资源纪律的排队条款:限时获取 ⇒ 无锁工作 ⇒ 再取)。 - 或者收窄这次检查的范围并在报告里申报:已申报的收窄是被接受的偏差,CI 跑满农场。 - PM L1 审核的是 CI 收敛,不是你本地的覆盖面;未申报的收窄不在此列,那是漏跑。 - - 比回合长的门禁在写报告那一刻读日志(重定向目标);未完成的记 NOT MEASURED 并写原因。 + - 报告里没有还在跑的门禁:前台没跑完的记 NOT MEASURED 并写实测原因,归 CI。 - 结束一轮之前自检:最后一条消息是否在描述你不拥有的进程给你的唤醒? ## 何时停手不写码 @@ -323,9 +318,11 @@ model: opus "summary": "what was implemented, 2-4 sentences", "tests": "commands run + pass/fail evidence (real output excerpts); ablation only where a tested behaviour changed: rebuild + on-disk mutation proof", "gates": "local subset: each command + exit code captured before any pipe + --ran reconciliation; every family CI runs: the PR's check-runs (name + conclusion) cited, not re-run locally", - "dogfood_battery": "n/a — no `!` in the PR title and no (narrowing) arm | · the lock's VERDICT line · Test Files N/N · Tests M/M · every failure named", "mcp_calls": " — MCP GitHub calls with tool names; a write tool in the list = this report is refused", "api_writes": " — REST proxy writes, each endpoint listed", + "classifier_refusals": [ + { "command": "verbatim", "reason": "as the classifier quoted it", "mode": "subagent | cloud | thread", "human_turn_before": "yes | no | unknown — a human-typed turn earlier in this session", "resend": "none | passed | refused, + what changed" } + ], "open_questions": [ { "question": "…", "options": ["A …", "B …"], "recommendation": "A, because …" } ], @@ -336,6 +333,7 @@ model: opus - `status: "rework"` = 你自知不完整的部分成果,在 `summary` 里说明为什么。 - `premise_still_valid: false` = 核验证伪了前提(规则 6):证据进 `summary`,`pr` null 或只圈存活部分。 +- `classifier_refusals` 闭字段:分类器每拒一条命令记一行,无则 `[]`;照实记,⛔ 不造拒、不为填它重发。 - 报告模板是工具,不是真相:某字段的预设与实际发生的对不上时直说。 ## 字节与 sanitizer 纪律 diff --git a/.claude/settings.json b/.claude/settings.json index 06dc0d3b1d8..9e4b89e5c94 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -100,6 +100,16 @@ "Bash(git push -u origin claude/mailbox-*:**)", "Bash(git push -u origin claude/issue-*\\**)", "Bash(git push -u origin claude/mailbox-*\\**)", + "Bash(git push -u origin claude/issue-*?*)", + "Bash(git push -u origin claude/issue-*[*)", + "Bash(git push -u origin claude/mailbox-*?*)", + "Bash(git push -u origin claude/mailbox-*[*)", + "Bash(git commit -F *\\**)", + "Bash(git commit -F *?*)", + "Bash(git commit -F *[*)", + "Bash(git commit --allow-empty -F *\\**)", + "Bash(git commit --allow-empty -F *?*)", + "Bash(git commit --allow-empty -F *[*)", "Bash(xargs git push -u origin claude/issue-*)", "Bash(xargs git push -u origin claude/mailbox-*)", "Bash(xargs git commit -F *)", diff --git a/.claude/skills/dogfood-verification/SKILL.md b/.claude/skills/dogfood-verification/SKILL.md index 1e3381e7017..333c9359f49 100644 --- a/.claude/skills/dogfood-verification/SKILL.md +++ b/.claude/skills/dogfood-verification/SKILL.md @@ -31,37 +31,18 @@ dev 工作树、dev-server 端口、preview 浏览器全是**共享的**:并行 ⚠️ 环境事实的锚点是 `docs/qa/platform-checklist/RUNNER.md` —— 本节只写它没有的那 几条,⛔ 不留第二份拷贝。 -- [ ] **自有端口**:挑一个空闲的非默认端口(不要 3000/3001/3210)。先查: - `lsof -nP -iTCP: -sTCP:LISTEN`。在 `.claude/launch.json` 加一条指向**本** - 工作目录的具名配置,例如 - `pnpm -C /examples/app-showcase exec objectstack dev --ui --seed-admin -p -d file:/tmp//data.db`。 - 工作树没了就**删掉自己那条** —— 死条目让 `preview_start` 挂在缺失的 `pnpm -C` 上。 -- [ ] **同时导出 `OS_PORT` —— 只给 `-p` 不够。** showcase 的自 ping 连接器读的是*环 - 境*(`SHOWCASE_SELF_URL`→`OS_PORT`→`PORT`→3000),于是 `fetch failed` 冒充出口被封。 -- [ ] **自有数据**:`--seed-admin` 在空 DB 上给出 `admin@objectos.ai / admin123`。持 - 久化 `-d file:/tmp//data.db` 重启后仍在(适合多步配置的运行);`--fresh` - 给全新首跑(退出即清)。 -- [ ] **确认独占控制**:`preview_start` 后检查 `location.origin` === 你的 - `http://localhost:`。标签页不断漂到你没导航过的应用/路由、或出现你没写过 - 的草稿 → **有并行会话占着浏览器**。别跟它抢;把所有检查钉到你的绝对 origin, - 靠 API + 源码(支柱 3)。 -- [ ] 还要开 PR 的话,在**基于 `origin/main` 的独立 git worktree** 里做(见 §5)—— - 永不从共享的脏分支提交。 +- [ ] **自有端口**:挑一个空闲端口 —— 不要 3000(`os dev` 的缺省端口、Console 开发代理的缺省目标),也不要 `.claude/launch.json` 入库条目已占的端口。先查:`lsof -nP -iTCP: -sTCP:LISTEN`。在 `.claude/launch.json` 加一条指向**本**工作目录的具名配置(该文件入库、`.claude/**` 受治理:⛔ 不提交你的条目),例如 `pnpm -C /examples/app-showcase exec objectstack dev --ui --seed-admin -p -d file:/tmp//data.db`。工作树没了就**删掉自己那条** —— 死条目让 `preview_start` 挂在缺失的 `pnpm -C` 上。 +- [ ] **`-p` 由 `os dev` 自己导出给编译**,缺省启动的自 ping 连接器拨的就是本端口;坑在 `--no-compile`(拨上次编译看到的端口,导出 `OS_PORT` 不是修复)与端口被占时的顺移 —— 两条都住 RUNNER 的连接器条;日志有 `server bound to port` 行即已顺移,照它发请求。 +- [ ] **自有数据**:`--seed-admin` 在空 DB 上给出 `admin@objectos.ai / admin123`。持久化 `-d file:/tmp//data.db` 重启后仍在(适合多步配置的运行);`--fresh` 给全新首跑(退出即清)。 +- [ ] **确认独占控制**:`preview_start` 后检查 `location.origin` === 你的 `http://localhost:`。标签页不断漂到你没导航过的应用/路由、或出现你没写过的草稿 → **有并行会话占着浏览器**。别跟它抢;把所有检查钉到你的绝对 origin,靠 API + 源码(支柱 3)。 +- [ ] 要开 PR 就照 §5 在独立工作树里做 —— 永不从共享的脏分支提交。 ## 1. 启动 - [ ] `preview_start` 你在 `.claude/launch.json` 的具名配置;轮询就绪: `curl -s -m3 -o /dev/null -w '%{http_code}' http://localhost:/api/v1/health` → 200。 -- [ ] Console UI 在 `/_console/`;应用在 `/_console/apps/`(如 - `com.objectstack.setup`、`com.objectstack.studio`)。API 根 `/api/v1`,设置 - `/api/settings`,合并后的应用/导航 `/api/v1/meta/app?id=`。 -- [ ] ⚠️ **`?id=` 键的是应用 `name`,不是包 id。** stock boot 的 name 是 - `showcase_app` / `setup` / `account`(`studio` 不随 stock boot 装载,`?id=studio` - 理应为空 —— 详见 RUNNER)—— 不是上一行那种 `com.objectstack.setup` / - `com.example.showcase`(那是包 id,只在 `/_console/apps/` 的路径段上成立)。传 - 包 id 得到的是 `{"items":[]}`,读起来和「应用元数据没了」一模一样 —— 最高价值 - 的假 P0 形状。**先不带 query 取一次 `/api/v1/meta/app`,读它真正返回的 name, - 再去过滤。** +- [ ] Console UI 在 `/_console/`;应用在 `/_console/apps/<包 id>`(如 `com.objectstack.setup`、`com.example.showcase`;应用 name 是别名);Studio 不是应用,在 `/_console/studio/`。API 根 `/api/v1`,设置 `/api/settings`,合并后的应用/导航 `/api/v1/meta/app?id=`。 +- [ ] ⚠️ **`?id=` 键的是应用 `name`(`showcase_app` / `setup` / `account`),不是包 id。**传包 id 得到 `{"items":[]}`,读起来和「应用元数据没了」一模一样 —— 最高价值的假 P0 形状(RUNNER 同条)。**先不带 query 取一次 `/api/v1/meta/app`,读真名再过滤。** ## 2. 构建/运行时模型 —— 攒一批,然后一次重启 @@ -78,10 +59,10 @@ dev 工作树、dev-server 端口、preview 浏览器全是**共享的**:并行 `ui/` 下已合并的修复在 Console 重建之前**不会活在 :3000 上**:运行中的服务器继续 提供旧构建产物。所以**在宣布 :3000/_console 上发现 console/Studio UI 缺陷之前,先 对当前 `ui/` 源码或全新构建核一遍** —— 构建可能是旧的,缺陷可能已修。最快的权威 - 核验 = `ui/` 的 HMR console 指向你的服务器: - `VITE_SERVER_URL=http://localhost: DEV_PROXY_TARGET=http://localhost: pnpm --filter @object-ui/console dev` - (独立 origin → 需要它自己的 `admin@objectos.ai/admin123` 登录)。跳过这步曾在 - 一个上游已修掉的 action-create 死路上白付一整圈 spawn-a-fix。 + 核验 = `ui/` 的 HMR console 代理到你的服务器,浏览 `:5180`: + `DEV_PROXY_TARGET=http://localhost: pnpm --filter @object-ui/console dev` + (⛔ 不设 `VITE_SERVER_URL`:调用跨 origin、绕过代理,认证路由答 401;独立 origin → + 需要它自己的 `admin@objectos.ai/admin123` 登录)。 - [ ] **构建新鲜度由你自核。** `pnpm console:build` 产出的 dist 不盖 SHA 章,`os dev` 无从判定它是否陈旧,照常挂载 `/_console`;改过 `ui/` 就先在仓库根目录重建再观察。 @@ -118,21 +99,17 @@ dev 工作树、dev-server 端口、preview 浏览器全是**共享的**:并行 ## 5. 交付 —— 隔离的 PR(工作树共享/脏时) -- [ ] 只捕获你自己的文件:`git diff -- > /tmp/fix.patch` - (用**显式路径**,不用多行 shell 变量 —— 后者会静默产出空 patch)。 -- [ ] `git fetch origin main && git worktree add --no-track -b /tmp/pr origin/main` - → `git -C /tmp/pr apply /tmp/fix.patch` → 确认 `git -C /tmp/pr status` *只*列你的文件。 +- [ ] 只捕获你自己的文件:`git diff -- > /issue-/fix.patch` (用**显式路径**,不用多行 shell 变量 —— 后者会静默产出空 patch)。 +- [ ] `bash scripts/pm/dev-worktree.sh --branch=claude/issue--` → `git -C apply` 该 patch → 确认 `git -C status` *只*列你的文件。 - [ ] 加 **changeset**(`.changeset/.md`,`"@objectstack/": patch`)—— 发布包的改动过不了 CI 的「Check Changeset」门。 -- [ ] 提交(信息末尾带 `Co-Authored-By:` trailer)、推送、开 **draft** PR(dev 容器走 REST 端点; - 人手上 `gh pr create --draft`),PR 报给派发你的席位;ready / 入队 / 人工合并归该席位。 -- [ ] `git worktree remove /tmp/pr`:⛔ 不带 `--force`,被拒说明有东西没提交,先读 `git status`。 +- [ ] 提交(末尾带无模型 trailer 对 `Claude-Session:` + `Co-authored-by: Claude`)、推送、开 **draft** PR(dev 容器走中继 `pr_create`,`scripts/pm/fleet-write/dispatch.mjs`;人手上 `gh pr create --draft`),PR 报给派发你的席位;ready / 入队 / 人工合并归该席位。 +- [ ] `rm -rf /node_modules && git worktree remove `:⛔ 不带 `--force`,被拒说明有东西没提交,先读 `git status`。 ## 6. Shell 卫生 - glob 匹配不上时 zsh 会吃掉 `--include=*.ts` → 用专门的 **Grep 工具**,或给 glob - 加引号。 -- 复合 `git` 命令里,显式参数优于多行 `VAR="a b c"`。 + 加引号;复合 `git` 命令同 §5,显式参数优于多行 `VAR="a b c"`。 --- diff --git a/.claude/skills/pm-dispatch/SKILL.md b/.claude/skills/pm-dispatch/SKILL.md index 7a9cfb247c5..de1a92fad5f 100644 --- a/.claude/skills/pm-dispatch/SKILL.md +++ b/.claude/skills/pm-dispatch/SKILL.md @@ -49,7 +49,7 @@ PM 的工作是循环:选卡 → 认领 → 派发 → 收集 → L1 审核 → - L2 契约审核:PR 碰 `references/contract-review.md` 契约四面才欠,加在 L1 之上,⛔ 永不替代 L1。 - L2 档随面定(`contract-review.md`);L1 与 `TIER_DEFAULT` 审核恒归车道,⛔ 永不归 L2 席。 - ⛔ L1 规则不及 L2,L2 规则不及 L1;L2 席的账号、独立性、信箱与只写记录诸规只管 L2 席。 -- GitHub PR review 与 CI check 名不属两级;旧词与旧路径只读不写,唯在座 `review#N` 席仍写原名。 +- GitHub PR review 与 CI check 名不属两级;旧词与旧路径只读不写,唯未改名席仍签旧名。 ## 入口与角色 @@ -79,7 +79,7 @@ PM 的工作是循环:选卡 → 认领 → 派发 → 收集 → L1 审核 → - 项目席唤醒 = PR 订阅 + 自建自绑巡查 routine(总监席与按需席除外);⛔ 无 `send_later` 链。 - 探针先行:fire 的第一动作是一次最便宜的车道盘点查询,⛔ 在它之前不读任何长文本。 - 队列空(逐卡表见 `references/seat-lifecycle.md`)+ 无在飞 + 无待 L1/L2 + 决策箱无新答复 ⇒ 自退。 -- 分诊席与车道席常驻(按需席除外),断粮换号重开席与信箱;裁决归总监。 +- 分诊席与车道席常驻(按需席除外),断粮换号坐新号的席;裁决归总监。 - 子代理裁决逐份过转录核验采信。 ## 阶段细则索引 @@ -131,7 +131,7 @@ PM 的工作是循环:选卡 → 认领 → 派发 → 收集 → L1 审核 → - 五个 pm 状态标签加 `needs-user-decision` 共六态互斥,转换恒一笔 replace ⛔ 不 add。 - `pm:queue` 卡逾三天欠一次显式转换(派发/转箱/停放/撤单/改前提),⛔ 不是排期。 - hold/blocked 的行契约、双通道与 `Restart-touch:` 触发文件细则见 `references/state-machine.md`。 -- `needs-user-decision` 是决定待做,`pm:on-hold` 是决定已做;`manual — <理由>` ⛔ 不是合法出口。 +- `Restart-when: manual — <理由>` ⛔ 不是合法出口。 - 无机制可唤醒的卡 ⛔ 不 hold:关 not planned,理由/出处载关单评论;重开免费,维护者可否决。 - 缺陷卡 ⛔ 不藏进 hold 也不自行关闭:可复现且用户可达 ⇒ 回 `pm:queue`。 - declared≠enforced 观察类 ⇒ 转 enforce-or-remove 通道;真 won't-fix 候选 ⇒ 逐卡进决策箱。 @@ -173,7 +173,7 @@ PM 的工作是循环:选卡 → 认领 → 派发 → 收集 → L1 审核 → | `domain:spec` | `packages/spec` 整包:schema 形状、`contracts/**`、退役行为半边、strictness 台账;describe/JSDoc/墓碑散文/错误 guidance 与 alias 表;`packages/spec/scripts/**`、`packages/spec/docs/**` 及按锚定规则的例外归本域的工具链(域边界枚举与席内分派见 `references/domains/spec.md`) | | `domain:ui` | `ui/**` 全部代码:`@object-ui/*` 库与 `ui/apps/*`、`ui/packages/types` 与 schema 语料、`ui/scripts` 与门禁工具、文档随所记录的面走;`packages/console`(dist 由 `pnpm console:build` 生成 ⛔ 不手改);协议恒归 `domain:spec`,受管面归 `domain:skills`;见 `references/domains/ui.md` | | `domain:cloud` | 涉 cloud(专题打 `area:cloud`)即整卡归 cloud PM(`repo:cloud` 席):读或改 cloud 代码、生产方或带 cloud 半边;本仓车道 ⛔ 不认领;只缺事实读数者留车道敲信箱;cloud PM 跟到关卡,余下本仓活写明 cloud 事实后另立卡;判据见 `references/cross-repo-coordination.md` | -| `security` · `l2-review` · `eval`(车道,无 `domain:*` 标签) | 本仓安全公告(私有仓卡归该仓车道,cloud 即上行);席位 `security#N` 见 `references/lanes/security.md`;永不公开的规则只住 `references/security-findings.md`。L2 席、AI 评测席见 `references/lanes/l2-review.md`、`references/lanes/eval.md` | +| `security` · `l2-review` · `eval`(车道,无 `domain:*` 标签) | 本仓安全公告(私有仓卡归该仓车道,cloud 即上行);席位见 `references/lanes/security.md`;永不公开的规则只住 `references/security-findings.md`。L2 席、AI 评测席见 `references/lanes/l2-review.md`、`references/lanes/eval.md` | | `repo:objectstack`(全仓调度,无 `domain:*` 标签) | 跨各域按座位贴点名的专题认领本仓卡;cloud 与安全公告除外;见 `references/lanes/objectstack.md` | | (无固定归属,按落点分诊) | `packages/apps/*`、`examples/*`(归它演练的子系统,测试基建见 devx 行)、`docs/audits/**` | @@ -181,7 +181,7 @@ PM 的工作是循环:选卡 → 认领 → 派发 → 收集 → L1 审核 → - 退役 `domain:*` 只退流通,对象保留;`domain:engine`/`domain:services`/`domain:cli` 读作 `domain:server`。 - `domain:*` 与队列只由分诊落笔;两例外:sub-issue 承父卡域、main-red 锚卡,免审计评论。 - 无分诊审计评论 ⛔ 不得认领;车道席自分诊是上行第三例外,住 `triage-duties.md`。 -- 派发前在飞检查 `node scripts/pm/check-handover.mjs --inflight --paths=PATH[,PATH…]`:待派面对 `pm:dispatched` 卡认领申报面本地求交、不另发查询。 +- 派发前在飞检查 `check-handover.mjs --inflight --paths=PATH[,PATH…]`:待派面对 `pm:dispatched` 卡认领申报面本地求交、不另发查询。 - 越界只四通道:跟到底的越界面、无主阻塞项、main-red 锚卡、spec.md 搭车。 - 合并队列是共享串行资源:车道买到并行编写,非并行落地。 - 谁发现 flake 谁修或立单,⛔ 不绕行。 @@ -222,9 +222,8 @@ PM 的工作是循环:选卡 → 认领 → 派发 → 收集 → L1 审核 → - 或修复需破坏性/难回滚动作;其余归 PM 裁量:派发与排序,维护者否决窗口而非许可门。 - 新键/值/导出名有先例(spec、生产者或标准同词同概念):席位点名先例,否决窗口落地。 - 人工地板与风险/工作量判据(`triage-duties.md`)任一命中即呈维护者,⛔ 不入 PM 裁量。 -- 不升级类(碰产品行为或契约形状即报 fork):恢复不变量;任务顺序;验证策略;说明书脱节。 -- 四类记账事同属不升级类,恒以无产品可见行为变化为界:去重与卡片合并;台账与记账整理; -- 纯文档措辞更正(无契约声明改动);既有门禁内部参数与盲区修复(加强,非削弱,非新增)。 +- 不升级类(碰产品行为或契约形状即报 fork):恢复不变量;任务顺序;区边界;验证策略;说明书脱节。 +- 四类记账事同属此类,恒以无产品可见行为变化为界:去重与卡片合并;台账与记账整理;纯文档措辞更正(无契约声明改动);既有门禁内部参数与盲区修复(加强,非削弱,非新增)。 - dev 的 `needs_decision` 一律呈人工:席位附报告转决策线程(含「疑属不升级类」),⛔ 不代答。 - 第三档:带前提的裁决,亦由人工下,三件套缺一不可:① 裁决(选定路线)。 - ② 把裁决挂在具名、可证伪的前提上,派发令要求 dev 先验前提再动手。 @@ -309,8 +308,8 @@ Account: `` (the seat's linked user as `GET /user` answers it; alw Branch: `claude/issue--` Worktree: `-issue-` Domain: `domain:` -Seat: `repo:#` | `epic:##` (this PM's seat; absent = seat 1) -File surface: `<预期触碰的目录>` (stop on breach; explain in the report) +Seat: `repo:@` | `epic:#@` (this PM's seat, as it signs) +File surface: `FILE`, `FILE` (目录项后紧跟 `(reason: …)`;同名测试、生成物与 changeset 不列;stop on breach; explain in the report) Container & model: ``, `mode:subagent | mode:cloud | mode:thread`, `model: <档位词,引当次 --tier 输出;天花板拼 CONTRACT_REVIEW_TIER,同行引其 MANDATORY 路径行或 reason:(逐卡裁决,或常设档位令的 id 与时刻);⛔ 不抄模型 id>`, `effort: ` Clause-②: yes | no Metadata-protocol: added | narrowed | semantic | none (the kind of change to what a metadata author can write; levels: AGENTS.md's Post-Task Checklist step 3; the dev copies it beside `Clause-②:` into the PR body and each changeset body; a kind other than `none` or a `(narrowing)` arm owes the PR body a third line, from the diff: `Skills-docs: updated here | follow-up owed — FILES | follow-up #N | none — REASON`; `updated here` = the diff teaches it in the docs (in `skills/**` only on `domain:skills` PRs, else `follow-up #N`) and its evals exercise it; the seat files the owed card, rewriting `owed — FILES` to `#N` before ACCEPT via `references/seat-post-protocol.md`'s PR-body line) diff --git a/.claude/skills/pm-dispatch/references/area-lease.md b/.claude/skills/pm-dispatch/references/area-lease.md index 2d65a67595e..d68c08314eb 100644 --- a/.claude/skills/pm-dispatch/references/area-lease.md +++ b/.claude/skills/pm-dispatch/references/area-lease.md @@ -1,13 +1,11 @@ # 区域租约模式(area-lease) -本模式 = 一席 + 按需分区 + L1 线程 + 区域 ACCEPT 后自落地;席留 W0、路由、受管面与台账。 - ## 分不分区,动态定 - 区是席内的文件簇租约,只防两个 dev 同时改同一批文件,⛔ 不定席取哪张卡:取卡照座位贴点名的专题(`area:*`、epic)与级。一个 `area:*` 可切成几区,也可并入现有区。 - 坐席、每次交接或换班时席位重判三件:分不分、分几区、边界;⛔ 不沿用上一班的表。 - 分区阈值(经验):可认领卡 ≥15 张且跨 ≥3 个互不相干的模块簇;不足即照常按卡认领。 -- 边界按卡触及的文件与包聚类,让两区极少改同一函数;⛔ 不按卡标题或词汇分。 +- 边界按卡触及的文件与包聚类;⛔ 不按卡标题或词汇分。 - 排空的区并入邻区,积压即再拆,⛔ 不抬一容器 dev 上限(住项目记忆)。 - 租约表(区→路径→线程会话)住座位贴,任一列变或线程轮换即重写,为唯一记录。 - L1 线程每 3 活跃区一条,新开名 `L1-a`、`L1-b`…,在跑留原名。 @@ -17,7 +15,7 @@ ## 开席 1. 席位会话坐席:座位贴存根、自有信箱(`project-forms.md`)、租约表。 - - 信箱一步恒不省;重坐、换号或移座恒开新信箱。 + - 信箱一步恒不省;重坐恒开新信箱。 2. 每区一条项目线程,由协调者开(`coordinator.md`);L1 线程照上节。 - 开场消息逐字带:「照 `execution-duties.md`〈定档〉:认领 Container & model 行写档位与 effort,派 `os-dev` 显式传 model、effort 并贴该行」 3. 维护者在每条新席线程亲写一句授权行:auto mode 只认本线程维护者原话,转述与点选不算。 @@ -35,12 +33,13 @@ - `Pre-claim deps:` 卡点名的 `Blocked-by:`、「after #N」逐个已合;热文件照下文重叠检查。 - `Prior rulings read:` 照 `decision-analysis.md`;grep `docs/adr/**`、链卡(⛔ 行在内)与反向 pin 测试;记录冲突,或路线改门的可见行为超出本卡裁决,同作不过。 - 重叠检查:认领前与每次推前跑 `overlap-check.mjs`;exit 1 排所列 PR 后,3 补前提重跑。 +- 认领加宽:补 `Claim amendment` 前重跑 `check-handover.mjs --inflight --paths=PATH[,PATH…] --card=N`(只填新增文件与本卡号);无交即补;撞他人认领 ⇒ 该部分排其后(`Notify: serial`)或拆成带 `Blocked-by:` 的卡,⛔ 不越过。 - 认领照 `execution-duties.md` 派发原子对与〈定档〉,`Claim:` 带 `Area: <区>` 行。 - 认领后回读(SKILL.md 标签写四步)只查 `pm:dispatched` 与 assignee,缺即重挂;首推即开 draft PR。 - 认领前照 `dispatch-runbook.md` 派发前置核前提;开线程请求交席位攒批(`coordinator.md` 三)。 - 写码与开发期读码全经 `os-dev` 等子代理(一卡或一组耦合卡,文件面不相交)。 - 同系列卡可从前卡分支起步(AGENTS.md §2 主干形,⛔ 不叠 PR);新测试建按卡命名的新文件,AGENTS.md 共享 harness 规则适用时除外,由重叠检查定排队。 -- 席线程只协调,⛔ 不读 diff 与日志;ACCEPT 欠的自读(`contract-review.md`、〈路径分叉〉)除外。所落 PR 欠的红检查读日志(`readings-ci.md`)派子代理读,一读兼守本条与该文。 +- 席线程只协调,⛔ 不读 diff 与日志;ACCEPT 欠的自读(`contract-review.md`、〈路径分叉〉)除外。所落 PR 欠的红检查日志派子代理读(`readings-ci.md`)。 - 每区 dev 位空即补;逐位上张 PR 入合并队列才领下张,此前跑修复轮;Tier H 或待裁 PR 让位。 - 席每轮逐区查,核认领 Container & model 行;取卡照点名范围次序,p0/p1 插队;p3 留收口或搭同文件 PR 成批(每 PR ≤5 卡)。 - 认领必答:同区卡过 `execution-duties.md` 折叠五门即默认合一 PR,否则串行;额度墙亦照该文。 @@ -48,12 +47,15 @@ - 送审:≤50 行、只改文本或测试、`Clause-②: no` 且无他契约面 PR 由区照 `l1-review-checklist.md` 自审落地,ACCEPT 点名自审;余者由 L1 线程 ACCEPT 读,先于 `contract-review.md` 不起第二个 agent。 - 契约记录只欠 `contract-review.md` 四面,head 移动照其例外;同 patch-id 干净合 main 只保 ACCEPT。 - 落地:区先读 `check-governed-merges.mjs --pr N`;非受管 PR 照 `landing-operations.md` 自落,受拒报原文。 -- PASS 且全绿的非受管 PR 10 分钟内落地;挂前先查 PR 上已有落地评论,有即 ⛔ 不再挂。 +- PASS 且全绿的非受管 PR 10 分钟内落地;挂前先查已有落地评论,有即 ⛔ 不再挂。 - 受管面与过线卡的 PR 区 ⛔ 不落,交席位;席位照 SKILL.md〈路径分叉〉①–④ 一笔交棒。 - 席位每轮照 `execution-duties.md` 四件套行复查全部已 PASS 受管 PR,各区转来的一并在内。 - 性能卡与 PR 的提速数字只引已过 L1 的 bench PR 读数;⛔ 不引估算或未过 L1 的本地测量。 -- 席只裁路由(拆并延、归区);改可见行为或解读 ADR 照 SKILL.md〈升级与决策〉呈维护者。 -- 仅呈维护者选项组过独立评审,多卡一批;席自裁 ⛔ 不起评审,自读码。均带 `Prior rulings read:` 行,开工前呈 ⛔ 不在施工中途。 +- 席只裁路由(拆并延、归区;区边界扩、缩、并、释放,重写租约表为记);改可见行为或解读 ADR 照 SKILL.md〈升级与决策〉呈维护者。 +- 卡碰租约外文件 ⇒ 区交席位,⛔ 不留卡等维护者;席三选一:扩区;该区只认领此卡(文件级 `File surface:`,`check-handover.mjs --inflight` 复查);转他席。⛔ 不呈维护者、不起评审,只留否决窗口。 +- 租约外是共享热文件(如 `packages/core`)⇒ 默认逐卡认领、租约路径不动。 +- 两卡排同一超 2,000 行源文件 ⇒ 席立其纯移动拆分卡(`Blocked-by:` 其上 open PR),排队卡随后;拆分 PR 连上限登记 `facade-delegation-registry.json`。 +- 仅呈维护者选项组过独立评审(档位照 `decision-analysis.md`),多卡一批;席自裁 ⛔ 不起评审,自读码。均带 `Prior rulings read:` 行,开工前呈 ⛔ 不在施工中途。 - 席信箱只收:待裁、待落地受管 PR、跨区冲突、阻塞、交接完成;安全照 `security-findings.md`。 - 线程约 150k 即在干净点轮换,⛔ 不在 L1/L2 中途;交接写 `/mnt/project-files/<席>/handover-<区>.md`。 - 省耗:跨线程只传指针;⛔ 不减 dev。 @@ -63,4 +65,4 @@ - 用量近 80% 即交接:停派任何级;在途照 `os-dev.md` 资源纪律 5 推完并点名,每条工作分支留 draft PR;余照 `seat-post-protocol.md` 清单。 - 交接与各区现状落座位贴评论:所有权、open PR、下一步、待批、坑;⛔ 不只留项目或记忆。 -- 新旧账号重叠时座位贴写所有权切分:旧号持有的 PR 清单与新号可取集;新号只取后者。 +- 换号 = 新号坐自己的席(席不过户);旧号的卡逐卡 `Release:` 回队,新号照常认领。 diff --git a/.claude/skills/pm-dispatch/references/contract-review.md b/.claude/skills/pm-dispatch/references/contract-review.md index 57d8c3717b4..8b8167042b8 100644 --- a/.claude/skills/pm-dispatch/references/contract-review.md +++ b/.claude/skills/pm-dispatch/references/contract-review.md @@ -20,7 +20,7 @@ - 送审路由只住此处:车道能取 `CONTRACT_REVIEW_TIER` 才自审;取不到(账号够不到、配额拒 429、 维护者限配)⇒ ⛔ 不降档 ⛔ 非分诊,落交接行并同笔请 L2 席(照 `lanes/l2-review.md`); 无 L2 席在座改点能取该档的兄弟席,皆无则挂等 L2 标记留欠审表待 (a)(b)(c)。交接行: -- `Contract-review-handoff: — CONTRACT_REVIEW_TIER unavailable (, ) · head ` +- `Contract-review-handoff: — CONTRACT_REVIEW_TIER unavailable (, ) · head ` - 欠审 PR(含 draft)现 head 无记录无活认领且 (a)(b)(c) 之一 ⇒ 车道达档自审或交接,⛔ 非分诊 - (a) 交接行/敲门点名现 head(同轮所点席接)或带等 L2 标记;(b) 现 head 已等满一轮(`seat-lifecycle.md`); - (c) 车道收班或离总表,欠审入交班简报;L2 席只接 (a) 所点、自记录 delta、他席皆禁之 head。 diff --git a/.claude/skills/pm-dispatch/references/coordinator.md b/.claude/skills/pm-dispatch/references/coordinator.md index a809d0a4536..7e0197b0b84 100644 --- a/.claude/skills/pm-dispatch/references/coordinator.md +++ b/.claude/skills/pm-dispatch/references/coordinator.md @@ -4,21 +4,21 @@ ## 一、车道归属登记在座位贴(coordinator 开席位线程前读;席位线程坐席时读) -- 项目管哪些车道只由项目指令声明;每条车道开一个席位线程,坐该车道空着的座位贴。 -- 一个项目在一条车道默认一席,维护者明说开座位(「开座位」「再开一个座位」)才加席。维护者对本项目已有席的车道再点 `area:*`(「接 area:X」「再开一个 area:X」)⇒ 交给该席:席把 `area:X` 写进座位贴标题与接卡行,照 `area-lease.md` 分区(自开一区或并入现有区);⛔ 不另开席位线程、座位贴、信箱或巡检。 +- 项目管哪些车道只由项目指令声明;每条车道开一个席位线程,坐本账号在该车道的座位贴(无则问维护者一次)。 +- 一个账号在一条车道恒一席,席不过户。维护者对本项目已有席的车道再点 `area:*`(「接 area:X」「再开一个 area:X」)⇒ 交给该席:席把 `area:X` 写进座位贴标题与接卡行,照 `area-lease.md` 分区(自开一区或并入现有区);⛔ 不另开席位线程、座位贴、信箱或巡检。 - 车道没有本项目的席时照常开席;下文 L2 积压加开照旧。 - 席位线程在贴的说明段写「由 X 账户的项目负责」;贴协议与互斥照 `seat-lifecycle.md`。 -- 一车道归一项目:座位贴 🟢 写他账号 ⇒ 车道已有主;仲裁者是座位贴,⛔ 不是项目记忆。 -- ⛔ 不坐别席,另一项目在飞卡由其席跟完;维护者指令行改写 ⇒ 按 `project-forms.md` 接管。 -- L2 积压 ⇒ 自开一条 `l2-review` 席位线程,⛔ 不先问维护者,开后在项目聊天说一句。 +- 座位贴 🟢 写他账号 ⇒ 是他账号的席;仲裁者是座位贴,⛔ 不是项目记忆。 +- ⛔ 不坐别席,另一项目在飞卡由其席跟完;维护者强制接管令照 `project-forms.md`,只取卡。 +- L2 积压 ⇒ 在本账号的 `l2-review` 席下加开一条线程,⛔ 不先问维护者,开后在项目聊天说一句。 - 积压 = 就绪 head 等 L2 记录逾约 30 分钟,或在座审核席人均排队逾约 3 个 head。 -- L2 新席坐空座、开信箱、按认领分行;队列排空即签退加开席,⛔ 不留闲席;用量墙照第六节。 +- 加开线程按认领分行;队列排空即签退,⛔ 不留闲线程;用量墙照第六节。 ## 二、跨车道取卡(coordinator 每次唤醒读) - 取卡面 = 各车道 open 卡,次序现读 `card-pick.mjs --order <序>`;判据照 `execution-duties.md`。 - 维护者只说改级 ⇒ 只落级,评论照 `filing-gate.md` 引原话;⛔ 不借此开线程,照取卡全序。 -- 每张卡交其车道的席位线程;车道无席位线程而座位贴空着 ⇒ 先开席位线程再交卡。 +- 每张卡交其车道的席位线程;车道无席位线程而本账号的席空着 ⇒ 先开席位线程再交卡。 - 维护者 ⛔ 不逐卡点名车道:车道读卡 `area:*` 与父单;S/M 分流见 `dispatch-runbook.md` 卡线程节。 ## 三、全项目一个上限,p1 先(coordinator 调度读;席位交候选时读) diff --git a/.claude/skills/pm-dispatch/references/cross-repo-coordination.md b/.claude/skills/pm-dispatch/references/cross-repo-coordination.md index 21ca95053fa..2e048064e53 100644 --- a/.claude/skills/pm-dispatch/references/cross-repo-coordination.md +++ b/.claude/skills/pm-dispatch/references/cross-repo-coordination.md @@ -6,10 +6,10 @@ - 单车道仓 `repo:*` 席自理机械三务,⛔ 不产 `domain:*`;决策卡入本仓收件箱,不落 objectstack。 - 机械三务 = 自扫 sweep、自打 `type`、自做首触(含 `finding`;业务理由归召唤的总监席)。 - 新仓登记是一张清单:座位贴、标签、类别归属、门禁盘点、写身份锁移植(deny + hooks)。 -- 新仓三件:加入 `GOVERNED_REPOS`、安装车队 App、写 `lanes/.md` 宪章;应用仓无分诊席。 -- 新仓准入只问一句:真需要常设席位吗;hotcrm 宪章见 `references/lanes/hotcrm.md`。 -- 车道可分席(席号 `· seat N`):忙时一车道开多席,闲时收归一席;每席独立座位贴。 -- 认领评论带 `Seat: <席>#N` 行申报席号(缺省席 1);同席认领互斥,他席认领不触发自退。 +- 新仓三件:加入 `GOVERNED_REPOS`、安装车队 App、宪章住新仓(`lanes/.md` 仅指针);应用仓无分诊席。 +- 新仓准入只问一句:真需要常设席位吗;hotcrm 宪章住 hotcrm 仓 `docs/PRIORITIES.md`(The seat 节)。 +- 车道可分席(一账号一席):忙时一车道开多席,闲时收归一席;每席独立座位贴。 +- 认领评论带 `Seat:` 行申报本席,同署名;同席认领互斥,他席认领不触发自退。 - 拆分触发预登记:单轮逼近 fire 周期,或某仓在全序下持续断粮 ⇒ 按仓拆回多席。 - seam 卡单一归属:归修复落地仓的席,双仓皆动 objectstack 侧主导;涉 cloud 者归 cloud PM(域表)。 - `scripts/pm/**` 等住 objectstack 的全板工具链单写手恒为 objectstack 侧席,他侧上游立卡回链。 diff --git a/.claude/skills/pm-dispatch/references/decision-analysis.md b/.claude/skills/pm-dispatch/references/decision-analysis.md index 295dab0276a..b43eae04a99 100644 --- a/.claude/skills/pm-dispatch/references/decision-analysis.md +++ b/.claude/skills/pm-dispatch/references/decision-analysis.md @@ -19,12 +19,8 @@ - 问题写客户看到的症状、谁碰到、多频繁;选项句写选了客户看到什么、约几个 PR。 - ⛔ 速读不写代码名、文件路径、命令、裁决字母、裸卡号;点到的卡配一句中文说明。 - 四轴、四棱块、自检行、置信缺口、工作量先例归英文分析段,⛔ 不删。 -- 例(新应用的菜单名被存成译文): - - 问题:在中文界面下新建或编辑应用,菜单里自动生成的名字被存成中文;换成英文界面, - 菜单还是中文。 - - 选项:A 存原文,切换语言时菜单名跟着变,一个小 PR;B 维持现状。 - - 推荐 A:应用要给不同语言的人用。 - - 不定会怎样:中文用户建的应用,在其他语言下菜单一直是中文。 +- 英文段首两行 `Served-tier: `、`Analysed-by: `(执笔会话或子代理),⛔ 不写模型 id;标 `CONTRACT_REVIEW_TIER` 须执笔转录过 `verify-review-tier.mjs`(`--tier-evidence=` 只判 L2 记录)。 +- 呈维护者前读该行:缺或未达档 ⇒ 达档重跑,贴带两行的 delta 评论(逐棱同异)再呈;⛔ 永不呈读不出档的分析。 分析段骨架:背景 / Governing text(引文 + grep,或 none found + 检索式)/ 协议声明、是否改协议 / 带 re-check 命令的前提 / 具体问题 / 选项 / 推荐 / 相关单与 PR。正文六项: diff --git a/.claude/skills/pm-dispatch/references/dispatch-runbook.md b/.claude/skills/pm-dispatch/references/dispatch-runbook.md index 7f54d813518..9df4cf81d73 100644 --- a/.claude/skills/pm-dispatch/references/dispatch-runbook.md +++ b/.claude/skills/pm-dispatch/references/dispatch-runbook.md @@ -197,13 +197,13 @@ ## 派发词构造细则 - 兄弟 dev 报告里的成本或形状估计一律落机制假设区并注明须复测。 -- ⛔ 不得穿裁决的衣服转述:被当事实搬运的估计会把错误方向写死,而天真测试照绿。 +- ⛔ 不得穿裁决的衣服转述。 - 前提含 spec 有这个槽位 ⇒ 派发前先读安装包内的活性账本对应行。 - 账本路径 `node_modules/@objectstack/spec/liveness/<域>.json`;`status: 'planned'` = 有 carrier、零消费者。 - 该行的 `authorHint` 就是证词;不读账本的派发让 dev 交出渲染为零的元数据。 - 停条件写法:要证据不要判决,且动作须在本轮内终局。 - 前提与停条件检查要 dev 回报证据面(搜了什么、找到什么),分叉归 PM 判。 -- ⛔ 不写成发现消费者就停下:那把判决权交回被停的一方。 +- ⛔ 不写成发现消费者就停下。 - 可执行性判据:一次性 dev 无中途提问的通道,先问再继续预设了不存在的续接。 - 两种改写都在一轮内闭合:允许做 ⇒ 只做最小编辑,并在报告里单列该判断与回退方式。 - 不许做 ⇒ ⛔ 不要动该文件,让门禁红着并在报告里点名该站点。 @@ -216,6 +216,7 @@ - 文件面两句原文照抄:预期落点是 X。 - 若实测表明真正的生产者在别包,直接按生产者侧修,落点与理由写进报告和 PR 正文。 - 跨包常等于跨车道,PM 事后补跨座位声明。 +- 文件面碰超 2,000 行源文件的卡:派发令点名新代码落进的模块。 - 例:`screen-input-contract.ts` 的 grep 命中「ruling A′」,裁决区写 `A′ · <裁决记录 id>` 与原句: 「a non-number for a numeric field is refused, never silently passed」;路线随之为拒收(A′)。 - 原令「有限数字串转数字」与之相左,应派发前送 L1 线程;栅栏点名 A′ spec 散文在范围。 diff --git a/.claude/skills/pm-dispatch/references/domains/skills.md b/.claude/skills/pm-dispatch/references/domains/skills.md index a73871e7869..430783cd3b6 100644 --- a/.claude/skills/pm-dispatch/references/domains/skills.md +++ b/.claude/skills/pm-dispatch/references/domains/skills.md @@ -26,7 +26,7 @@ - 棘轮以删减付账;砍点逐条核幸存,被砍内容若在别处无家,砍掉就是丢规则。 - 「Instruments serve the fleet」答不出 ⇒ `Suggested-grade: p3` 或建议不做,⛔ 不自入队;级归分诊。 - 内部指令面中文,机器判据恒英文;认领前重读全线程;标签写 read-modify-write 加回读。 -- QA 波次何时开轮只住 `../lanes/qa.md`;`qa#1` 的 §6 例行与场景半边逐开发波跑,不是波次。 +- QA 波次何时开轮只住 `../lanes/qa.md`;QA 席的 §6 例行与场景半边逐开发波跑,不是波次。 ## 席内判断 diff --git a/.claude/skills/pm-dispatch/references/execution-duties.md b/.claude/skills/pm-dispatch/references/execution-duties.md index 8187bb5f052..e32bb93b354 100644 --- a/.claude/skills/pm-dispatch/references/execution-duties.md +++ b/.claude/skills/pm-dispatch/references/execution-duties.md @@ -29,7 +29,7 @@ - fold-or-serial 必答:席或区有 ≥2 张可认领卡同机制或共享热文件,以五门显式答折叠与否。 - 答题处是链首认领(排后的卡另记串行队);不折叠则排队与否照 `area-lease.md` 重叠检查。 - 分诊 `Fold-with: #N` 仅是建议,点名各卡皆无 open PR 才有效;否则各自落地,拒折理由记一行。 -- 并行纪律四条(常规,非豁免):① 认领申报文件面到区域级,排队与否照重叠检查。 +- 并行纪律四条(常规,非豁免):① 认领申报文件面到文件级,排队与否照重叠检查。 - ② 开 PR 前合一次 main;③ 兄弟卡落地后再合一次;④ 冲突交合并队列仲裁,⛔ 不手动排序。 - 其间 ⛔ 不追 main,`behind` 非理由:只冲突/main 致红/踢出队列才合;入队前按落地 K 与 A 节。 - 派发令与复读请求 ⛔ 不令主动合;合后按 AGENTS.md §10 只重跑它所划的门禁。 @@ -45,6 +45,7 @@ - 阻塞项无主 ⇒ 被挡席认领做掉,不限大小;在该卡走完整认领、尊重其热文件串行队。 - 阻塞项在飞 ⇒ 等;卡 PR 叠未合 PR 或 `Blocked-by:` 未合的,合前 ⛔ 不开线程(维护者令除外)。 - 定「等 #N」即同笔写卡 `Blocked-by: #N`+`pm:blocked`;⛔ 只记记忆或评论,无读者即漏派。 +- 解锁:每次巡查与认领前,本车道 `pm:blocked` 卡照 `state-machine.md` 解锁行一笔 `label-write`(replace)回 `pm:queue`。 - 标签序 = NORTH-STAR「Priority」第 3 条(无级殿后),本车道开放卡现读 `card-pick.mjs --order <序>`。 - 开放 = 未派发(无 `pm:dispatched`、无 assignee);在飞的 P0/P1 不挡任何候选,只余取卡全序。 - `card-pick.mjs` 每行印 `domain:*`,读作文件归属;cloud 与安全卡照旧不认领。 @@ -55,12 +56,12 @@ - 一车道多席按全序交替取卡:席 1 奇位、席 2 偶位;只为破交替才发 `split`;认领戳仲裁。 - 周清扫卡归本车道席认领,一 PR 至多约十条互不相关的行;未做到的行滚入下周卡。 - 空闲杂务:无卡可认领或等分诊的车道席对本车道卡做下四件;⛔ 不定级,自分诊例外照旧。 -- ① 交付卫生:交付卡补收尾记录;离手摘 `pm:*` 同笔设下一态;`Blocked-by:` 全关即重验回队。 +- ① 交付卫生:交付卡补收尾记录;离手摘 `pm:*` 同笔设下一态。 - ② 最老 open 卡对 `origin/main` 复读前提与修否并贴证据;已修交分诊或维护者关,⛔ 不自关。 - ③ 新卡预读:复现、查重查询与命中数、一行 `Suggested-grade: p · <理由>`;⛔ 不写级标签。 - ④ 本车道 `finding` 卡补缺的 `reach:` 或复现,或写明为何不合三类。 - ⛔ 不静默等分诊:敲信箱键(`project-forms.md`);报「等分诊」须引所敲评论 id,引不出即未问。 -- 缺审计评论当轮敲 `Request: triage · #n · first-touch audit`,分诊空席敲总监,⛔ 不改报维护者。 +- 缺审计评论而已带 area、type、级 ⇒ 当轮自补(`triage-duties.md` 自分诊 ③),缺级才敲 `Request: triage · #n · first-touch audit`,分诊空席敲总监,⛔ 不改报维护者。 ## 认领(先认领后动工) diff --git a/.claude/skills/pm-dispatch/references/filing-gate.md b/.claude/skills/pm-dispatch/references/filing-gate.md index f005266bab2..e5915f5680a 100644 --- a/.claude/skills/pm-dispatch/references/filing-gate.md +++ b/.claude/skills/pm-dispatch/references/filing-gate.md @@ -31,7 +31,7 @@ - POST 前正文答四件:类别、业务理由、动手的读者(哪席哪步)、查重查询与命中数(含已关)。 - 查重命中 open 卡且修复同机制或同文件:它无认领或归本席 ⇒ 在其下评论(何事、何处、证据、建议级),⛔ 不立卡; 归他席认领 ⇒ 照常立卡,`Dedupe:` 行点名它。评论抬严重度或可达面同笔挂 `pm:retriage`(人定的级除外),分诊答复定级,⛔ 立卡人不改;只读现有查重返回的卡。 -- 车队立的卡(席位、代立发现、清单、分诊)建卡带 area、type、级与正文定级行,缺一拒收。 +- 车队立的卡(席位、代立发现、清单、分诊)建卡带 area、type、级与正文定级行,缺一拒收;留本车道者同轮补审计(`triage-duties.md` 自分诊 ②)。 - 维护者或外部人立的卡由分诊首触补齐 area 与 type;人定的级 ⛔ 不改,分诊与各席同此。 - 改级前读现级末次 `labeled` 事件:带 `performed_via_github_app` 或 bot actor 才算车队,余人定。 - 代维护者落的级:同笔评论行首 `Ruling-ref: priority:pN` 引原话才算人定;⛔ 不凭 bot 判车队。 diff --git a/.claude/skills/pm-dispatch/references/l1-review-checklist.md b/.claude/skills/pm-dispatch/references/l1-review-checklist.md index 59ea2569ef5..c58f7e39d4c 100644 --- a/.claude/skills/pm-dispatch/references/l1-review-checklist.md +++ b/.claude/skills/pm-dispatch/references/l1-review-checklist.md @@ -1,6 +1,6 @@ # L1 审核清单细则 -见 execution-duties.md 〈L1 审核〉;本文逐项展开每份 dev 报告的 L1 判据,对着它过。 +见 execution-duties.md 〈L1 审核〉;本文逐项展开每份 dev 报告的 L1 判据。 ## PR 形态与卡片关系(机械项现读 `l1-face.mjs --pr N`) @@ -18,8 +18,8 @@ - 种类非 `none` 或带 `(narrowing)`:`Skills-docs:` 行在且属实;`follow-up owed` 立卡改 `#N`;缺 ⇒ REWORK。 - changeset/CHANGELOG、`content/docs/**`、`apps/docs/**`:逐句核 diff,ACCEPT 点名所核句,⛔ 不起子代理。 - Tests/docs-only 按仓库分流:本仓库走 `skip-changeset` 标签,⛔ 不走空 changeset。 -- 空 changeset 在本仓库滞留发布;含读者可见生成产物时 dev 改选 changeset 亦对。 -- dev 挂 `skip-changeset` 遭分类器拒 ⇒ 席位转维护者定夺,⛔ 不径自代挂:代做即洗权限。 +- 含读者可见生成产物时 dev 改选 changeset 亦对。 +- dev 挂 `skip-changeset` 遭分类器拒 ⇒ 席位转维护者定夺,⛔ 不径自代挂。 - 其言与席位自核 tests/docs-only 俱备方挂,评论载两者;dev 报告 `deviations` 须逐字载被拒命令。 - 就地修范围外的邻接缺陷 ⇒ 四条件逐条核:同缺陷类、机械、无他人认领、同门禁族。 - 再核 claim 文件面同轮已修订、PR 正文点名该修并载证据;缺一条即判 REWORK。 @@ -32,6 +32,7 @@ - 它住 PR 分支历史或附件,审核人亲跑;证明读数(逐字节相同、导出相等)写进 PR 正文。 - 不在此列:合并后还会再跑的工具,如门禁、regen 步骤、客户照迁移指南跑的 codemod。 - 移动/拆分重构净增远超纯移动:逐文件点清多出各块用途,记进 ACCEPT 评论;点不清判 REWORK。 +- 非测试源文件已超 2,000 行又净增 >300 行:ACCEPT 点名为何进不了新模块,无理由 ⇒ REWORK。 ## 测试与门禁证据(机械项现读 `l1-face.mjs --pr N`) @@ -49,7 +50,7 @@ - 门禁读数钉当前 head:run `head_sha` 或 dev 所抄短 sha 不符 `head.sha`、或没抄 ⇒ 双向不入账。 - ⛔ 非当前 head 上的 `cancelled` 零动作、永不重跑:新推送自带全套 run。 - 席位核对门禁证据 = check-runs(名+结论);本地并集只证本地子集,⛔ 不替缺席者。 -- `!` 或 `(narrowing)`:入队前核 `dogfood_battery` 钉 head、全量、红已修/已报;缺或收窄 ⇒ REWORK。 +- `!` 或 `(narrowing)`:入队前核 head 上 `Dogfood battery (opt-in)` success;缺则挂 `needs:dogfood-battery`。 - 把发送或写挪到应答之后的 PR:dogfood 门禁不跑于 PR、跑于队列,全绿 PR 照样被队列弹出。 - ⇒ 入队前 grep `packages/qa/dogfood/test` 里应答后紧读该副作用的用例,同一 PR 改为有界等待。 @@ -58,13 +59,13 @@ - 收益穿过必经边界之后还在吗:价值主张依赖下游如实转发时,至少端到端验一次。 - 必经边界含 HTTP 错误信封、序列化、日志汇聚、跨进程传输;⛔ 不是每单都做。 - 裁决实施 PR:grep 消费层(REST 信封测试、objectql、runtime)确认旧立场零拷贝。 -- 且真正非法形状的拒收断言仍逐字在,这是派发侧两句的对账。 +- 且真正非法形状的拒收断言仍逐字在。 - 拒收类用例的绿是不是它抛了的绿:判据是验收点含应当被拒收。 - 抽查 diff 里的拒收用例有没有断言 `code` 与 `status`(ADR-0112 信封)。 - 缺 `code`/`status` 断言判 REWORK 补齐,⛔ 不接受绿色输出。 - N 个包全绿要问清方向与时序,否则不算清扫证据;判据是含跨包签名收窄或契约收紧。 - 问一:filter 用的是前缀 `'...pkg'`(下游消费者)还是后缀 `'pkg...'`(上游依赖)。 -- 问二:typecheck 之前建过依赖闭包吗;没建则读的是陈旧 `dist/*.d.ts`,绿可能是假绿。 +- 问二:typecheck 之前建过依赖闭包吗;没建则读的是陈旧 `dist/*.d.ts`。 - 两问都没答案 ⇒ 以全仓门禁结论为准,或判 REWORK 要证据。 ## 前提、停条件与删除 diff --git a/.claude/skills/pm-dispatch/references/landing-operations.md b/.claude/skills/pm-dispatch/references/landing-operations.md index 7e53c62b6c1..3a9fa4601db 100644 --- a/.claude/skills/pm-dispatch/references/landing-operations.md +++ b/.claude/skills/pm-dispatch/references/landing-operations.md @@ -58,7 +58,7 @@ - 车道 PM 的权责三件:验收(L1 清单)、首次入队、确认 MERGED;落地执行在案判决,非自批。 - 首次入队:ACCEPT 后挂 6–9 分钟 flip 定点,到点核门禁 job 结论。 - 绿即落地评论与 `pr_ready`+`automerge_enable` 一笔中继:`label-write --land`;未绿按阶梯重挂定点。 - `--land` 拒 `!`/`(narrowing)` PR,除非卡上最新受信 os-dev-report 的 dogfood 钉 head(`os-dev.md`)。 + `--land` 拒 `!`/`(narrowing)` PR,除非 head 上 dogfood 泳道(`needs:dogfood-battery`)为 success。 - 写节流拒(exit 10) ⇒ 待 `node scripts/pm/write-pace.mjs --status` 现空槽再重试。 - CI success webhook 不可靠:⛔ 不坐等,也 ⛔ 不忙轮询;定点文本照定时器写法纪律。 - undraft 429 ⇒ 卡记 `resets at`,到点一次重试裸 op(`rest-channel.md`),⛔ 不重发评论、不报阻塞。 diff --git a/.claude/skills/pm-dispatch/references/lanes/cloud.md b/.claude/skills/pm-dispatch/references/lanes/cloud.md index c3a0eae1628..e0c3b994539 100644 --- a/.claude/skills/pm-dispatch/references/lanes/cloud.md +++ b/.claude/skills/pm-dispatch/references/lanes/cloud.md @@ -4,7 +4,7 @@ ## 形态 -- 本车道为单车道仓执行座位,可分席 `repo:cloud#N`:在 cloud 仓认领、派发、L1 审核、落地。 +- 本车道为单车道仓执行座位,席 `repo:cloud@ACCOUNT`:在 cloud 仓认领、派发、L1 审核、落地。 - cloud 卡首触归本车道,⛔ 不归分诊(`triage-duties.md` 日对账条);分诊只做下文兜底。 - 卡线程派发令住项目文件的 `pm-orders/cloud/seatN/` 目录。 - 范围:cloud 全仓;本仓 `domain:cloud`+`repo:cloud` 卡认领前先转入,转法与例外照多仓协调规则 1。 @@ -14,6 +14,6 @@ - 首触、定级、取卡序、企业版与安全卡规则见 cloud 仓 `docs/strategy/triage-rules.md` 与 `docs/strategy/core-functions.md`;⛔ 本文件不抄。 - 卡阻于 objectstack 卡 ⇒ 挂 `pm:blocked` 或认领它的本车道席敲阻塞卡车道席 `Request: assist`。 -- 阻塞卡未认领或停车改敲 `triage#1`;每张阻塞卡一次,轮记列明敲了谁;不限级(维护者令)。 +- 阻塞卡未认领或停车改敲分诊席;每张阻塞卡一次,轮记列明敲了谁;不限级(维护者令)。 - 兜底:分诊日对账见 cloud 卡无状态逾 4 h ⇒ 写信本车道各席;分诊 ⛔ 不代打标签。 - 发版板(窗内升 `priority:p0`)在 cloud 仓的生产者是本车道(`seat-post-protocol.md` 发版板节)。 diff --git a/.claude/skills/pm-dispatch/references/lanes/director.md b/.claude/skills/pm-dispatch/references/lanes/director.md index bd4acd9b462..9b190011d84 100644 --- a/.claude/skills/pm-dispatch/references/lanes/director.md +++ b/.claude/skills/pm-dispatch/references/lanes/director.md @@ -78,4 +78,4 @@ - 每张板恰好一个生产者;鲜度节奏、清板三选一见 `../seat-post-protocol.md`。 - 见新 tag 族发布 ⇒ 在 cloud 与每个应用仓立平台版本 bump 单;单张封顶,已有则追评刷新。 - bump 单等待卡清单 = hold 索引(`Restart-when:`/`Blocked-by:` 点名该发布的 open 卡),查询落正文。 -- 车队总表由坐席/接管/收班同笔重生成;一席一行,⛔ 不手改;见 `../project-forms.md`。 +- 车队总表由坐席/收班同笔重生成;一席一行,⛔ 不手改;见 `../project-forms.md`。 diff --git a/.claude/skills/pm-dispatch/references/lanes/eval.md b/.claude/skills/pm-dispatch/references/lanes/eval.md index e0306fc7569..709bb005ad6 100644 --- a/.claude/skills/pm-dispatch/references/lanes/eval.md +++ b/.claude/skills/pm-dispatch/references/lanes/eval.md @@ -3,7 +3,7 @@ ## 座位与唤醒 -- 席位 `eval#N`,首席 `eval#1`;签名、座位贴、信箱同他席;无 `domain:*` 标签、无 `pm:queue`。 +- 席位 `eval@ACCOUNT`;签名、座位贴、信箱同他席;无 `domain:*` 标签、无 `pm:queue`。 - 定时归本席自控(维护者令):自建自调 Routines;各项节奏住座位贴。 ## 评测范围 diff --git a/.claude/skills/pm-dispatch/references/lanes/hotcrm.md b/.claude/skills/pm-dispatch/references/lanes/hotcrm.md index b8cb01c8e55..2c66f5ca422 100644 --- a/.claude/skills/pm-dispatch/references/lanes/hotcrm.md +++ b/.claude/skills/pm-dispatch/references/lanes/hotcrm.md @@ -1,21 +1 @@ -# 车道岗位说明:repo:hotcrm - -见 cross-repo-coordination.md;本文是本席的岗位说明,现值状态恒在座位贴,⛔ 不迁入本文件。 - -## 形态 - -- 本席为姊妹仓执行座位:在 hotcrm 仓认领、派发、L1 审核、落地。 -- ⛔ 不产 `domain:*`;机械三务(含首触定级)按 cross-repo-coordination.md 单车道仓条自理。 -- hotcrm 的规则住 hotcrm 仓,⛔ 本文不抄:`AGENTS.md`(Scope;Product, priorities and the development - process;Platform Upgrades)与 `docs/PRIORITIES.md`(专题、首触、定级、阶段 × 文档)。 -- 跨仓机制照 `cross-repo-coordination.md` 规则 1 与多车道仓条,⛔ 本文不另写:平台缺口卡的立法 - 与 `Blocked-by:` 回链、`repo:hotcrm` 缝标签只给真协调卡、平台卡的 `domain:*` 归分诊。 - -## 常设承诺 - -- 半状态巡查在本仓无载体:无 `half-state-patrol.yml`,无 workflow 即无锚 issue。 -- ⇒ SKILL.md 执行座位职责的读锚第一步在此恒空,代之以手工半边。 -- 手工半边:开新派发前整车道全交集读 open 卡。 -- 逐张核 `pm:dispatched` 与 `pm:in-review` 的交付 PR 是否已合并或关闭,先处置半状态。 -- ⛔ 无锚不等于免检。 -- pm 状态机词表各仓统一,幂等创建在 `scripts/pm/ensure-pm-labels.sh`,对 hotcrm 实跑是落地步骤。 +# 车道岗位说明:repo:hotcrm —— 住 hotcrm 仓 `docs/PRIORITIES.md`(The seat — who runs this backlog 节),⛔ 本文不抄;跨仓机制见 `cross-repo-coordination.md`。 diff --git a/.claude/skills/pm-dispatch/references/lanes/l2-review.md b/.claude/skills/pm-dispatch/references/lanes/l2-review.md index 114c2e3b9d7..11d0a0e669d 100644 --- a/.claude/skills/pm-dispatch/references/lanes/l2-review.md +++ b/.claude/skills/pm-dispatch/references/lanes/l2-review.md @@ -3,16 +3,16 @@ ## 座位 -- 席位 `l2-review#N`,一席一座位贴;坐席账号能达 `CONTRACT_REVIEW_TIER`。 +- 席位 `l2-review@ACCOUNT`,一账号一席一贴;坐席账号能达 `CONTRACT_REVIEW_TIER`。 - 席会话档位与 effort 照 `../execution-duties.md` 定档节;每送审 head 起一个全新只读子代理达档审,⛔ 席内达档审。 -- 每席开一个 `pm:mailbox` PR(`mailbox-open.mjs --seat l2-review#N`);签名、坐席与收班同他席。 +- 每席开一个 `pm:mailbox` PR(`mailbox-open.mjs`);签名、坐席与收班同他席。 ## 路由 -- 先请本账号开的审核席(本项目线程,从线程清单与 `seat-online` 帖找);皆忙才溢至他账号席。 +- 先请本账号的审核席(其下线程,从线程清单与 `seat-online` 帖找);皆忙才溢至他账号席。 - 同项目向 L1/L2 席请审、delta 与回告发线程消息,⛔ 不敲信箱;信箱只留跨账号或跨项目。 - N 席按认领分行:欠审表每个 head 先贴 `Contract-review-claim:` 者持有;后者撤回弃产出。 -- 兜底接 head 只住 contract-review.md 欠审接审行,`check-owed-reviews.mjs` 同读;⛔ 不按席号路由。 +- 兜底接 head 只住 contract-review.md 欠审接审行,`check-owed-reviews.mjs` 同读;⛔ 不按席名路由。 - 每日抽查约 1/5 席位自审记录(≤50 行自落、自做 L2),≤10 条、契约面先;不过即退回该席。 - delta 归原 L2 审核者;L2 席下班留下旧记录 ⇒ 下一 L2 席接 delta,交接行点名它。 diff --git a/.claude/skills/pm-dispatch/references/lanes/objectstack.md b/.claude/skills/pm-dispatch/references/lanes/objectstack.md index b762d104fcc..26a559cec6f 100644 --- a/.claude/skills/pm-dispatch/references/lanes/objectstack.md +++ b/.claude/skills/pm-dispatch/references/lanes/objectstack.md @@ -4,11 +4,11 @@ ## 形态 -- 席位 `repo:objectstack#N`,可多席、多账号;签名、座位贴、信箱、坐席与收班同他席。 -- 一个项目在本车道默认一席(维护者明说开座位才加席);席接哪些 `area:*` 是该席的属性,写在座位贴标题与接卡行。维护者再点一个 `area:*` 是改该席的接卡面并在席内分区,⛔ 不是加席(`coordinator.md` 一)。 +- 席位 `repo:objectstack@ACCOUNT`,一账号一席;签名、座位贴、信箱、坐席与收班同他席。 +- 一个账号在本车道恒一席;席接哪些 `area:*` 是该席的属性,写在座位贴标题与接卡行。维护者再点一个 `area:*` 是改该席的接卡面并在席内分区,⛔ 不另开席(`coordinator.md` 一)。 - 每席照 area-lease.md 分区运作:区线程、L1 线程、区内落地;本文只写全仓与多席特有者。 - ⛔ 非单车道仓席:cross-repo-coordination.md 单车道仓条、seat-lifecycle.md 单车道仓行不适用。 -- 首触与 `domain:*` 归分诊(`triage-duties.md`);本车道立卡带 area/type/级,⛔ 不产、不改 `domain:*`。 +- 首触与 `domain:*` 归分诊(例外见 `triage-duties.md`);本车道立卡带 area/type/级,⛔ 不产、不改 `domain:*`。 - ⛔ 不给卡挂 `repo:objectstack` 标签:按仓认卡;该标签已退流通。 ## 范围 @@ -33,4 +33,4 @@ ## 落地与归维护者 - 落地与交席照 area-lease.md 区内规则与 SKILL.md〈路径分叉〉。 -- 开席、加席、收席由维护者召唤;需裁事项照 SKILL.md〈升级与决策〉。 +- 开席、收席由维护者召唤;需裁事项照 SKILL.md〈升级与决策〉。 diff --git a/.claude/skills/pm-dispatch/references/lanes/qa.md b/.claude/skills/pm-dispatch/references/lanes/qa.md index ad1fc511192..f90d77cce6a 100644 --- a/.claude/skills/pm-dispatch/references/lanes/qa.md +++ b/.claude/skills/pm-dispatch/references/lanes/qa.md @@ -3,7 +3,7 @@ ## 座位与唤醒 -- 席位 `qa#N`,首席 `qa#1`;签名、座位贴、信箱同他席;无 `domain:*` 标签、无 `pm:queue`。 +- 席位 `qa@ACCOUNT`;签名、座位贴、信箱同他席;无 `domain:*` 标签、无 `pm:queue`。 - 自启三信号:新发版 tag ⇒ 冒烟;未暂停 epic 子卡全关 ⇒ 里程碑验收;每周一轮例行。 - 维护者仍可另敲一轮;发版只认新 tag 族读数,⛔ 不凭口头或分支名自判发版。 diff --git a/.claude/skills/pm-dispatch/references/lanes/queue.md b/.claude/skills/pm-dispatch/references/lanes/queue.md index 43ab7ad8194..c8ca5611089 100644 --- a/.claude/skills/pm-dispatch/references/lanes/queue.md +++ b/.claude/skills/pm-dispatch/references/lanes/queue.md @@ -3,7 +3,7 @@ ## 座位与唤醒 -- 席位 `queue#N`,首席 `queue#1`;签名、座位贴、信箱同他席;无 `domain:*` 标签、无 `pm:queue`。 +- 席位 `queue@ACCOUNT`;签名、座位贴、信箱同他席;无 `domain:*` 标签、无 `pm:queue`。 - 每 15–20 分钟巡查合并队列;⛔ 不持车道卡、不派 `os-dev`、不开 PR,自己不落地任何东西。 - 落地最多的席位不兼本席:判插队与出队有利益冲突;它只管自己在队的 PR。 - 本席未开时,分诊在每小时巡查里临时兼本章程:p0 队列 flake 修复获 ACCEPT 当轮照 (a) 插队, diff --git a/.claude/skills/pm-dispatch/references/lanes/review.md b/.claude/skills/pm-dispatch/references/lanes/review.md index df46a7c728e..4ffa6041eac 100644 --- a/.claude/skills/pm-dispatch/references/lanes/review.md +++ b/.claude/skills/pm-dispatch/references/lanes/review.md @@ -1 +1 @@ -已更名:章程住 `l2-review.md`;在座 `review#N` 席签名与致它的行仍写原名,只新席用 `l2-review#N`。 +已更名:章程住 `l2-review.md`;`review` 与它同一车道,新写用 `l2-review@ACCOUNT`,旧名记录仍读。 diff --git a/.claude/skills/pm-dispatch/references/lanes/security.md b/.claude/skills/pm-dispatch/references/lanes/security.md index e8cf6ae5dd0..6c687dad5aa 100644 --- a/.claude/skills/pm-dispatch/references/lanes/security.md +++ b/.claude/skills/pm-dispatch/references/lanes/security.md @@ -6,7 +6,7 @@ ## 座位 -- 席位 `security#N`,首席 `security#1`,只管本仓公告;签名、座位贴、坐席与收班同他席。 +- 席位 `security@ACCOUNT`,只管本仓公告,持公告者见贴;签名、座位贴、坐席与收班同他席。 - 无 `domain:security` 标签、无 `pm:queue`、无文件面:私卡照第 3、9 节,修复落在归属包。 - 坐席者 = 能读写本仓安全公告的账号(管理员或安全经理)的会话;读不了 ⛔ 不坐。 - 公告的读、建与写只照第 3 节;中继拒或本席空缺照第 3、9 节。 @@ -58,4 +58,4 @@ ## 收班 -- 台账与每份在飞公告留在座位贴,⛔ 不释放进 `pm:queue`;接任者坐席即接台账。 +- 台账与每份在飞公告留在座位贴,⛔ 不释放进 `pm:queue`;接职者坐席即接台账。 diff --git a/.claude/skills/pm-dispatch/references/project-forms.md b/.claude/skills/pm-dispatch/references/project-forms.md index 8fcf0c37836..23da8b42e54 100644 --- a/.claude/skills/pm-dispatch/references/project-forms.md +++ b/.claude/skills/pm-dispatch/references/project-forms.md @@ -12,7 +12,7 @@ - 首词恒为技能目录名 `pm-dispatch`;⛔ 不用 `fleet`,它已是 bot 与中继的名字。 - 席位词 = 中文名或车道文件名:总监 = `director.md`,分诊 = `triage.md`,L2 或复核 = `l2-review.md`。 - 其余席位词同 `lanes/` 下文件名(去 `.md`),如 cloud;验证 = `qa`+`eval` 一席。 -- 一车道多席:协调者取 🟢 行写本账号的那一席;无则取空席;再无则问维护者一次。 +- 一车道多席:协调者取本账号的那一席(`LANE@ACCOUNT`);无则问维护者一次,⛔ 不坐他账号的席。 - 其余一切住本文:⛔ 不往项目里贴模板;⛔ 不在账号层复制技能。 ## 席位是读出来的,不是配出来的 @@ -24,7 +24,7 @@ ## 接管不等撞墙账号 -- 🟢 行写着别的账号 ⇒ 指令行即维护者强制接管令。 +- 席不过户;维护者强制接管令只取卡,逐卡照下行。 - 四件形状见 `execution-duties.md` 认领节;台账 = 标签 + assignee + `Claim:` + `head:claude/` PR。 - 台账按 `assignee:<旧登录名>` 读;⛔ 项目记忆与共享目录永不是台账,只是本账号的缓存。 - 项目记忆只存维护者原话(带时间)与技能指针,⛔ 不复述规则;与技能相左 ⇒ 照技能,删该行。 @@ -32,9 +32,9 @@ ## 信箱 PR -- 每席一个 draft PR,键是席位 ⛔ 非账号,epic 席 `epic:##` 同样开;标签 `pm:mailbox`+`pinned`。 +- 每席一个 draft PR,键是席位 ⛔ 非账号(分支 slug `LANE_ACCOUNT-0`),epic 席 `epic:#@ACCOUNT` 同样开;标签 `pm:mailbox`+`pinned`。 - 正文首行 `Mailbox-of: <席位> · `;坐席即开(`mailbox-open.mjs`)并订阅,存根记 `Mailbox:`。 -- 永不合并,不欠 CI,落地与台账查询排除它;移交或换账号关旧开新;评论首行 `To: <席位>`。 +- 永不合并,不欠 CI,落地与台账查询排除它;评论首行 `To: <席位>`。 - 次行恒为一键,下列事件必敲;一事一行 ≤200 字节,只写键与编号;表外即半态。 - 跨账号或跨项目:车道→L2 或兄弟席 `Request: contract-review`;反向随记录 `Notify: contract-review`。 - 任一席→分诊:p0 嫌疑、main 红、确定性队列红 `Request: urgent-triage`。 @@ -47,7 +47,7 @@ - p0/p1 卡阻于他车道未认领或闲置 ≥3h 的卡:认领席(未认领则分诊)→其车道 `Request: assist`。 - 收方随记录(认领/ETA/不接理由)回 `Notify: assist`;ETA 或 2h 无记录交分诊,彼道无席呈决策卡。 - 上下线→兄弟席与分诊 `Notify: seat-online`、`Notify: seat-offline`;清单变→兄弟席 `Notify: split`。 -- 持发现席→`security#1`:公告建成或误公开卡挂标即 `Notify: security`,只带编号;私有仓卡不敲。 +- 持发现席→持公告的安全席:公告建成或误公开卡挂标即 `Notify: security`,只带编号;私有仓卡不敲。 - 分诊→认领席:认领卡或 open PR 闲置 ≥3h `Request: progress`;反向随记录 `Notify: progress`。 - 记录 = 项上写下一步与 ETA 的评论、§C 停车或释放;同项 60 分钟一敲,答 ETA 到期前不敲。 - ⛔ 不敲:回执、重发;收方订阅 PR 已载者;停车或待决策卡的项的进度;问维护者走决策卡。 @@ -57,4 +57,4 @@ ## 总表 -- objectstack 置顶 issue「车队总表」,一席一行;坐席/接管/移交重生成,列照 `fleet-roster.mjs`。 +- objectstack 置顶 issue「车队总表」,一席一行;坐席/收班重生成,列照 `fleet-roster.mjs`。 diff --git a/.claude/skills/pm-dispatch/references/readings-ci.md b/.claude/skills/pm-dispatch/references/readings-ci.md index 8e915f5f6c0..f9df157458f 100644 --- a/.claude/skills/pm-dispatch/references/readings-ci.md +++ b/.claude/skills/pm-dispatch/references/readings-ci.md @@ -45,5 +45,5 @@ - corepack 下载 pnpm 可在检查体开跑前崩 undici(`assert(!this.paused)`)⇒ 是基础设施红。 - `check-governed-merges` 浅克隆上拒答而非少报,并报未审计仓数;补救 `git fetch --shallow-since=`。 - ⛔ 不越过该拒答自行枚举:短清单读作合规;加深日期取窗口起点之前,不猜深度。 -- `check:pm-dispatch-gates` 1216–1246 秒超容器上限 ⇒ 不走锁,detach 加 `tail --pid=$!`;超时非读数。 +- `check:pm-dispatch-gates` 快档前台 404 秒(闲盒 4 核,0124851b)⇒ 前台跑,不走锁;超时非读数。 - `check-half-states.mjs` 连 `--help` 都跑整仓 I/O ⇒ 早读到的输出文件是空的,不是干净的。 diff --git a/.claude/skills/pm-dispatch/references/seat-lifecycle.md b/.claude/skills/pm-dispatch/references/seat-lifecycle.md index 42c56fa9d78..dc96712387c 100644 --- a/.claude/skills/pm-dispatch/references/seat-lifecycle.md +++ b/.claude/skills/pm-dispatch/references/seat-lifecycle.md @@ -5,9 +5,9 @@ - 开轮互斥:fire 后首个写动作前读四个读数,未收班活动任一未满一轮 ⇒ 自退(一轮 60 分钟);现读 `round-open.mjs`。 - 读数一、二:最近的收班简报,与晚于它的最新开轮标记。 - 开轮标记是轮中会话在座位贴上的唯一痕迹;标记可漏写,认领不可省。 -- 读数三:本车道 `pm:dispatched` ∪ `pm:queue` 卡最新非本 session 同席号的 `Claim:` 评论。 +- 读数三:本车道 `pm:dispatched` ∪ `pm:queue` 卡最新非本 session 同席的 `Claim:` 评论。 - 或收班简报后卡分支有推送:推即认领,欠一条 `Claim:`。 -- 读数四:本车道 `state=CLOSED` 按 `updated_at` 降序首张带同席号且非豁免 `Claim:` 卡的 session ID。 +- 读数四:本车道 `state=CLOSED` 按 `updated_at` 降序首张带同席且非豁免 `Claim:` 卡的 session ID。 - 不占席:评审链、总监席,在任 PM 会话与其租约表会话两两互见(含推送);三、四只增自退。 - 总监席多场并行、无在任者:读数一、二与自退对它不成立;执行席互斥照旧。 - 收班简报是前任不再写的显式声明,是释放标记不是锁:简报即最新事件 ⇒ 立即坐席。 @@ -21,9 +21,9 @@ - 贴 = 座位(标签 `pm:seat`),正文固定四段现值:当前 PM / 继承台账 / 热文件串行队 / 说明。 - 项目席的贴是存根,只留他账号要读的;模板见 `seat-post-protocol.md`。 -- 存根外的姿态、台账与轮报住项目;标题、assignee、坐席审计评论与跨账号移交简报照旧。 +- 存根外的姿态、台账与轮报住项目;标题、assignee、坐席审计评论与收班简报照旧。 - 正文只由在任座位 PM 编辑且为权威;标题(仅慢状态)与 assignee 是派生视图,三者同笔更新。 -- 维护者强制接管令取席位、队列、在飞卡、未起工卡与待落地 PR;⛔ 不等原认领者注记。 +- 维护者强制接管令取队列、在飞卡、未起工卡与待落地 PR,⛔ 不取席位(席不过户);⛔ 不等原认领者注记。 - 子代理 dev 的返回消息、探活与续派只在派发会话;落地或 `Release:` 后归新席位。 - 贴内只放指向车道文件的指针,升级走技能 PR,⛔ 不手抄接力。 - 写侧刷新点 = 轮次边界;中途状态由卡上 claim 评论与指针行、PR 上 `## 席位核对` 承载。 @@ -38,10 +38,9 @@ - 坐席同笔:建自绑巡查 routine、开信箱并订阅、存根记 `Patrol:` 与 `Mailbox:`、发 `seat-online`。 - 席会话的档位与 effort 照 `execution-duties.md` 定档节;坐席时低于即登记行注明,请账号主人照该值重开。 - 席会话 ⛔ 中途不改 effort;要另一档就起隔离子代理。 -- 收班同笔删 routine、关信箱、发 `seat-offline`;强制接管者代发 `seat-online`(`project-forms.md`)。 +- 收班同笔删 routine、关信箱、发 `seat-offline`。 - 下班席(`seat-offline`,或两敲 `Request: progress` 无答走接管四件)的在飞归同车道在线兄弟席。 - 兄弟席 `Resume-from:` 引简报或轮次记录认领;待裁先等字;无兄弟席「待席」;公告归安全席。 -- 移座:让席旧号仍排空即移空席、开自有信箱,原贴写所有权切分,毕评 `ownership transferred`。 - 离任留守只写点名的已 ACCEPT 待队列或待人批 PR,⛔ 不读队列、不新派发、不碰未点名卡。 - 留守卡在 `seat-offline` 同笔落其车道一态并清 assignee;漏者分诊读到该敲门当轮代落。 - 换班报告默认零建议,只收三类:原则错/缺、可机械化项、平台事实变化(事实表改一行)。 diff --git a/.claude/skills/pm-dispatch/references/seat-post-protocol.md b/.claude/skills/pm-dispatch/references/seat-post-protocol.md index 071e661bca2..2d09500f1e6 100644 --- a/.claude/skills/pm-dispatch/references/seat-post-protocol.md +++ b/.claude/skills/pm-dispatch/references/seat-post-protocol.md @@ -4,7 +4,7 @@ - 四段现值由在任座位在写侧刷新时收缩;⛔ 岗位说明 PR 不代改贴正文。 - 标题即状态板,固定格式 `[PM seat] <座位名> — <状态>`;`label:pm:seat` 列表页即舰队状态板。 -- 多席车道每席一贴,座位名带席号后缀 `repo:X · seat N`;席 1 省略后缀,沿用现贴。 +- 座位名恒为 `LANE@ACCOUNT`,各车道同,`@` 前后无空格;一账号一车道一席一贴,席不过户。 - 状态词表:`🟢 ` 在任、`🟢 Routine`、`⏳ vacant`、`⏸️ paused`。 - assignee = 在任 PM 的 GitHub 账号,退场或回收时摘除;无 assignee = 空缺,与标题互校。 - 例外:Routine 座位的 bot 通常不可 assign,以标题为准。 @@ -15,10 +15,12 @@ - 班次叙事 ⛔ 不进贴正文:逐卡状态在卡与 PR 上必填,合计走轮次报告。 - 存根四项:在座账号与项目 · 上任时刻 · 热文件串行队 · 指针行「姿态台账住项目」。 - 加 `Patrol:` `Mailbox:`,可选撞墙注记(HH:MM 恢复);坐席、串行队/cron 改、撞墙、移交才刷存根。 -- 标题与说明段接卡行同写本席接的 `area:*` 与 epic,工具只读标题;接卡面变即重写,重述、接管、移席照抄。 -- 接管压缩:接任 PM 按四段模板重述新正文;旧账留上版 body revision,审计评论带版本指针。 +- 标题与说明段接卡行同写本席接的 `area:*` 与 epic,工具只读标题;接卡面变即重写,重述照抄。 +- 坐席压缩:继任会话按四段模板重述新正文;旧账留上版 body revision,审计评论带版本指针。 - 热文件串行队收重叠检查(`area-lease.md`)排后的卡与车道章程点名的串行链,跨轮跨班次常设:文件或链 → 有序卡片清单 → 每张卡认领的区域。 -- 新增座位贴(加席)先查 `pm:seat` 索引再立贴,席号取本车道最大席号加一。 +- 新增座位贴先查 `pm:seat` 索引再立贴;离场账号的卡逐卡 `Release:` 回队。 +- 旧 `LANE#N` 记录恒可读、不重发,归其签名账号;在任贴原地改名,改名前署名与 `Seat:` 行仍写旧名。 +- 改名席先以 PR 在 `scripts/pm/seat-numbers.mjs` 落行,合并后才改名;首次切换实测新名不渲染成提及。 ## 活性、写侧刷新与收班 @@ -26,15 +28,15 @@ - 会话座位查最新产出评论的时间戳;回收 = 改正文 + 审计评论。 - 可跑读法:本车道 `pm:dispatched` 卡按 `updated_at` 降序一搜,或读最新认领评论。 - 写侧刷新三时刻:派发、收班、暂停或交接前;时间戳恒取自 `post-stamped.mjs`。 -- 帖与卡正文首行恒为署名 `LANE#N · ACCOUNT · SESSION`;缺即写工具拒发(`post-stamped.mjs` 头注)。 -- PR 正文末非空行署 ``,整篇经 `dispatch.mjs` 的 `issue_patch`。 +- 帖与卡正文首行恒为署名 `座位名 · ACCOUNT · SESSION`;缺或他号签 `LANE@X` 即写工具拒发(`post-stamped.mjs` 头注)。 +- PR 正文末非空行署 ``,整篇经 `dispatch.mjs` 的 `issue_patch`;两处读方亦认旧 `LANE#N`。 - 刷新前回执敲门;`--body` 拦截:评论晚于末次戳 ⇒ `--ack-through=ID`;空座欠账无卡号 ⇒ 拒写。 - 耐久状态只住正文或以 App 写入;正文守中继上限 60,000 字节,超大贴由半状态巡查浮出。 - 协议升级迁移状态或巡检发现正文不符时,当场改正文 + 审计评论。 - Routine 座位的收尾简报也落本席座位贴,即下轮自退守卫的读数。 - 留守写面 = 简报点名的 PR,残余定时器同界;留不了才热移交:收单注记 + 点名看护者。 - 收单注记写评审判据、落地步骤与当前状态;看护只守落地,⛔ 评审判断不可外包。 -- 看护者默认下任座位;在跑云会话经 poke 触发器投递,⛔ 非 `SendMessage` 直投。 +- 看护者默认同车道在线兄弟席;在跑云会话经 poke 触发器投递,⛔ 非 `SendMessage` 直投。 - 收班序列不看维护者措辞:`check-handover.mjs` 退出 0 → 刷正文与标题 → 简报最终一笔。 - 末尾巴合并 ⇒ 贴上一条尾清注记;继任立即坐席,点名集作围栏。 - 标题滞后是可修半状态,坐席时顺手修,⛔ 非阻塞;留守登记(谁、哪些尾巴)= 说明段一行。 @@ -43,17 +45,17 @@ - 巡查改绑 = 继任自建自绑并删旧,`Patrol:` 换号;前任笔迹归继任不自退,旧会话即结束。 - 上下文读数:`get_session`(无参)`external_metadata.context_usage.used_tokens`;读不到或 0 归协调者读。 -## 交接收尾清单(漏一步就是留残缺现场) +## 交接收尾清单 1. 立即停止新派发。 2. 认领卡落地,或同笔 `Release:`+`Resume-from:`+清 assignee 交回 `pm:queue`;`needs_decision` 进决策箱。 -3. 全量枚举本车道队列、决策箱与 findings,成接任台账;等裁决的卡只挂 `needs-user-decision`。 +3. 全量枚举本车道队列、决策箱与 findings,成继承台账;等裁决的卡只挂 `needs-user-decision`。 4. 台账义务逐条带卡号(条件型开 `pm:blocked`+`Blocked-by:`,定时型 `Restart-when:`),正文只放指针。 5. 第 2、3 步由 `node scripts/pm/check-handover.mjs --session=ID --account=LOGIN` 核,退出 0 才写空座正文。 6. 贴正文改 `⏳ vacant` + 台账:前任会话 ID、注销时间、队列快照、串行队、跨车道备忘。 -7. 收班简报与审计评论存档;接任指引 = `/pm-dispatch 接手` + 先读座位贴。 +7. 收班简报与审计评论存档;本账号再坐席先读座位贴。 8. 在飞卡与留跑会话贴里点名(卡号+派发会话 ID);派出的会话离任 PM 自 `archive_session`。 -9. 关本席信箱(`mailbox-open.mjs --close N`),接任者坐席时按席重开;向维护者交最终报告。 +9. 关本席信箱(`mailbox-open.mjs --close N`),再坐席时重开;向维护者交最终报告。 ## 座位 Routine 创建 diff --git a/.claude/skills/pm-dispatch/references/security-findings.md b/.claude/skills/pm-dispatch/references/security-findings.md index c879503232a..ab11d380a94 100644 --- a/.claude/skills/pm-dispatch/references/security-findings.md +++ b/.claude/skills/pm-dispatch/references/security-findings.md @@ -24,7 +24,7 @@ - 只发维护者为该版批准的清单:经中继换正文、定版本、再发布;运行编号记座位贴,⛔ 无正文。 - 两操作皆被拒 ⇒ 会话专递(选 A):机制只在会话交维护者,由其建草稿,⛔ 不换账号重发。 - 回退时座位贴只写不透明编号与状态,⛔ 无细节。 -- 公开仓修复只由 `security#1` 席以无卡派发令照章程按组派 `os-dev`;机制只进派发令与公告。 +- 公开仓修复只由持公告的安全席以无卡派发令照章程按组派 `os-dev`;机制只进派发令与公告。 - 用到公告的临时私有 fork ⇒ 修复从该 fork 落地。 - 私有仓私卡 = 该仓带 `security` 标签的普通 issue,经中继 `issue_create` 立,机制写在其中。 - 私有仓卡归该仓车道,照其规则派修、L1/L2 审核、落地;第 2、6 节照旧。 @@ -56,10 +56,10 @@ - 立卡门、server 与 security 车道、信箱、`checklist-test` 与 `os-dev` 只指向本文,⛔ 不留第二份。 - ⛔ 本规则不新增门禁、不新增标签。 -## 9. 归属:公告归 `security#1` 席,私有仓卡归该仓车道 +## 9. 归属:公告归安全席,私有仓卡归该仓车道 -- 公开仓的公告从接收到发布归 `security#1` 席(章程 `lanes/security.md`),发现者只报不修。 +- 公开仓的公告从接收到发布归安全席(章程 `lanes/security.md`),发现者只报不修。 - ⛔ 不扩本 PR 或分支,不自开修复分支,不在同一面顺手加固;dev 只走第 5 节上报。 - 席位两件事:照第 3 节建私卡;公告敲 `Notify: security · GHSA-ID`,只带编号;私有仓不敲。 -- 中继拒 ⇒ 机制会话里交 `security#1` 或私有仓车道席;席空缺交维护者;发布清单归维护者。 +- 中继拒 ⇒ 机制会话里交安全席或私有仓车道席;席空缺交维护者;发布清单归维护者。 - 任务绕不开它 ⇒ 报 `blocked`,只写「a security item is with the owner seat」;席位停卡,⛔ 不绕行。 diff --git a/.claude/skills/pm-dispatch/references/state-machine.md b/.claude/skills/pm-dispatch/references/state-machine.md index 2ecc3b7b665..51f56f1d168 100644 --- a/.claude/skills/pm-dispatch/references/state-machine.md +++ b/.claude/skills/pm-dispatch/references/state-machine.md @@ -30,7 +30,7 @@ - 工已完而被门禁缺陷卡住者同用本态,⛔ 不设新标签、不重派;`Blocked-by:` 指向门禁卡。 - 正文行 `Unlock-action: re-check PR #M`(重查落地)或 `re-check #N when label <标签> `。 - 只认此二值,别的拼写静默回落重派,散文另起行;停放的 PR 正文须点名那张门禁卡。 -- 目标全关(PR 已合并)⇒ 每日扫描过可安装检查,一条评论放回队列;仍有阻塞即改写该行。 +- 目标全关(PR 已合并)⇒ 车道席每轮(`execution-duties.md`)、分诊每日扫描兜底,过可安装检查,一条评论放回队列;仍有阻塞即改写该行。 - 每日扫描另报:blocked 卡无该行或无 open 目标,互挡与成环,挡路卡级低于所挡,hold 不一致。 - 挡路卡取自身与所挡 open 卡(同仓跨仓同)里最高的级;人定的级 ⛔ 不动,由扫描报维护者。 - `scheduled-full-run-card.yml` 经 `scripts/ci/scheduled-full-run.mjs` 刷新小时红卡时亦放回,规则更窄: diff --git a/.claude/skills/pm-dispatch/references/triage-duties.md b/.claude/skills/pm-dispatch/references/triage-duties.md index d6ad96e3d33..b84bbbd884c 100644 --- a/.claude/skills/pm-dispatch/references/triage-duties.md +++ b/.claude/skills/pm-dispatch/references/triage-duties.md @@ -29,10 +29,13 @@ - 主干全量红与确定性队列红首触定 p0(锚卡、根因卡、full-run 卡);flake 锚卡判确定性才升。 - 例外:一签名 2h 内踢 ≥2 独立 head 组的队列 flake 即 p0;修复合入关卡,2h 无新踢按上行定。 须失败用例 `main` 已有;一 PR 后叠组算一 head,其新红测试即出队;计数插队见 `lanes/queue.md`。 -- 车道席自分诊:本车道卡挡自有在飞(认领卡/PR/落地/拆分链)且证据清楚,方可首触定 p1/p2。 -- 证据 = 卡上引具名失败 check/run、复现读数或 pin 测试;记录照分诊格式贴卡,请分诊复审。 -- 行首 `Ruling-ref:` 引本例外裁决原话;⛔ 不改 `domain:*`、不定 p0(归 main-red)、不碰人工地板。 -- 分诊每轮读上轮以来新贴的自分诊记录,逐条回复确认或改判;复审前席位定级有效。 +- 车道席自分诊三例,限本车道卡、认领前做:① 卡挡自有在飞(认领卡/PR/落地/拆分链)且证据清楚,可首触定 p1/p2, + 证据 = 卡上引具名失败 check/run、复现读数或 pin 测试;② 自立且留本车道的卡,立卡同轮首触 area、type、级 + (`filing-gate.md`)、size 与审计;③ `card-pick.mjs` 报 `no triage audit` 而已带 area、type、级 ⇒ 只补审计,⛔ 不改级。 +- 记录 = 车道签名下英文 `Triage:` 首行审计,行首 `Ruling-ref:` 引本例外裁决原话,末行 `Review: triage`。 +- ⛔ 不改 `domain:*`、不定 p0(归 main-red)、不碰人工地板、cloud 卡与决策箱卡,不并卡、不关卡。 +- 分诊每轮复审上轮以来末行 `Review: triage` 的记录,回帖行首 `First-touch review: confirmed` 或 + `First-touch review: re-graded pN — 理由`,并做跨车道四查(路由、cloud、查重并卡、决策箱);复审前席位定级有效。 - 分诊定级轮读车道 `Suggested-grade:` 行:是输入不是定级,确认或改判,不采纳给理由。 - 分类动作每张三选一,外加一个修复通道;裁定写方向、给六态之一。 - 日对账 fire 读 `check-half-states` 阻塞与决策诸行,照 `state-machine.md` 处置;卡号进轮次记录。 @@ -46,7 +49,7 @@ - `needs-user-decision` = 设计卡、契约形状提案、需要 appetite 的多周程序;只挂 issue。 - 先例已定新键/值/导出名非契约形状提案;分诊审计 ⛔ 不自加门,唯语义/形状真分歧呈人。 - 碰迁移形状或删已发布能力也进决策箱;说明书脱节不进:有裁定出处才是 (b),否则改文档。 -- 决策卡速读居四棱块之上、同题,至多四行业务话;写法与例见 `decision-analysis.md`。 +- 决策卡速读居四棱块之上、同题,至多四行业务话;写法见 `decision-analysis.md`。 - 首行写立卡门类别 ①–④;四类定义、⛔ 清单、四答、理由判据与配额见 `filing-gate.md`。 - `finding` = 三类内待定级:(a) 可复现缺陷(复现或失败探针);(b) 违背已声明契约(引契约文); - (c) AI 写元数据会被运行时拒收或静默丢弃的陷阱;其余进 PR `## Acceptance notes`,⛔ 不立卡。 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 247a913f3b4..93f7c57423d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -612,6 +612,10 @@ jobs: - 'scripts/ci/assert-turbo-remote-cache.mjs' - 'scripts/ci/prune-turbo-cache.mjs' - 'scripts/population-floor.mjs' + # [#38528] The temporal_live coverage gate Build Core runs before + # the build (its step says why there): a change to the gate runs + # the gate. + - 'scripts/check-temporal-live-filter.mjs' # Test inputs that live OUTSIDE every package (#9829, #10015). Packages # whose suites read across their own boundary declare that radius in # scripts/check-cross-package-test-inputs.mjs, and turbo.json mirrors each @@ -837,44 +841,107 @@ jobs: # [#37095] What makes the merge queue run `temporal-conformance` # (ruling record 7146156389): the pgvector store, the driver whose # whole suite that job runs against the live servers, the - # live-server files its filtered steps select (the two - # metadata-protocol globs spell that step's `live-mysql - # live-postgres` substrings), the service-analytics files whose - # live-PostgreSQL cells key on OS_TEST_POSTGRES_URL (#21564; no glob - # selects exactly these, so they are listed: a NEW such file must - # be added here by hand), and this file. + # live-server files its filtered steps select, the service-analytics + # files whose live-PostgreSQL cells key on OS_TEST_POSTGRES_URL + # (#21564), and this file. + # + # [#38528] AND every workspace source those tests LOAD. A live test + # reaches other packages' source through its vitest alias, and their + # `dist/` (built from `src/` by the job's build steps) through the + # package link; a row for the test alone left the source under test + # unscheduled, so a queue entry changing only that source skipped + # this job, landed, and went red first on `main`. + # `node scripts/check-temporal-live-filter.mjs` (`--self-test` beside it) + # walks each live test's run-time import closure the way vitest + # resolves it and reds on a closure file no row below matches; + # `--list` prints each closure and the row covering each file. A row + # is a package's `src/**` where the closure enters through the + # package's barrel (it then reaches nearly every module, and a + # file-by-file list would red on the next re-export), a narrower + # directory where it reaches one corner of a package, and a literal + # path for a single file. The service-analytics `src/**` row and the + # metadata-protocol `src/**` row replace the per-file and per-glob + # rows those packages carried, which they cover. temporal_live: - 'packages/plugins/knowledge-pgvector/**' - # [#37100] The adapter contract suite the pgvector store runs - # against the live PostgreSQL: a change to it is a change to that - # step's verdict. - - 'packages/services/service-knowledge/src/testing.ts' - 'packages/drivers/driver-sql/**' - - 'packages/metadata-protocol/src/**/*live-mysql*' - - 'packages/metadata-protocol/src/**/*live-postgres*' - 'packages/runtime/src/**/cascade-delete-multivalue-lookup-real-driver*' - - 'packages/services/service-analytics/src/__tests__/analytics-faces-one-lowering.test.ts' - - 'packages/services/service-analytics/src/__tests__/cube-measure-field-type-door.test.ts' - - 'packages/services/service-analytics/src/__tests__/cube-measure-relationship-path-type.test.ts' - - 'packages/services/service-analytics/src/__tests__/dataset-duration-measure.test.ts' - - 'packages/services/service-analytics/src/__tests__/dataset-tools.test.ts' - - 'packages/services/service-analytics/src/__tests__/home-amount-consolidated-measure.test.ts' - - 'packages/services/service-analytics/src/__tests__/json-stored-door-live-drivers.test.ts' - - 'packages/services/service-analytics/src/__tests__/json-stored-door-undeclared-join.test.ts' - - 'packages/services/service-analytics/src/__tests__/list-at-scalar-operator-both-faces.test.ts' - - 'packages/services/service-analytics/src/__tests__/native-sql-aggregate-policies.test.ts' - - 'packages/services/service-analytics/src/__tests__/native-sql-base-column-qualify.test.ts' - - 'packages/services/service-analytics/src/__tests__/native-sql-boolean-comparand-door.test.ts' - - 'packages/services/service-analytics/src/__tests__/native-sql-empty-sum-order-window.test.ts' - - 'packages/services/service-analytics/src/__tests__/native-sql-measure-number-presentation.test.ts' - - 'packages/services/service-analytics/src/__tests__/native-sql-number-comparand-door.test.ts' - - 'packages/services/service-analytics/src/__tests__/native-sql-offset-only-window.test.ts' - - 'packages/services/service-analytics/src/__tests__/objectql-echo-bucket-enumeration.test.ts' - - 'packages/services/service-analytics/src/__tests__/objectql-echo-date-bucket.test.ts' - - 'packages/services/service-analytics/src/__tests__/objectql-echo-offset-only-window.test.ts' - - 'packages/services/service-analytics/src/__tests__/objectql-face-order-limit.test.ts' - - 'packages/services/service-analytics/src/__tests__/order-key-selected.test.ts' - - 'packages/services/service-analytics/src/__tests__/read-scope-temporal-coercion.test.ts' + # [#37100] The adapter contract suite the pgvector store runs + # against the live PostgreSQL (`src/testing.ts`), and [#38528] + # the service it is a store of: every knowledge-pgvector live + # file loads `KnowledgeServicePlugin` through the alias. + - 'packages/services/service-knowledge/src/**' + # [#38528] The migration statements the metadata-protocol live + # files execute (they import the migration beside them, and the + # package barrel through objectql), and the manifest + # `discovery-version.ts` imports. + - 'packages/metadata-protocol/src/**' + - 'packages/metadata-protocol/package.json' + # [#21564] The live-PostgreSQL cells of service-analytics, and + # [#38528] the service they test. + - 'packages/services/service-analytics/src/**' + # [#38528] The packages every live test loads through the alias + # or the package link, each reached through its barrel: + # `@objectstack/core` (capability-mount.live-postgres loads + # `capability-composition.ts`; driver-sql's `sql-driver.ts` + # imports the barrel), objectql (the knowledge-pgvector and + # analytics files run ObjectQL over SqlDriver), and what those + # barrels import in turn. + - 'packages/core/src/**' + - 'packages/objectql/src/**' + - 'packages/types/src/**' + - 'packages/formula/src/**' + - 'packages/metadata/src/**' + - 'packages/metadata-core/src/**' + - 'packages/metadata-fs/src/**' + - 'packages/lint/src/**' + - 'packages/sdui-parser/src/**' + - 'packages/observability/src/**' + - 'packages/services/service-settings/src/**' + # [#38528] KnowledgeServicePlugin's default embedder and the + # `@objectstack/platform-objects/system` objects it registers. + - 'packages/plugins/embedder-openai/src/**' + - 'packages/platform-objects/src/system/**' + # [#38528] The analytics bucket-enumeration live file runs the + # wasm SQLite driver beside PostgreSQL. + - 'packages/drivers/driver-sqlite-wasm/src/**' + # [#38528] `@objectstack/spec`, loaded through the alias by its + # barrel: every namespace it re-exports and the root modules. + # Not `src/**`: `src/migrations/` (two thirds of the tree, the + # conversion kits) and `src/studio/` are outside every closure. + - 'packages/spec/src/*.ts' + - 'packages/spec/src/ai/**' + - 'packages/spec/src/api/**' + - 'packages/spec/src/automation/**' + - 'packages/spec/src/contracts/**' + - 'packages/spec/src/conversions/**' + - 'packages/spec/src/data/**' + - 'packages/spec/src/identity/**' + - 'packages/spec/src/integration/**' + - 'packages/spec/src/kernel/**' + - 'packages/spec/src/marketplace/**' + - 'packages/spec/src/meta-spelling/**' + - 'packages/spec/src/qa/**' + - 'packages/spec/src/security/**' + - 'packages/spec/src/shared/**' + - 'packages/spec/src/system/**' + - 'packages/spec/src/ui/**' + # The manifest `metadata-core`'s artifact conversion reads. + - 'packages/spec/package.json' + # [#38528] What the live tests' vitest configs load before any + # test: the configs outside a row above, the preflight runtime's + # config runs, the memory-tmp env helper, and the comment mask + # driver-sql's isolation test imports. + - 'packages/metadata-protocol/vitest.config.ts' + - 'packages/runtime/vitest.config.ts' + - 'packages/services/service-analytics/vitest.config.ts' + - 'packages/qa/vitest-filter-preflight/src/**' + - 'packages/runtime/src/expected-read-refusal-noise.ts' + - 'scripts/vitest-memory-tmp.mjs' + - 'scripts/js-comment-mask.mjs' + - 'scripts/invoked-as.mjs' + # [#38528] The guard that holds this list to the closures. + - 'scripts/check-temporal-live-filter.mjs' - '.github/workflows/ci.yml' # ── WHICH TEST CORE SHARDS START (#26084) ───────────────────────────── @@ -3419,6 +3486,18 @@ jobs: - name: prune-turbo-cache self-test run: node scripts/ci/prune-turbo-cache.mjs --self-test + # [#38528] The `temporal_live` filter above must hold every workspace + # source the live-server tests of `temporal-conformance` load, or a queue + # entry changing only that source skips the live job and goes red first on + # `main`. This gate walks those tests' import closures and reds on a file + # no row matches (its header is the authority). Here because Build Core + # starts on every diff that can move a closure or the list (`packages/**`, + # this file, the gate itself are `core` rows) and installs the workspace + # the gate reads vitest configs with; it reads no `dist/`, so it runs + # before the build, like the self-tests above. + - name: temporal_live covers every source a live test loads + run: node scripts/check-temporal-live-filter.mjs --self-test && node scripts/check-temporal-live-filter.mjs + # ── Turbo remote cache (#21186) ───────────────────────────────────── # Vercel's managed Turborepo remote cache. objectstack-ai/cloud's # test.yml builds this repo at its pinned SHA with the same command and diff --git a/.github/workflows/dogfood-optin.yml b/.github/workflows/dogfood-optin.yml new file mode 100644 index 00000000000..6d40bd7a3bc --- /dev/null +++ b/.github/workflows/dogfood-optin.yml @@ -0,0 +1,274 @@ +# Opt-in pre-merge dogfood battery (#38694, ruling D on #38688). +# +# ## The gap this closes +# +# A breaking change (a `!` title, or a `Clause-②:` line carrying the +# `(narrowing)` arm) owes proof that the real-app regression suite still passes +# on its own head BEFORE it queues. The three dogfood shards that are that suite +# run only in `ci.yml`'s `dogfood` job, and that job skips `pull_request` (THE +# TWO SPEEDS above its `jobs:`): a PR first meets the battery inside the merge +# queue, where a red ejects it and rebuilds every entry behind it. Until now the +# proof was a local run on the shared agent box, reported as typed text; that +# run no longer fits the box's foreground limit. +# +# Maintainer ruling D on #38688 (comment 7269391948, 「云端流水线代跑」): a CI +# runner proves a labelled breaking PR's battery, and the landing door reads +# that result by head SHA. This workflow is that runner. It adds a TRIGGER and a +# verdict, nothing else: the shards, their slicing and their guards are the +# queue's, copied from `ci.yml` (see "Drift" below). +# +# ## What the door reads +# +# label `needs:dogfood-battery` +# check `Dogfood battery (opt-in)` -- the `battery` job below, one check run +# per run, on the PR's head SHA (a `pull_request` run's check suite +# sits on `pull_request.head.sha`, not on the merge-preview commit). +# +# `success` there means all three shards ran on this head and each one attested +# that every step was green. Any other conclusion, or no such check run on the +# head, is NOT a proof. One head can carry several check runs of that name: every +# `pull_request` event starts a run, and a run whose guard says no (an unlabelled +# PR, or an unrelated label added later) publishes it as `skipped`. So the reader +# asks "is there a `success` of this name on this head", never "what does the +# newest one say". The three shard check runs +# (`Dogfood battery shard (k/3, opt-in)`) are evidence for a human reader; the +# door reads the one aggregate, so a shard-count change never moves its contract. +# ⛔ Neither name is `Dogfood Regression Gate`: that literal is a required context +# (`scripts/check-required-contexts.mjs`), and a check run here carrying it would +# satisfy branch protection on a PR without the queue ever running it. +# +# ## Opt-in, by ruling -- and what it must never grow +# +# The 2026-09-01 opt-in ruling quoted in `pack-smoke-optin.yml` binds here too, +# and ruling D restates it for this lane: the cost stays opt-in. +# +# ⛔ Never a `paths:` filter that runs it by default. +# ⛔ Never in `.github/labeler.yml`, nor any other step that applies the label +# from changed paths or from the title: the seat that owns a breaking PR +# hangs the label by hand. Auto-applying it is a different design +# (auto-detect), not the one ruled. +# ⛔ Never a required context, and no `merge_group:` trigger: a `merge_group` +# event carries no pull request, so the label cannot be read there, and the +# queue already runs the same three shards on every entry. +# +# When to apply the label: on a PR whose title carries `!` or whose body carries +# `Clause-②:` with `(narrowing)`, once its head is the one the seat means to +# land. Every later push to a labelled PR is another full run (cost below). +# +# Cost, measured on the 30 most recent green merge-queue runs of `ci.yml` +# (2026-11-29T16:58Z to 2026-11-30T04:16Z, 90 shard jobs): a shard job takes +# 18.8 min median, 25.8 max, so one labelled push costs about 59 runner-minutes +# (61 billed, 75 at the slowest). The ruling's figure is about 8 % on that +# runner: 12.5 breaking PRs a day against 164 queue builds a day, each queue +# build running the same three shards, is 12.5 / 164 = 7.6 % more dogfood shard +# jobs, at one labelled push per PR. An unlabelled PR costs nothing: its jobs +# skip, and a skipped job bills no minutes. +# +# ## Wiring decisions (the `pack-smoke-optin.yml` ones, for the same reasons) +# +# `pull_request`, ⛔ never `pull_request_target`: the run executes the PR's own +# code, so it must get the PR's own read-only token. It reads no secret at all: +# the turbo remote-cache lines of `ci.yml` are left out because a +# `pull_request` run receives no remote credentials there either (Build Core's +# "Turbo remote cache (#21186)" comment). So a fork PR runs it exactly as an +# internal one does, with nothing to withhold. +# +# `types:` restates GitHub's defaults beside `labeled` (naming `types:` REPLACES +# the default set). The guard has two limbs, on every job: the PR carries the +# label now, and on a `labeled` event the label just added is OURS -- otherwise +# every size label would start another run of an unchanged tree. `concurrency` +# supersedes per PR at workflow level (an unrelated label's run gets a group of +# its own) and again at job level, where the shard group carries the shard +# number: the three legs of one matrix share a job id, and one group for all +# three would cancel two of them. +# +# The checkout is the MERGE PREVIEW (no `ref:`), as on both precedents: the tree +# `main` will contain once this head lands, the nearest thing to what the queue +# builds. The verdict still lands on the head SHA (above). +# +# `fail-fast: false`, unlike the queue: nobody is waiting behind this run, and +# the author wants every red shard named in one run, not the first. +# +# The verdict COUNTS credentials, as `ci.yml`'s gates do since #6082: each shard +# ends with `check-shard-attestation.mjs --emit` and an upload that carry no +# `if:`, so they run only when every step before them passed. The aggregate +# passes only when the matrix result is `success` AND all three credentials of +# THIS run are present. Unlike `Dogfood Regression Gate` it does not pass a +# cancelled or skipped matrix: that gate must publish a context on every PR, +# this one is a proof, and a run that proved nothing must not read as one. +# +# ## Drift: two copies of one battery +# +# `ci.yml` exposes no callable unit (no `workflow_call`, no composite action for +# the dogfood steps), and it is out of this lane's scope, so the steps below are +# a COPY of its `dogfood` job: the closure build, the `OS_TEST_SHARD` slice, the +# vitest worker cap, the stall guard, the completeness guard and the turbo cache +# restore. Nothing holds the two equal. An edit to the queue's shard steps that +# is not repeated here leaves this lane proving a different battery than the one +# the queue runs, and it stays green while doing so. Left out on purpose: the +# queue-verdict seed-only path, the remote-cache lines, the cache save and prune +# (a PR never writes the cache), and the test-leftovers report (report-only). + +name: Dogfood Battery (opt-in) + +on: + pull_request: + branches: + - main + types: [opened, synchronize, reopened, labeled] + +permissions: + contents: read + +# A newer run for the same pull request supersedes this one, so the older run is +# cancelled. The group key is ci.yml's shape; `cancel-in-progress` is true only on +# `pull_request`, so no other event's run is ever cancelled. An unrelated label's run +# gets a group of its own (its jobs are skipped anyway), so adding some other label +# never cancels a running `needs:dogfood-battery` run. +concurrency: + group: dogfood-optin-${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.event.after || github.ref }}-${{ github.event.action == 'labeled' && github.event.label.name != 'needs:dogfood-battery' && github.run_id || 'run' }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + shard: + # ~19 minutes per shard, three in parallel. Opt-in only -- see the header. + name: Dogfood battery shard (${{ matrix.shard }}/3, opt-in) + if: >- + contains(github.event.pull_request.labels.*.name, 'needs:dogfood-battery') + && (github.event.action != 'labeled' || github.event.label.name == 'needs:dogfood-battery') + runs-on: ubuntu-latest + # ci.yml's dogfood budget, unchanged: the stall guard below is the primary + # detector, and `check:stall-guard-budget` judges its window and cap against + # this number. + timeout-minutes: 30 + concurrency: + group: dogfood-optin-${{ github.event.pull_request.number }}-shard-${{ matrix.shard }} + cancel-in-progress: true + strategy: + fail-fast: false + matrix: + shard: [1, 2, 3] + steps: + # No `ref:` -- the MERGE PREVIEW (header, "Wiring decisions"). + - name: Checkout the merge preview + uses: actions/checkout@v7 + + - name: Setup workspace + uses: ./.github/actions/setup-workspace + + # Restore-only: the queue's dogfood seeds, saved from `main`, replay the + # closure this PR did not change; a PR never writes the cache. + - name: Restore Turbo cache + uses: actions/cache/restore@v6 + with: + path: .turbo/cache + key: ${{ runner.os }}-turbo-dogfood-${{ matrix.shard }}-main-${{ github.sha }} + restore-keys: | + ${{ runner.os }}-turbo-dogfood-${{ matrix.shard }}-main- + ${{ runner.os }}-turbo-dogfood- + + # ci.yml's closure step, without the seed-only and remote-cache lines. + - name: Build the dogfood closure for this opt-in shard + env: + NODE_OPTIONS: --report-on-signal --report-signal=SIGUSR2 --report-directory=${{ runner.temp }}/stall-reports + run: | + mkdir -p "$RUNNER_TEMP/stall-reports" + node scripts/run-with-stall-guard.mjs --log "$RUNNER_TEMP/dogfood-build.log" --stall-minutes 10 \ + --report-dir "$RUNNER_TEMP/stall-reports" -- \ + pnpm turbo run build --filter=@objectstack/dogfood --concurrency=4 --log-order=stream + + # ci.yml's test step: the slice travels in the task-declared env + # `OS_TEST_SHARD` (turbo.json hashes it into `@objectstack/dogfood#test` + # only, and the dogfood vitest config hands it to vitest's `shard`), never + # a `--` passthrough. The worker cap and the stall guard are the queue's. + - name: Run this opt-in shard of the dogfood battery + env: + NODE_OPTIONS: --report-on-signal --report-signal=SIGUSR2 --report-directory=${{ runner.temp }}/stall-reports + run: | + export VITEST_MAX_WORKERS="$(node scripts/vitest-worker-cap.mjs)" + mkdir -p "$RUNNER_TEMP/stall-reports" + export OS_TEST_SHARD="${{ matrix.shard }}/3" + node scripts/run-with-stall-guard.mjs --log "$RUNNER_TEMP/dogfood.log" --stall-minutes 10 \ + --report-dir "$RUNNER_TEMP/stall-reports" -- \ + pnpm turbo run test --filter=@objectstack/dogfood --log-order=stream + + # A shard that dies silently looks like a shard that had less work. With + # no log the test step already failed, and the credential below is + # withheld by that failure. + - name: Test completeness guard + if: always() + run: | + if [ -f "$RUNNER_TEMP/dogfood.log" ]; then + node scripts/check-test-completeness.mjs "$RUNNER_TEMP/dogfood.log" + else + echo "No test log -- the test step did not get far enough to produce one." + fi + + - name: Upload stall diagnostic reports + if: failure() + uses: actions/upload-artifact@v7 + with: + name: stall-reports-dogfood-optin-${{ matrix.shard }} + path: ${{ runner.temp }}/stall-reports/ + if-no-files-found: ignore + retention-days: 14 + + # This shard's positive credential (#6082). LAST, and with no `if:`, so it + # exists only when every step above passed. + - name: Attest this shard ran and passed + run: | + node scripts/check-shard-attestation.mjs --emit \ + --job dogfood-optin --shard ${{ matrix.shard }} --total 3 \ + --out "$RUNNER_TEMP/shard-attestation" + + - name: Publish this shard's attestation + uses: actions/upload-artifact@v7 + with: + name: shard-attest-dogfood-optin-${{ matrix.shard }}-of-3 + path: ${{ runner.temp }}/shard-attestation/ + if-no-files-found: error + retention-days: 7 + overwrite: true + + battery: + # The one check the landing door reads -- see "What the door reads". + name: Dogfood battery (opt-in) + needs: [shard] + if: >- + !cancelled() + && contains(github.event.pull_request.labels.*.name, 'needs:dogfood-battery') + && (github.event.action != 'labeled' || github.event.label.name == 'needs:dogfood-battery') + runs-on: ubuntu-latest + timeout-minutes: 10 + concurrency: + group: dogfood-optin-${{ github.event.pull_request.number }}-battery + cancel-in-progress: true + steps: + - name: Download this run's shard attestations + id: attestations + continue-on-error: true + uses: actions/download-artifact@v8 + with: + pattern: shard-attest-dogfood-optin-* + path: ${{ runner.temp }}/shard-attestations + merge-multiple: true + + # Passes only on the matrix's `success` AND all three credentials of this + # run; a cancelled or skipped matrix is not a proof (header). + - name: Verify all three shards ran and passed on this head + env: + OS_ATTEST_DIR: ${{ runner.temp }}/shard-attestations + OS_SHARD_RESULT: ${{ needs.shard.result }} + OS_DOWNLOAD_OUTCOME: ${{ steps.attestations.outcome }} + OS_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + missing='' + for k in 1 2 3; do + [ -f "$OS_ATTEST_DIR/dogfood-optin-$k-of-3.json" ] || missing="$missing $k/3" + done + echo "head ${OS_HEAD_SHA}: shard matrix result '${OS_SHARD_RESULT}', attestation download '${OS_DOWNLOAD_OUTCOME}', missing credentials:${missing:- none}" + if [ "$OS_SHARD_RESULT" != 'success' ] || [ -n "$missing" ]; then + echo "::error::Dogfood battery NOT proven on ${OS_HEAD_SHA}: matrix '${OS_SHARD_RESULT}', missing credentials:${missing:- none}. Read the red shard's log; push a fix (or re-run the failed jobs) to prove the head again." + exit 1 + fi + echo "Dogfood battery proven on ${OS_HEAD_SHA}: 3 of 3 shards ran and passed." diff --git a/AGENTS.md b/AGENTS.md index 3e9fbb72da0..dc248ee2e3c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -544,21 +544,17 @@ Even inside your own worktree, operate defensively: a build fast but leaves no `.d.ts`, so `gen:api-surface` cannot run at all under it — that one needs a real build. 10. **A clean merge is not a working merge — but scope the re-check to the overlap** - ([why](docs/agents/multi-agent-discipline.md#why-a-clean-merge-is-not-a-working-merge)). **Before opening a - PR, pull `main`, refresh build - state (§9), and run the full suite once.** After the PR is open, merge `main` only on a GitHub-reported - conflict, a `main`-caused CI red or a queue removal, then only the scoped re-checks; dogfood once, on the final head - ([detail](docs/agents/multi-agent-discipline.md#where-joint-breakage-surfaces)): - - **Always:** rebuild what the merge touched, and if `packages/spec` moved on either - side, `pnpm --filter @objectstack/spec build && pnpm --filter @objectstack/spec - check:generated` — generated snapshots (`api-surface`, baselines) are the classic - jointly-wrong artifact, and only a rebuild of the merged source can validate them - (never trust git's textual merge of a generated file). Then assert your branch's - *delta vs `main`* is still exactly what your PR intends (e.g. "N removed / 0 - added"). - - **Full `pnpm typecheck && pnpm test` again only when** the incoming commits touch - the same packages or the same behavior your diff does, or a conflict occurred - outside trivially-mechanical files. + ([why](docs/agents/multi-agent-discipline.md#why-a-clean-merge-is-not-a-working-merge)). **Before opening a PR, pull + `main`, refresh build state (§9), and run targeted gates; CI runs the full suite.** After the PR is open, merge + `main` only on a GitHub-reported conflict, a `main`-caused CI red or a queue removal, then only the scoped + re-checks; a breaking PR's dogfood runs on a CI runner once labelled `needs:dogfood-battery`, and the landing door + reads that result on its final head ([detail](docs/agents/multi-agent-discipline.md#where-joint-breakage-surfaces)): + - **Always:** rebuild what the merge touched, and if `packages/spec` moved on either side, + `pnpm --filter @objectstack/spec build && pnpm --filter @objectstack/spec check:generated` — only a rebuild of + the merged source validates a generated snapshot (`api-surface`, baselines); never trust git's textual merge of a + generated file. Then assert your branch's *delta vs `main`* is still exactly what your PR intends. + - **Targeted gates again only when** the incoming commits touch the packages or behavior your diff does, or a + conflict occurred outside trivially-mechanical files. 11. **Generated artifacts don't text-merge — a driver defers them and `pre-commit` collects the debt.** `.gitattributes` routes the generator-owned artifacts to `merge=os-regen` (`pnpm check:merge-driver` reconciles both directions); the driver does **not** regenerate — it records @@ -1016,7 +1012,7 @@ Both non-handshake shapes, and how to classify and probe your own: ## Post-Task Checklist -1. `pnpm test` — verify nothing broke. Touched a type-check-covered package? `pnpm typecheck` too. +1. Targeted gates (Multi-agent discipline §10): touched packages' `test` and `typecheck`; CI runs the full suite. 2. **Land it — don't leave passing work in the working tree.** Once tests pass, create a feature branch, commit, push, open a PR, and — once remote CI is fully green and the PR is accepted — arm auto-merge so the queue lands it (Multi-agent discipline §7). A finished task diff --git a/apps/docs/reference-redirects.mjs b/apps/docs/reference-redirects.mjs index 8c3df5f40f7..7b3a6c5cec0 100644 --- a/apps/docs/reference-redirects.mjs +++ b/apps/docs/reference-redirects.mjs @@ -72,10 +72,19 @@ const EARLIER_MOVES = [ /** * `category` -> its page slugs, read from the generator's output folder. * Sorted, so the table is a pure function of the folder's contents. + * + * A missing folder, or one with no category in it, throws. The alternative is + * an empty table: the site would build, serve none of these redirects and say + * nothing, and every old reference URL would answer 404. */ export function repoReferencePages(root = REPO_ROOT) { const dir = join(root, REPO_REFERENCES_REL); - if (!existsSync(dir)) return new Map(); + const missing = (what) => + new Error( + `reference-redirects: ${what}, so the redirect table for the moved reference pages would be empty. ` + + 'Generate it with `pnpm --filter @objectstack/spec gen:docs`.', + ); + if (!existsSync(dir)) throw missing(`${REPO_REFERENCES_REL} does not exist`); const out = new Map(); for (const entry of readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory())) { const slugs = readdirSync(join(dir, entry.name)) @@ -87,6 +96,7 @@ export function repoReferencePages(root = REPO_ROOT) { .sort(); out.set(entry.name, slugs); } + if (out.size === 0) throw missing(`${REPO_REFERENCES_REL} holds no category folder`); return new Map([...out].sort(([a], [b]) => a.localeCompare(b))); } diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 3bd9f92ab43..5e0223f82e4 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -34,13 +34,15 @@ Which store is mounted depends on the platform database: - **Two stores and none the deployment's** (a host that mounts the service and two adapters itself): a source that names no adapter is refused when it is registered or saved — `VALIDATION_ERROR` (400), naming the adapters to choose from. - **A source naming a store that is not mounted** (a retired store such as `ragflow`, or a typo) is refused when it is saved in Studio, over `PUT /meta/knowledge_source` or through MCP: `VALIDATION_ERROR` (400), naming the source, the adapter and the stores that are mounted. A source that leaves `adapter` out is not refused for it. That save check does not reach a package install, a source registered in code or `os validate`; such a source does not stop the boot: the server logs one error naming the source and the stores that are mounted, and indexing or searching that source answers `SERVICE_UNAVAILABLE` (503) with the same choices; `search_knowledge` lists it in `refused`. - **The embedder** comes from Settings → AI & Embedder ([below](#configuring-the-embedder-from-settings)). +- **Mounted is not enabled.** A service the runtime mounts this way is enabled by configuration, read once when the server starts: an embedder (one a plugin registered, or a provider saved in Settings → AI & Embedder that builds one) and the deployment's store mounted. Without both, every source is **held**, whichever store it names: it is listed to administrators and never built, synced, reconciled or searched; `search_knowledge` is not listed on MCP (HTTP or stdio); a search or a rebuild answers `SERVICE_UNAVAILABLE` (503) naming what is missing; no reap guard is registered and no store is called, so a retention sweep deletes rows on time. The boot says it once: at `info` when only a shipped source mounted the service and nothing was saved, at `warn` when the stack declares `requires: ['knowledge']`, a saved provider builds no embedder (one saved without its key) or the store is not mounted. The server always starts. To enable it, save an embedder provider (or mount the store the log names), then restart. A service you mount yourself (below) is not held. - **Another libSQL store** for the `turso` case: save its URL as `turso_url` (and `turso_auth_token` for a managed `libsql://` database) in Settings → Knowledge, then restart. A `file:` URL saved there must name a file inside that same data directory, and a URL carrying a NUL byte or another control character, written out or percent-encoded (`%00`), is refused, as is a token carrying one (a pasted line break counts); either way the store answers `SERVICE_UNAVAILABLE` saying why, and the boot goes on. - **Where the file is**: `os start --home` and `OS_HOME` move it with the default database, so on a container put `OS_HOME` on a volume and the index survives a redeploy. A database named by URL (`OS_DATABASE_URL`) does not move it. - **Settings → Knowledge** holds only what the service and its store read: `turso_url` and `turso_auth_token`, which `@objectstack/knowledge-turso` adds to the page where it is the store and reads them, with the "Test connection" check of those two fields (on PostgreSQL the page shows none of the three), and `chunk_target`, the longest passage the splitter cuts. The page names no adapter: a source's store is the one its own `adapter` names, and `os knowledge status` reports it per source. Every search re-checks each hit as the asking user, and no setting turns that off. A PostgreSQL deployment that saved the two Turso keys before the group left the page keeps their rows; the settings service never deletes a stored row. To tidy it up, delete the `knowledge` rows named `turso_url` and `turso_auth_token`, and the `sys_secret` row the `turso_auth_token` row's handle names: without the store no API door clears that key, and the row is a decryptable copy of the token. Nothing requires it. - **More than one replica** on MySQL, MongoDB or a remote libSQL database: each replica keeps its own local `knowledge.db` and indexes only the record writes that replica itself handles, so replicas answer from indexes that differ. Give them one store: save a shared `libsql://` URL in `turso_url`, or run on PostgreSQL, where the vectors live in the one database. - **An install without the libSQL client**: `@objectstack/knowledge-turso` is an optional dependency of the CLI, because its client is a native module. Where it could not be installed the server warns at boot that the store was not mounted, and sources naming `turso` answer `SERVICE_UNAVAILABLE`. - **Without a source or the token** nothing is mounted: no knowledge service, no store and no Knowledge settings page. `knowledge-memory` is never mounted for you. -- **A source is saved only on a deployment that mounts the knowledge service.** On one without it, saving a source in Studio, the metadata API or MCP is refused `SERVICE_UNAVAILABLE` (503) and nothing is written: nothing there would load, index or search it, and the service is mounted when the server starts, never while it runs. A source saved at run time is not one the app ships, so it does not mount the service either. The refusal names the fix: add `requires: ['knowledge']`, restart, then save the source. A package install, a seed or a migration is not refused; the boot names each source it holds with no service to load it, and the same fix. +- **A source is saved only on a deployment that mounts the knowledge service.** On one without it, saving a source in Studio, the metadata API or MCP is refused `SERVICE_UNAVAILABLE` (503) and nothing is written: nothing there would load, index or search it, and the service is mounted when the server starts, never while it runs. A source saved at run time is not one the app ships, so it does not mount the service either. The refusal names the fix: add `requires: ['knowledge']`, restart, save an embedder provider, restart again, then save the source. A package install, a seed or a migration is not refused; the boot names each source it holds with no service to load it, and the same fix. +- **A source is saved only while the service is enabled.** Where the runtime mounted the service and its sources are held ([Mounted is not enabled](#turning-it-on-requires-knowledge)), saving a source in Studio, the metadata API or MCP, or moving a package-less source into a package, is refused `SERVICE_UNAVAILABLE` (503) and nothing is written. The refusal names what is missing and the fix: save an embedder provider, restart, then save; or, where the boot log says the deployment's store is not mounted, mount it, restart, then save. Duplicating a package is not refused for it, and a package install, a seed or a migration is not either: those sources are held. - **Mounting it yourself** still works: an app whose `plugins` already hold `KnowledgeServicePlugin` keeps its own, and the runtime adds neither a second service nor a store. ## Writing a source @@ -118,8 +120,9 @@ export default defineStack({ Retrieval is a plain service call — no AI runtime required. Resolve the `knowledge` service and call `search`. Hits are re-checked against the caller's -`ExecutionContext` (RLS), sorted by score, and capped at `topK` before they come -back. Because the re-check runs after ranking, for a caller other than the +`ExecutionContext` (RLS), sorted by score, re-ordered for the caller when their +source declares an [order for the asker](#ordering-hits-for-the-asker), and +capped at `topK` before they come back. Because the re-check runs after ranking, for a caller other than the system identity the service asks each source for more hits than `topK`, and asks once more when too few records survive, so a caller who may read few of the matching records still gets up to `topK` hits @@ -128,13 +131,17 @@ hit's `title` is the value of the object's display field (`nameField`, else the derived title field). The two open stores, [pgvector](#self-hosted-vector-store-postgresql--pgvector) -and [libSQL](#local-vector-store-a-libsql-file), search with two legs: the -vector leg ranks by meaning, and a keyword leg ranks the passages that hold the -query's terms as written — an order number, a model code like `X-200`, a -person's name, a short term like 「出差」 — which a vector alone can rank -below `topK`. The two rankings are merged by reciprocal rank fusion, so a hit's -`score` is 1 for a passage first in both and 0.5 for one first in only one, and -the merge happens before the permission re-check. +and [libSQL](#local-vector-store-a-libsql-file), search with two legs by +default: the vector leg ranks by meaning, and a keyword leg ranks the passages +that hold the query's terms as written — an order number, a model code like +`X-200`, a person's name, a short term like 「出差」 — which a vector alone can +rank below `topK`. The two rankings are merged by reciprocal rank fusion, so a +hit's `score` is 1 for a passage first in both and 0.5 for one first in only +one, and the merge happens before the permission re-check. A source can run one +leg alone with `source.retrieval.mode` (`'vector'`, or `'keyword'`, which calls +no embedder); its first hit then scores 1. A score orders the hits of one +source; it is not a measure of relevance, and scores of two sources are not +comparable. ```ts const knowledge = ctx.getService('knowledge'); @@ -178,6 +185,34 @@ Protocol, adapters, embedder, and `KnowledgeService.search` — is open, so you installed ([Connect an MCP Client](/docs/ai/connect-mcp)). +### Ordering hits for the asker + +A source can put the hits related to the person asking first, without +filtering any out: "the policies of my own company first, then the group's". +Declare `affinity` on the source, naming fields it lists in `metadataFields`: + +```ts +source: { + kind: 'object', + object: 'policy', + content: ['title', 'body'], + metadataFields: ['business_unit', 'owner'], + affinity: [ + { field: 'business_unit', caller: 'business_unit', mode: 'nearest' }, // own unit, then each parent, then the rest + { field: 'owner', caller: 'user', mode: 'boost', places: 3 }, // an owned policy passes up to 3 others + ], +}, +``` + +The platform reads who is asking from the search's own identity (the user, and +their primary business unit with its parents up to the root, as far as they may +read them), so no tool argument and no model supplies it. Only that source's +hits move, by position: each keeps the `score` its store answered, nothing is +dropped, and a source without `affinity` answers exactly as before. `places` is +a whole number from 1 to 20, and a source declares at most one `nearest`. The +rules, and every refusal, are in +[the protocol](/docs/protocol/knowledge#ordering-for-the-asker). + ## Searching inside chosen records Pass `scope` to search only inside some records: the records a source indexes, or a parent record that source reaches through a lookup it lists in `metadataFields`. @@ -195,7 +230,7 @@ An adapter that reads the scope filters before it ranks, so the `topK` hits all ## The `search_knowledge` tool -An AI client searches through one tool, `search_knowledge`, defined once by the knowledge service. The MCP door (HTTP and stdio) and the in-product agent serve that one definition unchanged, so every client is offered the same arguments and gets the same answer. It searches only sources whose `aiExposed` is not `false`, and reads as the person asking. +An AI client searches through one tool, `search_knowledge`, defined once by the knowledge service. The MCP door (HTTP and stdio) and the in-product agent serve that one definition unchanged, so every client is offered the same arguments and gets the same answer. It searches only sources whose `aiExposed` is not `false`, and reads as the person asking. Where the knowledge service is held (no embedder or no store, [above](#turning-it-on-requires-knowledge)), the tool is not listed at all; on stdio it is registered after the boot reads the service as enabled, and a connected client is told by `notifications/tools/list_changed`. | Argument | What it does | |:--|:--| @@ -230,7 +265,7 @@ When `KnowledgeServicePlugin` is mounted beside the settings service, Settings - **A provider is saved and complete** → an `@objectstack/embedder-openai` embedder for that provider. The saved Base URL applies only to the custom and Azure providers; other providers use their preset endpoint. The boot line names the endpoint host. "Complete" is what the **Test embedder** button checks: a provider, an API key (Ollama excepted) and, for a custom or Azure endpoint, a Base URL. - **Dimensions and batch size are positive integers**, saved as numbers or set as text through an `OS_*` override (`OS_AI_EMBEDDER_DIMENSIONS=256`). A value that is not a positive integer is refused, with a `warn` at boot and the error below on every use — never silently ignored. - **The batch size is passed only when you saved it.** Left unsaved (the form shows 64), the embedder sends as many inputs per request as the model's documented cap allows — 10 for DashScope `text-embedding-v3`, 2048 for OpenAI `text-embedding-3-*` — and 10 for a model it does not know. A saved batch size is held to the saved model's documented cap (`documentedMaxBatchSize(model)` from `@objectstack/embedder-openai`): a saved 64 on `text-embedding-v3` sends 10. For a model without a documented cap the saved size is sent as saved. -- **Nothing is configured** — no provider saved, `none` saved, or the saved settings incomplete → the server still boots, and every use of the embedder answers an error naming the missing settings: an adapter that embeds refuses indexing and search with it, and nothing is sent anywhere. Nothing is sent to a provider until you have saved one, and the API key is never logged or put in an error. +- **Nothing is configured** — no provider saved, `none` saved, or the saved settings incomplete → the server still boots, and every use of the embedder answers an error naming the missing settings: an adapter that embeds refuses indexing and search with it, and nothing is sent anywhere. Where the runtime mounted the service (`requires: ['knowledge']` or a shipped source), its sources are held instead ([above](#turning-it-on-requires-knowledge)): nothing is built or searched, and `search_knowledge` is not listed. Nothing is sent to a provider until you have saved one, and the API key is never logged or put in an error. **A saved change takes effect after a restart** — the page says so under the provider field. There is no hot replacement. @@ -255,10 +290,55 @@ source: { ``` - `recursive` (the default) cuts at blank lines, then line breaks, then sentence ends, then semicolons, then characters. It reads Chinese and English sentence ends — 「3.2 条」 and 「400.50 元」 stay whole — and never cuts inside a Markdown table or list item that fits. -- `markdown` cuts one section per heading; each passage begins with its heading path, which is embedded with it. +- `markdown` cuts one section per heading; each passage begins with its heading path, which is embedded with it. A section that fits in one passage (its text together with the heading path it is given, within the length below) is one passage; only a section that does not fit is cut as `recursive` cuts, and `minChars` (default 200) merges the short pieces of that cut. - `whole` keeps each document as one passage. -A passage is at most `split.maxChars` characters — else the **Knowledge → Target chunk size** setting, else 800 — and, when the adapter reports its embedder's input limit, within 80% of that limit by the shared token estimate below. A `whole` document over that budget is **removed from the index and reported** (`failed` and `failures` on the reindex result, an `error` log on the event sync), never truncated; because the estimate runs high, a `whole` document can use about 60% of the model's limit. The full rules are in [the protocol's split section](/docs/protocol/knowledge#35-the-split). +A passage is at most `split.maxChars` characters — else the **Knowledge → Longest passage** setting, else 800 — and, when the adapter reports its embedder's input limit, within 80% of that limit by the shared token estimate below. A `whole` document over that budget is **removed from the index and reported** (`failed` and `failures` on the reindex result, an `error` log on the event sync), never truncated; because the estimate runs high, a `whole` document can use about 60% of the model's limit. The full rules are in [the protocol's split section](/docs/protocol/knowledge#35-the-split). + +### One passage per unit + +Policies, regulations, contracts and manuals are made of units: an article, a numbered section, a question with its answer. A hit is most useful when it is one whole unit: not half of one, and not three of them. The `markdown` strategy gives exactly that once each unit is its own heading: + +- **One heading per unit.** Write each unit as a Markdown heading at the start of its line (`## Article 12 Air travel`), with the unit's text under it. Bold text such as `**Article 12**` is not a heading, so every article under one real heading would share that one section. Keep a unit's sub-items as list items or plain lines, not headings: a sub-heading starts a section of its own, and with it a passage of its own. +- **A unit that fits is one passage.** When a unit's text together with its heading path fits within the passage length above, it is one passage, whatever `minChars` is. A table and the note right after it, written inside the same unit, stay in that passage. +- **A passage never holds two units.** Each section is split on its own, so short neighbouring units are never merged, and every passage begins with its unit's heading path (shortened when it is long, see below; the hit carries all of it as `headingPath`). +- **A unit that does not fit** is cut as `recursive` cuts, its pieces merged up to `minChars`, and every piece still begins with the unit's heading path. A table too long for one passage is cut between rows, each piece repeating the header row; a note after the table can then land in a different piece than the rows it explains. +- **`minChars` only merges the pieces of a unit that does not fit.** It is the merge threshold for that cut: pieces shorter than it are joined up to it. It is not a switch for one passage per unit, which needs no setting, and `minChars: 0` turns nothing off: a unit that fits is still one passage, and only the pieces of a unit that does not fit are left unmerged. + +Most apps do not store their text in that shape: articles are bold paragraphs, or the text lives in rich text. Keep it as it is, and give the same record a second text field that holds the index text, the same content rewritten with one heading per unit, filled by the app each time the record is saved (in a record hook, for example). List only that field in `content`: + +```ts +source: { + kind: 'object', + object: 'policy', + content: ['index_text'], // the derived field alone + metadataFields: ['department', 'status'], + split: { strategy: 'markdown', maxChars: 800 }, +} +``` + +Keeping the index text on the same record, rather than in a second object with one row per unit, means a hit names the record people open, the search re-checks that record as the asking user, and `where` and `metadataFields` read the record's own fields. There is no second object to secure, keep in step with the first, or delete with it. The field is indexed like any other content field: its text is sent to the embedder, and a credential or internal field is never indexed. + +**An optional top heading names the document.** The text the embedder sees is the passage: neither the record's title nor the department that owns it is in it unless the text says so. Starting the index text with one top-level heading that names them, with every unit one level below it, makes each passage's heading path begin with that heading: + +```md +# Group travel policy · Finance department + +## Article 1 Scope +Applies to every employee travelling on company business. + +## Article 7 Hotel limits +| Region | Limit per night | +|---|---| +| Region 1 | 600 | +| Region 2 | 450 | + +Region 1 means Beijing, Shanghai, Guangzhou and Shenzhen. +``` + +Article 7 is then one passage that begins `Group travel policy · Finance department > Article 7 Hotel limits`, the table and its note together, and a question that names the policy or the department matches it. Keep the top heading short: a heading path is written into the passage whole only while it leaves at least half of the passage length for text, and otherwise shortens to the unit's own heading (the hit's `headingPath` still lists all of it). A title that is already in the top heading needs no second `content` entry: a field listed before the index text would become a passage of its own, ahead of the first heading. + +Moving an existing source to this shape changes its `content` and `split`, so its index is rebuilt once ([below](#when-the-model-or-the-split-changes-rebuild)), and the rebuild sends the whole source to the embedding provider again. ## Embedder input limits diff --git a/content/docs/api/metadata-api.mdx b/content/docs/api/metadata-api.mdx index c77558d980a..eba0a06d0f5 100644 --- a/content/docs/api/metadata-api.mdx +++ b/content/docs/api/metadata-api.mdx @@ -174,7 +174,7 @@ Under a `group` or `isolated` tenancy posture every `/packages` write is the platform operator's (ADR-0131 D12 items 7–8, D11): install (`POST /packages`), the manifest `PATCH`, enable, disable, publish, `publish-drafts`, `discard-drafts`, `revert`, `rollback`, `commits/:commitId/revert`, `duplicate`, -`adopt-orphans` and this delete. Any other caller, a `manage_metadata` holder +`move-in` and this delete. Any other caller, a `manage_metadata` holder inside one organization included, is refused `403 PERMISSION_DENIED` naming the posture, before anything is read or written, whatever the package carries. Reads are unchanged. Under `single` every `manage_metadata` holder writes as diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 9adaf844c92..6c5742c1ef4 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -408,6 +408,10 @@ never deadlock against itself. The exemption is keyed on run identity rather tha elevation, so a `runAs:'user'` run stays row-level-security scoped while it writes — it does not become a system write. +On an object that declares `closedStates`, the document is held for the whole +approval, between its steps as well, and every run of the approval writes it: +see [the hold](#hold). + **The record's lines are locked with it.** Rows of a `master_detail` child of the locked record (an expense claim's lines, an opportunity's products) refuse insert, update and delete with the same `409 RECORD_LOCKED`, and so does moving a row into @@ -1410,6 +1414,424 @@ in-flight request, `reassign` hands one slot to another user directly. - Forget rejection paths - Hard-code approvers +## Approvals on an object that declares `closedStates` [#closed-states] + +An object can declare [`closedStates`](/docs/references/data/object) (ADR-0162): +values of its own `select` fields on which a record and its direct +`master_detail` lines are closed to every caller that is not a system context, +who is refused `409 RECORD_LOCKED`. The approval status mirror writes in a system +context, so it can move such a record: the `pending` of a new approval takes a +document off a closed `approved`. That is why the platform asks more of an +approval on such an object, and what this section describes. In an application +where no object declares `closedStates`, none of it applies and nothing is read. + +### Which approvals are judged, and when + +An approval here is one passage of a record through its approval flow, taken +whole: the run started for the record and every child run under it, a `subflow` +body or an item of a `map`, to any depth. It holds one request for each step it +reaches, and one more each time a returned request is resubmitted. ADR-0044 +numbers those resubmissions as the rounds of a request, and the word means +nothing else on this page. + +The platform judges an approval once, at its first request, before anything is +written. It reads every approval step of the flow the record's run was started +on and of every flow a `subflow` or a `map` in it names, to any depth, each with +its own `approvalStatusField` and every object it can act on: the record's +object, and under a `map` the object the node names for its items as well. A +later request of the same approval is not judged again, since refusing it would +end the approval between two steps that were already decided. Nor is a request +the platform cannot place as first or later, which is a request of an approval +whose earlier requests were opened before requests recorded the run they +belong to. So an approval that was in flight when its object first declared +`closedStates` is not held to what follows. + +A step is **concerned** where the object closes on its mirror field at a status +the mirror writes for a request that is not abandoned: `pending`, `returned`, +`approved` or `rejected`. An object that closes on that field only on values of +its own, such as `paid` or `void`, is asked none of the field and flow +conditions below. + +### What the mirror field owes + +For every concerned step, the step's mirror field: + +- **declares `pending`**, and the object closes on **neither `pending` nor + `returned`**. Those are the statuses of a request in flight, and the revise + window of a returned request opens on `returned` (ADR-0044). +- has **`pending` among the moves out of a closed `approved` or `rejected`**, + wherever a `state_machine` rule on the field declares those moves. A new + approval of a decided document opens it by writing `pending`. +- carries **no `readonlyWhen`**, and **no `visibleWhen` on its options for a + request's status** (`pending`, `returned`, `approved`, `rejected`, + `recalled`). The platform does not evaluate those predicates ahead, and on a + record where one holds it takes away a write the mirror needs. Keep callers + off a mirror field with `readonly`, which the mirror passes. + +The field's other rules and hooks cannot be read ahead, and they meet every +write of the mirror. A `state_machine` rule on the field owes the mirror its +other moves as well: from `pending` to each outcome, and out of `pending` and +`returned` when a request is abandoned. Where the object closes on the field at +`approved` or `rejected`, a write of the mirror that a rule or a hook refuses is +not swallowed: + +- **The `pending` of an approval's first request.** The approval does not open. + The request just written is voided as `cancelled`, its timeline carries the + refusal, no lock is taken, and the run fails at that step with the refusal's + own message. The record keeps the value it held. +- **Any other write.** The field keeps the value it holds, and the refusal is + reported three ways: an `error` line in the server log, a line with no actor on + the request's timeline that carries the refusal's message, and a notice to the + organization's administrators, who can change the rule. + +### What the flow owes + +- **One mirror field for every step.** Every approval step that can act on a + record of the object names the same mirror field as the concerned step. A + step that names another field, or none, refuses the approval, whether it comes + ahead of the concerned step or after it. A step in a `map` body counts as one + that can act on the parent's record, unless the node writes its items out and + every one of them is a record. +- **No pause between two steps.** *Between two steps* means after a step is + decided, either way, and before the next step opens. The next step can be the + same step opened again, so in a `map` or a `loop` body that holds a step, a + node after the body's last step stands between two steps too. No node that can + pause the run of itself may stand there, in a flow that runs as the user or in + one that runs as system: a `wait` or a `screen` there would hold the document + in approval with nobody asked to decide. The platform reads this off the node + type's descriptor (`supportsPause`), and reads a `subflow` or a `map` through + the body it calls. The revise window of a returned request (`approval_revise`) + is not such a pause. +- **A node type without a descriptor.** A node whose type publishes no + descriptor counts as one that can pause, and so does a node whose type the + platform cannot read: such a node between two approval steps refuses the + approval. The structural types `start` and `end` have no executor and never + pause, so the `end` of a `map` body or of a `subflow` body refuses nothing. +- **No `map` of approvals on the parent's record.** Where a concerned step can + act on the parent's record, the approval holds no `map` with an approval step + in its body, at any depth, unless the node writes its items out and none of + them is a record. An item that is a record has its request filed on the item, + and the parent's run waits on it as it would on a pause. A parent run that + carries no record, such as a batch sign-off that hands a `map` its items, is + not refused on this ground. +- **Readable whole.** Every flow a `subflow` or a `map` names is one the + platform can read. An approval it cannot read whole cannot be judged, and is + refused. + +One more ground is the host's, not the author's. An approval any step of which +can act on an object that declares `closedStates`, concerned or not, opens only +on a host that runs the approvals plugin's sweeps, which needs a `job` service. +The sweeps are what release a record held by a dead run, and what judge an +approval that no action judged, below. + +### An approval that does not mirror onto the closing field + +An approval none of whose steps mirrors onto a field the object closes on is +asked none of the field and flow conditions, only the host's. It moves nothing on +the closing field, so it does not open a closed document: a record that is closed +stays closed through it, on the value its last writer left, and every caller's +edit of it is refused, in the revise window after a send-back as well. Such an +approval is not a way out of the closed state. Where a closed document should +not be sent for approval at all, gate the flow's start on the state. + +### Each item under a `map` is an approval of its own record + +Under a `map` whose items are records, each item's request is filed on that +item, on the object the node names for its items, and what follows is judged for +that record alone: + +- the item object's closed values and mirror field are judged, with the rest of + the approval, at the approval's first request; +- the submitter is told an item's outcome without waiting for the items after it; +- when an item's request is abandoned, only the requests on that item's record + count, never another item's (below). + +### What a refused opening is for the person who submitted + +When the check refuses, the approval does not open: no request is written, +nothing is mirrored, no lock is taken, and nobody is asked to decide. The +approval node fails the run with a `VALIDATION_FAILED` error, and that failed run +is what the person who submitted sees. Its message names the record whose +approval was not started, and then, for each gap, the flow, the step, the object, +the field and what is missing. Its lead says that the object closes on its +approval field only where a gap concerns that field; where the only gaps are the +host's or a flow that could not be read, the lead says instead that the approval +can act on an object that declares `closedStates`. The message is in the run's +locale where the plugin carries it, and in English otherwise. The record keeps the +value it held, and the server log carries a warning that names the gaps. + +Nothing in the message is the submitter's to fix: every gap is the app's +configuration or the host's. Whoever maintains the app fixes the field, the flow +or the host, and the submitter then submits again. + +### Refused where the approval is authored + +The same conditions are refused before anyone submits, wherever the flow and +the object are in view together. `os validate`, `os build` and `os lint` fail +on a project's stack with the finding `approval-closed-state-gap`, one per gap, +in the same words as the refused opening. Studio, the REST `/meta` API and MCP +refuse to save or publish a `flow` or an `object` that would leave a gap, with +`INVALID_METADATA` (422) and the same words: at an active save, when a draft is +promoted, at a restore, and in a package publish. A draft save is not refused; +its promotion is. A package that declares `closedStates` and fixes its flow in +the same publish passes. + +An authoring door judges only what it has in view, so the refusal at the first +request stays the rule. These are left to the first request: + +- a flow that a `subflow` or a `map` names and the project or the deployment + does not hold there. When one flow is saved on its own, the flows it calls and + the flows that call it are not in view; +- a node type that a plugin adds, between two steps. At authoring only the + spec's own pausing types, such as `wait` and `screen`, count as a pause; +- whether the host runs a `job` service; +- a flow that declares no object, with no `start` object and no record input, + started by an action or by name on a record. At authoring a flow is judged on + its `start` object, or where it declares none, on the object of each record + input; the first request judges on the record the run was started on. + +### What an abandoned approval leaves + +Three writers abandon a request: its submitter's recall, of a pending request or +of a returned one in its revise window; an administrator's override of a pending +request, the override arm of the same recall; and the sweep that releases a +record held by a dead run. Each records `recalled` on the request. The platform +also abandons an approval whose run ended between two steps, below, at the +action that found it or in the reconciler: the requests keep the decisions +already made, a line with no actor on the latest request's timeline says that +the approval did not go on, why, and what the record was put back to, and the +submitter is told, and submits again. Where the object closes on the mirror +field at any value, one of its own or a status, an abandoned request never +writes a closed value of that field: + +1. **A closed value the approval did not write is left alone.** Where the field + holds a closed value that no request of this approval on this record had as + its status, another writer put it there, and the mirror writes nothing. A + request of the same approval on another record, another item of a `map`, does + not count. +2. **Otherwise `recalled`**, where the field declares it, or declares no options, + and the object does not close on it. +3. **Otherwise the first usable value in this order:** the value the field held + at submit, the field's declared default, empty. A closed value is passed over + at each step, and so is a value the field does not declare. On a required + field an empty value at submit is passed over for the default. + +So listing `recalled` among the field's closed values closes nothing through the +mirror: a withdrawn approval leaves the record open. A record that was closed +when it was submitted, and that the approval opened, is left open on the value a +never-submitted record carries, its default or empty. To close a withdrawn +document, use an action or a flow of the app's own. To show a withdrawn approval +on the record, declare `recalled` among the field's options and do not close on +it. + +Where the platform cannot tell whether the approval wrote the closed value the +field holds, because the abandoned request, or one opened on the record since the +approval's run started, does not record the run it belongs to, it goes down the +order. The server log says when the mirror withholds a declared `recalled` (a +warning) and when it passes over a closed value or leaves one alone. On a +required field that is not `readonly`, with no default the mirror can use, the +write of empty is refused: the field keeps the value it holds, and the refusal is +logged, and reported as above where the object closes on the field at `approved` +or `rejected`. + +### When the outcome lands on the record + +Where the object closes on a step's mirror field at `approved` or `rejected`, +the step's decision is held back: the request records it, and the field keeps +`pending` until the approval is over for the record. Every other status is +written as before: `pending` as a request opens, `returned` at a send-back, and +what an abandoned request leaves. + +So a node that follows a decision in the flow reads `pending` on the field, not +the decision, and a flow or a trigger that fires when the field becomes +`approved` fires once, when the approval is over, not at each step. A node that +needs a step's decision reads it on the step's outcome, as the flow's own edges +do. + +After each action that moves a run of the approval on (a decision, by a person +or by the escalation clock, a send-back, a resubmission, a recall, and the +continuation of a restored run), the platform reads the approval's requests on +the record and every run of the approval: the run that carries the record and, +through the steps that started them, every `subflow` child under it, and every +`map` item run that does not carry another record (an item that is a record has +an approval of its own). It answers one of: + +- **In progress.** A request is pending or returned on the record, or a run is + parked at a node between two steps. A run parked there on a child run counts + as what its child run is. Nothing is written. +- **Ended between two steps.** A run stopped on a node a step could still follow + (it failed or was cancelled there), a failure the flow routed at the top level + of a run ended it, to an end or to a pause no step follows, or a later step + could not open, and no request of the approval opened after it. The approval + is abandoned, above. +- **Cannot tell.** A run is being advanced by another process, the store did + not answer for a run, or the requests cannot be read. Nothing is written. +- **Finished**, otherwise: every run reached an end of the flow, a refusing end + included, stopped after the last step, or is parked at a pause no step can + follow. The latest request's decision is written, in the name of the person + who decided it. + +The platform keeps what it read on the approval's own requests, at each of these +actions, one that leaves the next request pending included, and as each request +opens: the runs it read to their end, and a failure between two steps it found +in one. A run is not read again once it, and every run its steps started, were +read to their end. Until then it is read again at the next action or sweep, so +a run that a stored step lists, and that the platform could not read once, is +not passed over later. One reading takes at most 200 runs beside those it does +not read again; a larger tree cannot tell on that reading and is read on at the +next. That has an end: once the approval's marks have stood for an hour, the +platform reads on only while a reading adds to the runs it does not read again +(it keeps at most 200 of them), and the reading that adds none places the +approval by the step last decided, below. Two costs come with that. An approval +whose runs the platform cannot finish reading is placed without having been +read to its end, and that can begin at about 399 runs: for a `map` step of 199 +items that each call a `subflow`, every reading takes the run and its 199 item +runs, and never the runs below them. And the cause is the shape of the flow, so +the same approval submitted again can meet the same end: give one approval +fewer runs to read, because submitting again does not help. Reading on can take +up to 200 further visits after the hour. The reconciler visits an approval once +a sweep, every five minutes by default (the plugin's `escalationScanIntervalMs`), +or once a turn of its walk where more requests are marked than one sweep reads, +below. + +The platform trims every flow's run history in time. A run it read before that +is not needed again. A run it never read counts as passed where the history of +a run it did read shows that the flow went on past the step that started it: +that step succeeded, and the flow reached an end or went on to a later step. +Such a run does not hold the approval. A step that failed does not count, also +where the flow routed the failure and went on. + +Four more states cannot tell at first: a run with no history left to read, +which the platform never read and which no run it read went on past (a process +stopped while it was advancing it); a run whose history does not list every run +its steps started (a `map` step that started more than 200 item runs, or a step +history that lost steps, or the lists of the runs its steps started, to its +size limit when it was stored); an approval with more runs than the platform +can read in full, above; +and a decided request whose run is still parked at that request's own step (a +process stopped before the run was resumed), in the run that carries the record +or in a `subflow` or `map` run below it. An hour after the approval's marks +were set, each has stopped at the step last decided, once two checks in a row +find it in the same state. The hour is counted from the marks, not from when +the run last moved, and a run the platform is resuming at that moment looks +like one a stopped process left: a run with no history to read, or a paused run +with nothing to resume it. An approval can wait longer than an hour between two +steps by design (a `wait` node, a batch of records approved one by one) only +where none of its steps is concerned: the flow conditions above refuse both for +one that is. Such an approval holds nothing back, and it is past the hour +whenever it resumes. So the check that first finds a run in such a state only +notes it, and the next check places the run if it finds the same. A check made +within the hour counts as the first, so this adds one visit of the reconciler, +and only where the check before did not find the same: one sweep, five minutes +at the default interval, or one turn of the walk where more requests are marked +than one sweep reads. Where a later step could +follow that step, the approval is abandoned, above, and a run still parked +there is cancelled, with the runs that wait on it, so nothing resumes it; the +decisions already made stay on their requests, and the submitter submits again. +The cancel is not tried again once the record is put back: where it fails, the +run stays parked, the approval stays abandoned, and continuing that run is +refused. Where the step was the last, its decision is written and, once it is +on the record, the organization's +administrators are told that the flow could not be seen through to its end +after that step (the notice `approval.flow_not_continued`). The run's pause is left: where the run is still +paused, an operator can continue the flow's remaining nodes or cancel the run; +where it has ended or no run is left, check that the steps after the decision +were done. A write that a rule or a hook refuses sends no such notice; the +notice goes out with the write that lands. An approval placed for a history +that does not list every run, or for more runs than the platform can read, can +be one whose flow did go on: the platform could not read it in full, so the +notice asks for a check and does not state a failure. + +A step history that loses whole steps carries no mark of it; this is a limit +of this release (ruling 7268216330 on #37767). The platform marks one thing: a +step that lost the list of the runs it started. Whole steps are lost in three +ways: a run that logged more than 200 steps is stored with 200 of them (its +top-level steps and its failed steps first, then the most recent of the rest); +a history over its 64 KB limit is stored as its most recent steps; and one that +still does not fit is stored with none. The platform reads what the history +kept, and a run named only by a step that was dropped reads as one the flow +went past: it is not read. In the last two cases the platform can still tell, +from the run's count of its steps, that steps are missing, and treats the +history as one that does not list every run, above. In the first it cannot. A +`subflow` or `map` step that is not among the 200 (one that succeeded inside a +`loop`, `parallel` or `try_catch`, or an early step of a very long run) no +longer lists the runs it started: a failure the flow routed inside one of them +is not seen, and the approval can be written as finished, with no notice. A +process that still holds the run in memory reads all of its steps. For a flow +whose run can log more than 200 steps and that starts child flows inside such a +region, read the outcome of those child runs in the flow's run history as well. + +Every decision on an approval any step of which can act on an object that +declares `closedStates` leaves a mark on its request (`unjudged_since`), also +where nothing is held back. The mark is cleared once the approval is judged, or +when its next request opens. The plugin's sweeps run a reconciler that judges +every approval whose mark still stands, as the action would have: after a run +that was cancelled, a parent run cancelled while its child's request was pending, +or a process that stopped, as above. Each sweep reads the oldest marks and the +next page of a walk over every marked request, so that approvals that stay in +progress do not keep the newer ones from being judged. Once the mark has stood +for an hour, it also reads as stopped where it stood a run that reports paused +while its pause is gone, and a run parked at a `subflow` or a `map` whose child +run has ended or has no history left, each once two sweeps in a row find it +so. That holds for a `map` over records too: +the platform does not read such an item run's steps, which belong to the item's +own approval, only whether the run has ended. +Where nothing was held back it clears the mark and writes nothing; where it +concluded that a run had stopped, a line in the server log says so. A write that +a rule or a hook refuses is reported as above, once, and tried again on each +sweep while the mark stands. Where the record was deleted, the approval is over: +it is marked abandoned on its latest request, its marks are cleared, and nothing +is written. The delete does that as it lands, below, and the reconciler does it +for a record that went another way. + +### The document is held for the whole approval [#hold] + +On an object that declares `closedStates`, every approval holds the document from +its submission until it is over: while a request is pending, as on any object, +and also through each passage, from a step's decision until the next request +opens or the approval is over (ADR-0162 D5). A passage holds the record and its +direct `master_detail` lines as a pending request does, whatever field the +object closes on and whatever the step's `lockRecord` says: a step that leaves +the record open while its request is pending (`lockRecord: false`) still holds +it once that request is decided. A caller's edit in a passage is refused +`409 RECORD_LOCKED`, so the document cannot change between the decision on it +and the outcome the approval writes. That caller includes an automation that +runs as a user outside the approval's own flow: a record-change flow with +`runAs: 'user'` that a decision sets off starts a run tree of its own, and its +write to the document is refused the same way. Run such a flow with +`runAs: 'system'`, or make the write from the approval's own flow. + +What passes the hold: + +- **The approval's own runs.** A write made by any run of the approval, the run + started for the record or a `subflow` or `map` run under it at any depth, a + hook's write through its own `ctx.api` included, lands. A run is known by the + root run it belongs to, which the automation engine carries on every write of + a run (`flowRootRunId`, beside `flowRunId`). A write a hook makes outside that + context, as another caller, is refused. +- **A system context**, the approval status mirror among them. +- **A write that carries only the mirror field.** +- **The revise window** of a returned request, as on any object. +- **The record's own delete.** It lands and ends the approval: the approval is + marked abandoned on its latest request, its marks are cleared, and nothing is + written. A line's delete, or a delete that cascades into a line, is held as + an edit is. + +A passage lasts as long as the approval's marks stand (`unjudged_since`, above). +A run that pauses between two steps, at a `wait` or a screen, holds the +document while it waits; so does a process that stops in a passage, until the +reconciler judges the approval: at its next sweep where the runs can be read, +otherwise once the hour above has passed. Where that is too long for the +business, the flow should not pause between two steps on such an object. + +An approval that was in flight when its object first declared `closedStates` +left no marks, and is not held between its steps. + +The approvals-family lock read (`getRecordLock`, above) answers for a pending +request only: in a passage it answers `{ "locked": false }` while an edit is +refused `409 RECORD_LOCKED`. A page that offers an edit in a passage learns of +the hold from the refusal. + ## Why Separating *who configures* from *who approves* from *as whom it runs* is the same capability/assignment/requirement decoupling as the rest of authorization (ADR-0066). The `runAs` default of `user` means an approval flow can't silently grant the submitter cross-tenant or cross-owner reach — elevation is opt-in and auditable. That is the safe-by-default posture: the common case respects RLS; the elevated case is explicit. @@ -1427,6 +1849,6 @@ Separating *who configures* from *who approves* from *as whom it runs* is the sa ## See also -- Decision records: **ADR-0049** (`runAs`), **ADR-0066** (unified authorization). +- Decision records: **ADR-0049** (`runAs`), **ADR-0066** (unified authorization), **ADR-0044** (send-back and resubmission), **ADR-0162** (closed states and the approvals on them). - Guide: [Hooks](/docs/automation/hooks) and [Flows](/docs/automation/flows); [Who can see data / automation / interface](/docs/permissions/access-recipes). - Reference: [Flow](/docs/references/automation/flow), [Approval](/docs/references/automation/approval). diff --git a/content/docs/automation/hook-bodies.mdx b/content/docs/automation/hook-bodies.mdx index 4cdd61ef5f7..f81d7258820 100644 --- a/content/docs/automation/hook-bodies.mdx +++ b/content/docs/automation/hook-bodies.mdx @@ -117,6 +117,7 @@ A hook body sees the same server-stamped write provenance an in-process handler | Member | Present when | |---|---| | `ctx.provenance.flowRunId` | The write comes from an automation flow's data node; the value is that flow run's id. | +| `ctx.provenance.flowRootRunId` | Set beside `flowRunId`: the id of the root run of that run's tree, the run itself for a run no other run started. Absent on a run the engine could not place in a tree. | | `ctx.provenance.attributedUserId` | The write is authorized as the system and credited to a real person (for example, the admin behind an identity-adapter call). | | `ctx.provenance.performedByClientId` | An AI client acting through the MCP OAuth door performed the write on behalf of the user in `ctx.session.userId`. | | `ctx.provenance.performedByAgentId` | The in-product AI agent performed the write for the signed-in person in `ctx.session.userId`, whose write it runs as; the value is the agent's name. | @@ -323,7 +324,7 @@ The dropped case is the dangerous one: nothing fails, the step reports success, Which hooks these rules can *see* depends on the command, because every rule in this family opens on `body.language === 'js'`. A hook authored as an inline `handler` function carries no `body`, so it is judged only where the command has first lowered the handler to a metadata body: `objectstack build` always has (it lowers before it parses — see [How the build lowers a handler](#build-pipeline)), and since [#16095](https://github.com/objectstack-ai/objectstack/issues/16095) `objectstack lint` judges that same lowered view, so an author who runs only the pre-flight is told the same thing the build would refuse. Since [#16544](https://github.com/objectstack-ai/objectstack/issues/16544) `objectstack validate` lowers before it parses as well, so all three commands judge the same view of a handler-authored hook — a stack `objectstack validate` passes is one `objectstack build` does not refuse on this family. A handler the build cannot lower (a forbidden token, a module-scope identifier) has no body on any command and is reported by the lowering rules instead, never guessed at here. -Only literal object names and literal payload keys are seen; a `sudo()` chain, a dynamic object name and an object this stack does not declare are all skipped, so the rule has no opinion on them. `.create()` is skipped too, and since [#16249](https://github.com/objectstack-ai/objectstack/issues/16249) it cannot even arrive: `objectstack build` refuses `.create(` at lowering, so a handler spelling it is bundled and never becomes a `body` these rules parse, and the write-shape ledger no longer advertises the verb. The reason behind that refusal is about the **sandbox** rather than the engine: the VM-side `ctx.api.object()` installs `insert` / `update` / `delete` / `updateMany` / `deleteMany` / `upsert` and no `create` leaf, and the `IScopedObjectRepository` contract declares `insert` only — so a body calling `.create()` threw `TypeError: not a function` on its first run, aborting the triggering write under the default `onError: 'abort'`. A loud failure, never a silent drop; the same payload spelled `.insert()` is what the rules judge. The flow surface has carried the same gate as `flow-update-readonly-field` since [#3425](https://github.com/objectstack-ai/objectstack/issues/3425), and since [#15394](https://github.com/objectstack-ai/objectstack/issues/15394) it reports a non-`runAs: 'system'` `create_record` node's static-`readonly` write at the same **error**, again with no conditional finding on a create. +Only literal object names and literal payload keys are seen; a `sudo()` chain, a dynamic object name and an object this stack does not declare are all skipped, so the rule has no opinion on them. `.create()` is skipped too, and since [#16249](https://github.com/objectstack-ai/objectstack/issues/16249) it cannot even arrive: `objectstack build` refuses `.create(` at lowering, so a handler spelling it is bundled and never becomes a `body` these rules parse, and the write-shape ledger no longer advertises the verb. The reason behind that refusal is about the **sandbox** rather than the engine: the VM-side `ctx.api.object()` installs `insert` / `update` / `updateById` / `delete` / `updateMany` / `deleteMany` / `upsert` and no `create` leaf, and the `IScopedObjectRepository` contract declares `insert` only — so a body calling `.create()` threw `TypeError: not a function` on its first run, aborting the triggering write under the default `onError: 'abort'`. A loud failure, never a silent drop; the same payload spelled `.insert()` is what the rules judge. The flow surface has carried the same gate as `flow-update-readonly-field` since [#3425](https://github.com/objectstack-ai/objectstack/issues/3425), and since [#15394](https://github.com/objectstack-ai/objectstack/issues/15394) it reports a non-`runAs: 'system'` `create_record` node's static-`readonly` write at the same **error**, again with no conditional finding on a create. The table above is about a **hook** body. An **action** body is the one surface where the answer changes, so read this before you move a body from one to the other: an action body runs **elevated** — its `ctx.api` is built over the caller's envelope with `isSystem` set, which is the same trusted posture that lets an action bypass row and field permissions — and the static strip applies only to non-system callers. So `ctx.api.object('x').update({ someReadonlyField })` **lands** in an action, and there is no finding for it. Elevation does not waive the *conditional* lock, though, so that half does carry across: `action-api-update-readonly-when-field` — a **warning** — on an action body's literal `ctx.api` update to a `readonlyWhen` field ([#13770](https://github.com/objectstack-ai/objectstack/issues/13770)). Net effect when you move a body: a `readonly` write changes behaviour, a `readonlyWhen` write does not. @@ -452,12 +453,18 @@ The extractor scans each body for known patterns and adds the matching capabilit | Pattern in source | Inferred capability | |---|---| | `*.object(…).find / findOne / count / aggregate / get / list` | `api.read` | -| `*.object(…).insert / update / upsert / delete / patch / remove / create` | `api.write` | -| `ctx.crypto.randomUUID` | `crypto.uuid` | -| `ctx.log.info / warn / error / debug` | `log` | -| `*.title()` — the related-record form only; bare `ctx.title()` names this record and needs no token | `api.read` | - -The matcher is deliberately over-inclusive — it names spellings the VM does not install (`patch`, `remove`, `get`, `list`, `create`) because an over-inferred token costs nothing the sandbox ever checks, while an under-inferred one surfaces as a sandbox refusal far from its cause. `create` is listed only for that reason: a body spelling it is refused at lowering (see [What the sandbox forbids](#what-the-sandbox-forbids)) and never reaches inference at all. +| The same read leaves on a bound handle — `const h = ctx.api.object('x'); h.find(…)` | `api.read` | +| `*.object(…).insert / update / updateById / updateMany / upsert / delete / deleteMany / patch / remove / create` | `api.write` | +| `*.transaction(…)` — `ctx.api.transaction(…)`, the same call on an alias of `ctx.api` (`const api = ctx.api; api.transaction(…)`), `?.` allowed on either side, or the member destructured off it (`const { transaction } = ctx.api; transaction(…)`) | `api.transaction` | +| `ctx.crypto.randomUUID`, or a `randomUUID()` call on a local alias of `ctx.crypto` (`const c = ctx.crypto; c.randomUUID()`, `const { crypto } = ctx; crypto.randomUUID()`) | `crypto.uuid` | +| `ctx.log.info / warn / error / debug`, or the same calls on a local alias of `ctx.log` (`const l = ctx.log; l.info(…)`, `const { log } = ctx; log.warn(…)`) | `log` | +| `ctx.email.send`, or a `send(…)` call on a local alias of `ctx.email` (`const e = ctx.email; e.send(…)`, `const { email } = ctx; email.send(…)`) | `email.send` | +| `ctx.activity.append`, or an `append(…)` call on a local alias of `ctx.activity` (`const a = ctx.activity; a.append(…)`, `const { activity } = ctx; activity.append(…)`) | `activity.append` | +| `*.title()` — the related-record form only; bare `ctx.title()` names this record and needs no token. On a hook, also a call with an argument on a local alias of `ctx.title` (`const t = ctx.title; t('account_id')`, `const { title } = ctx; title('account_id')`) | `api.read` | + +A local alias counts in two shapes only, the ones the publish check reads: a name bound to the member itself (`const l = ctx.log`), or a plain name destructured off `ctx` (`const { log } = ctx`, `const { log: l } = ctx`). The name must be declared once and never assigned again; a destructure with a default, an alias of an alias, and a field read that is not a call (`const f = l.info`) infer nothing. + +The matcher is deliberately over-inclusive — it names spellings the VM does not install (`patch`, `remove`, `get`, `list`, `create`) because an over-inferred token costs nothing the sandbox ever checks, while an under-inferred one surfaces as a sandbox refusal far from its cause. `create` is listed only for that reason: a body spelling it is refused at lowering (see [What the sandbox forbids](#what-the-sandbox-forbids)) and never reaches inference at all. `email.send` is the one exception: a hook body is never granted it, so a hook handler that spells `ctx.email.send` or calls `send(…)` on an alias of `ctx.email` is refused at build. Send mail on a record change from an action, a job or a flow. When inference does not derive what a body needs, declare the tokens yourself by supplying `body` on the hook or action instead of a `handler`: diff --git a/content/docs/data-modeling/import-mappings.mdx b/content/docs/data-modeling/import-mappings.mdx index e2dff2c5e00..3841d7a155d 100644 --- a/content/docs/data-modeling/import-mappings.mdx +++ b/content/docs/data-modeling/import-mappings.mdx @@ -376,10 +376,10 @@ the scope and names the cause (`Task: "Design review" could not be looked up wit "Gemini": the target field this lookup's dependsOn filters by cannot be filtered on, …`), never `reference_out_of_scope`. Point `param` at a stored field of the target. `os validate` and the runtime publish gate refuse such an entry at authoring (`object-field-ref-unknown`, -naming the target field). That check judges a `lookup`, `master_detail` or `user` field, against -the objects it can see, so an import still meets this sentence in three cases: on metadata stored -before the check; on a `tree` field or a legacy `reference` field, which the import scopes by -`dependsOn` too but the check does not judge; and after an `os validate` of a stack that does not +naming the target field). That check judges every field the import scopes, a `lookup`, +`master_detail`, `user` or `tree` field (a `tree` against its own object, with or without a +`reference`), against the objects it can see, so an import still meets this sentence in two +cases: on metadata stored before the check; and after an `os validate` of a stack that does not hold both objects, such as a target object from another package, or a target field turned into a formula in a package validated without the object whose lookup filters by it. The runtime publish gate judges against every object the environment serves, so a publish that turns such a target diff --git a/content/docs/data-modeling/object-extensions.mdx b/content/docs/data-modeling/object-extensions.mdx index 9e34d7cafa9..8fe0d270fe0 100644 --- a/content/docs/data-modeling/object-extensions.mdx +++ b/content/docs/data-modeling/object-extensions.mdx @@ -367,9 +367,12 @@ vendor's, another package's extension's, the pair's own `__c` fields. A group's - **The pair is the App's.** An object's pair is the `.custom` package of the App the object belongs to: for an object a module of an App owns, that is the App's pair. A `.custom` package an earlier version created for the module itself is still read while - it is installed; where both write a key, the App's pair is served. What any other - `.custom` package writes under these keys is not refused at those doors; it is not - applied, alone or beside the pair, and the boot log names the package and the object. + it is installed; where both write a key, the App's pair is served. Any other `.custom` + package that writes these keys is refused at save and publish (a package duplicate + included) and at install, and the refusal names the object's pair. `os validate` and + `os build` cannot see which packages are installed, so they do not judge it; what + reaches a running environment past the doors is not applied, alone or beside the pair, + and the boot log names the package and the object. - **Hiding a field is written in the arrangement.** `hidden` is not a display property a `fieldPatches` entry may set: a hidden field is also left out of the search index and out of a form's required check, so it is more than display. To keep a vendor field off diff --git a/content/docs/deployment/app-dependencies.mdx b/content/docs/deployment/app-dependencies.mdx index 3e17c51e125..019c52f8ffd 100644 --- a/content/docs/deployment/app-dependencies.mdx +++ b/content/docs/deployment/app-dependencies.mdx @@ -33,15 +33,28 @@ export default defineStack({ The declaration does two things: -- **It opens the reference.** The runtime save door judges a list view against - your package's own objects and those of the packages your manifest declares, - transitively; a view bound to an object outside that set is refused there, - `422`, and the fix it prints is this declaration. A dependency opens the - reference, not the data: users still see the other app's records under that - app's own permission sets and sharing rules. +- **It opens the reference.** The runtime save door judges the bindings below + against your package's own objects and those of the packages your manifest + declares, transitively; a binding to an object outside that set is refused + there, `422`, and the fix it prints is this declaration. A dependency opens + the reference, not the data: users still see the other app's records under + that app's own permission sets and sharing rules. - **It is checked before install** — below. - **It lets your package share the depended-on app's namespace** — below. +The bindings the save door judges this way, when the item is saved into a +package, include: + +| You save | The binding judged | +|:---|:---| +| A flow | its trigger object | +| A flow | the `objectName` of each `get_record`, `create_record`, `update_record` and `delete_record` node, and of a `screen` node that renders an object's form, nested nodes included | +| A dataset | its base object | +| A list view | its object | +| A form | its object | +| A knowledge source | its object | +| A standalone action | its `objectName` | + Every entry is required; there is no optional arm. Declare only the packages your app actually references. Two modules of one app need not declare each other: each declares the app, and that is enough for both to install, in either diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 115c5ca2e5c..a1f8a6c98c2 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -1341,6 +1341,7 @@ written. | `os migrate security-catalog-overlays --apply` | **Refuses** likewise — it deletes `sys_metadata` rows, and a live process saving metadata is exactly the collision | | `os migrate packageless-overlays --apply` | **Refuses** likewise — it moves `sys_metadata` rows into each base's pair | | `os migrate stored-references bind` | **Refuses** likewise — it writes one row's package column | +| `os migrate stored-forms` | Warns and continues — it is read-only | The check applies to SQLite only: Postgres and MySQL take their own server-side locks. Only same-user processes are visible without elevated privileges, and a @@ -1564,6 +1565,7 @@ where the data lives. | `os migrate meta --stored` | Replay the metadata conversion chain over this deployment's `sys_metadata` rows and rewrite the ones still carrying a pre-protocol shape. Hygiene, not a gate — nothing depends on it having run | | `os migrate security-catalog-overlays` | List the environment-wide permission-set and position rows (the legacy plurals `permissions` / `positions` included) stored over a name a configured package holds — the rows a v18 cold boot refuses — each with the package that holds its name; `--apply` deletes them, one history tombstone per row. Run it before the first v18 boot, with the flags and environment the deployment boots with: the platform security plugin's sets are held only where `os serve` composes it (an auth secret set, and the `auth` tier on), and the step takes `serve`'s `--preset` and `--dev` with `serve`'s meaning. Adopts nothing; exits 1 while it lists a row | | `os migrate packageless-overlays` | List the package-less view, dashboard, report, translation and email-template rows stored over a name exactly one installed package ships — the customizations Setup saved before ADR-0146 D11 closed that write — and with `--apply` move each into that package's paired `.custom` (created when absent) as a declared override, `basedOn` the base's installed version; the package-less row is deleted only after the moved one reads back as served. A name no package ships is environment metadata and is not touched; a name several packages ship, or one the pair already holds a row of, is listed and left with the reason. So is a view container (`list`, `listViews`, `form`, `formViews`): only a single view declares an override, so it is listed `cannot_declare` and never attempted, with the way out — save each of its views into the pair as a single view, then delete the container row. Takes `serve`'s `--preset` and `--dev`. Idempotent: a second run moves nothing. Run it once after upgrading | +| `os migrate stored-forms` | Read-only: list what the upgrade to the next protocol major does with every stored row that still holds a form in an old shape (a view container's `form`, a `formViews` entry, a `viewKind: 'form'` item) — kept, moved, folded, removed as an internal record form, or left in place — and whether that upgrade can switch, naming each row that holds it (its `.custom` pair cannot be created, or its form content cannot be read) with the action for its cause, and listing the old-shape drafts that cannot be published after the upgrade. No `--apply`: the move runs only inside the upgrade command. Takes `serve`'s `--preset` and `--dev`. See [Check stored forms before the next major](/docs/deployment/stored-forms-upgrade) | | `os migrate stored-references` | List the stored references the upgrade left naming no package because the one resolution rule (ADR-0150 D3) refuses them: a user's permission-set assignment, an audience-binding suggestion, a managed sharing rule, a queue membership, an open approval request, a paused flow run, a flow credential, a flow dispatch key, a connector connection, an assignment cursor or a legacy email template whose name more than one package holds, each with its row id and every candidate by its qualified address (`namespace/name`). A suggestion a package wrote naming an environment-authored permission set, or one held only outside the package's declared dependencies, is listed with the fix and is never bindable. Also lists the packaged fields whose picklist the rule refuses (served with no options) the names two packages held before the one-holder rule, and each installed package whose namespace spells a literal segment of the address grammar (`actions`, `connectors`, `global`, `hooks`, `oauth`, `runs`, `trigger`): the boot keeps it with one warning, its items are read with `?package=ID`, and only a rename of its namespace gives them qualified addresses at the door that reads the literal (for `runs` that door is the inbound hook alone, reached at its bare address until then). Read-only, and `--json` prints the same bytes on every run. Run before the release's first boot, it reads a table that has no package column yet as nothing bound yet, lists the rows that boot's backfill will leave unbound, and says so once; it adds no column. A table this composition does not carry (automation, approvals) is named, not skipped: compose as `os serve` does, with `--preset`/`--dev`. Then `os migrate stored-references bind --table T --id ID --package P` writes the package you chose into that one row: it asks the rule again first and refuses, writing nothing, when the row is already bound, now resolves on its own, or the package is no longer a candidate (a stale report), and refuses (`duplicate`) a bind the table's unique key refuses because a row bound to that package already holds the key, such as a connector connection the instance already has in that organization. Each bind leaves a `sys_audit_log` row; a second run writes nothing. Confirm with `--yes` | | `os migrate duplicates` | Report business identifiers already minted twice across the organization partitions, and the rows blocking the boot-time NULL-safe index tightenings — a read-only inventory as JSON on stdout. Renumbers nothing and writes no row and no schema; run it before the boot-time tenancy repair, which overwrites part of the evidence | diff --git a/content/docs/deployment/environment-variables.mdx b/content/docs/deployment/environment-variables.mdx index 808185687cb..751da2a0864 100644 --- a/content/docs/deployment/environment-variables.mdx +++ b/content/docs/deployment/environment-variables.mdx @@ -53,6 +53,8 @@ read at startup unless noted otherwise. Boolean variables accept `true` / `false | `OS_DATABASE_DRIVER` | enum | inferred | Force a specific driver when the URL is ambiguous. `sqlite` \| `sqlite-wasm` \| `postgres` \| `mysql` \| `mongodb` \| `turso`. `memory` / `mingo` / `in-memory` are refused at boot: the in-memory engine cannot serve a tenant-scoped read, so use `os dev --fresh` or `OS_DATABASE_URL=:memory:` instead. `mysql` is a supported deployment target that carries three dialect caveats — two of them integrity guarantees MySQL cannot enforce at the database. Read [MySQL dialect caveats](/docs/data-modeling/drivers#mysql-dialect-caveats) before choosing it. | | `OS_DATABASE_SQLITE_JOURNAL_MODE` | enum | `wal` | Journal mode for **file-backed** SQLite. `wal` (default) lets a dev server and CLI commands share one file without blocking each other, and is what makes the `os migrate` occupancy check reliable. Set to `delete` for SQLite's rollback journal — required when the database lives on a **network filesystem** (NFS/SMB), where WAL cannot work. The setting is applied, not merely skipped: `delete` converts a database that already adopted WAL back. Ignored for `:memory:`, for the WASM SQLite driver, and for non-SQLite drivers. A per-datasource `sqliteJournalMode` in driver config outranks it. See [Journal mode](/docs/data-modeling/drivers#journal-mode-wal-and-cross-process-access). | | `OS_DATABASE_POOL_MAX` | integer | `5` | Maximum pooled connections **each replica** opens to `postgres` / `mysql`. The pool, not the database, is usually what caps authed throughput on a multi-replica deployment: at the default of 5 a 3-replica cluster reaches at most ~15 connections, which can plateau the data API while the database still has most of its `max_connections` free. Size it so **`replicas × OS_DATABASE_POOL_MAX` stays below the database's `max_connections`**, leaving headroom for migrations and admin connections — e.g. 3 replicas × 40 = 120 against `max_connections=200`. A per-datasource `pool.max` in the datasource's own definition outranks it, and with the variable unset nothing changes. A value that is not a positive integer refuses the boot rather than falling back to the default. Ignored by `memory` / `sqlite` / `sqlite-wasm` / `turso`, which open no pool — declaring a `pool` block on those is an error, not a silent drop. | +| `OS_KNOWLEDGE_POOL_MAX` | integer | `20` | Connections in the `knowledge-pgvector` store's own pool, opened by **each replica** beside its `OS_DATABASE_POOL_MAX` pool (both reach the same server when the store is in the platform database, and a running build holds one more). The plugin's `poolMax` option wins over it. Keep `replicas × (OS_DATABASE_POOL_MAX + OS_KNOWLEDGE_POOL_MAX + builds running at once)` plus headroom below the database's `max_connections`; at the default, 3 replicas take 60 store connections, and the [store's README](https://github.com/objectstack-ai/objectstack/tree/main/packages/plugins/knowledge-pgvector#pool-size-and-time-limit) gives the formula and figures for `max_connections=200`. A value that is not a positive integer refuses the boot, naming the variable; blank reads as unset. A larger pool does not make one search faster. | +| `OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS` | integer | `10000` | The longest **one search statement** of the `knowledge-pgvector` store may run, in milliseconds: PostgreSQL's `statement_timeout`, set with `SET LOCAL` in that statement's own transaction, so it holds behind a transaction-mode pooler and touches no session setting. A statement past it is stopped and the search refused `TIMEOUT` (504), never answered empty. The plugin's `statementTimeoutMs` option wins over it. A value that is not a positive integer refuses the boot, naming the variable; blank reads as unset. | | `OS_ALLOW_DRIVER_CONNECT_FAILURE` | boolean | `false` | Escape hatch for the driver-connect boot guard. By default a data driver that fails to connect at startup **refuses the boot** — a server that cannot reach its database must not report itself started and then fail every request. The same guard covers a **declared datasource** that objects bind to via `datasource: '…'`, or an `external` one with `validation.onMismatch: 'fail'`: those objects have no fallback datasource, so an unconnected one means they are all dead. Set to `1` to boot anyway, in an explicitly degraded state logged loudly at startup. There is **no reconnection**: whatever failed stays dead for the process lifetime and every query and schema sync routed to it fails. | | `OS_STORAGE_LOCAL_ROOT` | path | `./.objectstack/data/uploads` | Root directory for the local file storage adapter, relative to the process cwd (used by `os serve`'s default `storage` capability wiring). This is the same value as **Setup → Settings → File Storage → Root directory**; setting it here pins that field (it shows as locked-by-env). Renamed from `OS_STORAGE_ROOT` — see below. | | `OS_STORAGE_ROOT` | path | — | **Deprecated alias for `OS_STORAGE_LOCAL_ROOT`.** Still read for one release, with a startup warning; it will be removed in a future major. Rename it now. Before the rename the two halves of the platform spelled this value differently — the CLI wrote `OS_STORAGE_ROOT` while the settings service read `OS_STORAGE_LOCAL_ROOT` — so **any value other than the default was silently discarded** at startup and uploads landed in `./.objectstack/data/uploads` regardless. If you set `OS_STORAGE_ROOT` on an older release, check where your uploads actually are before assuming a backup covered them. | diff --git a/content/docs/deployment/meta.json b/content/docs/deployment/meta.json index a82e19a78ac..e9107b8075e 100644 --- a/content/docs/deployment/meta.json +++ b/content/docs/deployment/meta.json @@ -6,6 +6,7 @@ "backup-restore", "tenancy-modes", "seed-tenancy-repair", + "stored-forms-upgrade", "single-project-mode", "marketplace-handbook", "publish-and-preview", diff --git a/content/docs/deployment/stored-forms-upgrade.mdx b/content/docs/deployment/stored-forms-upgrade.mdx new file mode 100644 index 00000000000..4e3d63b6bd3 --- /dev/null +++ b/content/docs/deployment/stored-forms-upgrade.mdx @@ -0,0 +1,142 @@ +--- +title: Check stored forms before the next major +navTitle: Stored Forms Check +description: What `os migrate stored-forms` reports about the forms your database still stores as views, what the upgrade to the next protocol major will do with each, and how to clear a row that holds the upgrade. +--- + +A form used to be stored as a view: a view container's `form`, a `formViews` +entry, or a view item with `viewKind: 'form'`. Forms are now their own +metadata type, and the next protocol major stops reading those three shapes. +Whatever your database still stores in them is moved by the major's upgrade +command, in the same run that switches to the major. The move and the switch +are all or nothing: if one stored row cannot be moved, the upgrade does not +switch, and the deployment stays on the release it is running. + +`os migrate stored-forms` shows you that outcome before you upgrade. It writes +nothing, and it has no `--apply`: the move is reached only from the upgrade +command ([below](#what-the-upgrade-command-writes)). + +```bash +os migrate stored-forms +os migrate stored-forms --json +``` + +It composes the deployment the way `os serve` does, so pass the `--preset` +and `--dev` flags the deployment boots with, and `--database-url` (or +`$OS_DATABASE_URL`) for the database. The boot is read-only. The command exits +`0` whenever the check ran; `canSwitch` in the `--json` output says whether +the upgrade would switch. + +## What it reports, per form + +A form is reported at each package that can serve it: a read-only package +that ships it (an installed app, or a package your code provides), a writable +package of your own, or the environment itself when no package ships it. + +| Outcome | What the upgrade does | +|---|---| +| **kept** | The form is already stored as a form. The rows the server serves behind it at that package fold into it. | +| **moves** | The row moves to a form row, with its body as written: into the package's paired `.custom` package as a declared override for a read-only package, into the package itself for a writable one, or into the environment. An override already stored in a `.custom` package keeps its package and the version it is based on. A row bound to a read-only package that ships no form of that name, or an override of a package that ships none, moves into that package's `.custom` package as a form of its own, with no override declared; its public address answers as it does today. Where the server today serves such a row at one other package's address, it moves as a row of that package does, into that package's `.custom` package as a declared override. The rows the server serves behind the moved row at that package fold into it. | +| **will be removed** | The row is an internal record form: a create or edit form with no public link that no action opens, over nothing that has a link. New and Edit follow the object's field groups instead, and the report says whether the object declares any. A row bound to no package is read at every package that ships its form: it is removed only when it is an internal record form at each of them, and moves at each of them otherwise. An older row behind the removed one goes with it, unless another package serves that row: the report then names it as not removed, with what happens to it there. | +| **left in place** | Nothing moves. The row served for the name carries no form (a list stored over it, alone or with older form rows behind it), or an internal record form is served ahead of a row with a public link and is not removed because of it. Every row of the name stays as stored, and the address keeps answering as it does today. Where another package serves that row with a public link and would move it, the row holds the upgrade at every one of those packages instead: both rows stay. Both rows stay as stored at every other package too: where either stands behind a row another package would move or remove, that move or removal holds the upgrade instead of folding or removing it. When the row served is one whose form content cannot be read, the form waits on that row, which holds the upgrade (below). A form no door serves today is left in place by the upgrade too, whatever package its row is bound to: the server serves no form of that name at the address the report names, so nothing of it moves, its rows stay as stored there, and the address keeps answering as it does today. A form that is switched off is not one of these: the server serves it closed, and it moves with its switch. | +| **holds the upgrade** | The row cannot be moved. The report repeats the reason and the action. | + +For each form, the report asks the server whether it serves a form of that +name today at the address the report names it at: a package, or the +environment. For a form stored with no package, the environment's address +covers every place the server serves it, under a package that ships only a +list of that name included. A form it does not serve there is **left in +place** where the table would move it, and also where the move would hold the +upgrade because its `.custom` package cannot be ensured or its destination is +sealed: the upgrade never moves a form into service. + +A list stored behind the row served for a form is not part of it: the upgrade +leaves it as stored, and the report says so. When a row is read at more than +one package, the report names it at each. Where the server today serves one +row at two packages' addresses of one app that would both move it, or two +rows would move into one slot of the app's `.custom` package (a row the +`.custom` package already holds of that name among them), each such row +holds the upgrade: a +`.custom` package holds one row of a form's name, so neither address can be +given a destination. Where the server serves one row at several packages, +of one app or of several, and those packages would not all move it or all +remove it (one moves or removes it, another leaves it in place or holds), +the row holds the upgrade at each of them too: moving or removing a row +takes it from every package that serves it. Nothing moves, and every +address keeps answering as it does today. The row is named once, with every +address it is read at. A row every package that serves it would remove is +removed, and one every package leaves in place is left in place. A row that +holds the upgrade is not folded into another row: where it stands behind a +row that moves, the report names it apart. + +When several rows of one form are stored (an override in the `.custom` +package, a row bound to the package, a row bound to no package), the body +kept is the one served today. A folded row carries one thing: if it switched +the form off (its link kept, `enabled` or `allowAnonymous` set to `false`), the +kept form keeps its link and is switched off too. When the folded row was one +that nothing reads today, that closes a form that is open today. The report +marks it **NEWLY CLOSED**, with the kept form's address. Switch it on again in Setup after +the upgrade if it should stay open. + +A row that declares a public link, or that stands over a form that declares +one, is never offered for deletion. Deleting such a row would open a form +that is closed today. + +## What the upgrade command writes + +The major's upgrade command runs the same check first, and writes only when +no row holds the upgrade. If one row holds it, nothing is written: every +stored row stays byte for byte as it is, both public doors answer as they do +today, and the deployment stays on the release it is running. + +Otherwise, the `.custom` packages the moves land in are created first, +through the one path that creates them, before any row is written. They stay +if the run fails: an empty `.custom` package changes no answer, and the next +run reuses it. Then, in one transaction: + +1. Each form that moves is written as a form row at its destination, with its + body as stored. A form whose folded row switched it off is written switched + off, its link kept. Each written row is read back before anything else + changes. +2. Then the old rows go: a view item row is deleted; a stored view container + is saved again without the form it held, its lists and any form it still + keeps byte for byte as they were. A container left with nothing in it is + deleted. +3. Each internal record form listed as **will be removed** is deleted the same + way, and the report carries its body. + +If any step fails, the transaction rolls back and every stored row stays as +it was. + +The upgrade command writes only on a database that can roll a transaction +back. Where the database's driver cannot, the command refuses before it +changes anything (no `.custom` package is created either) and names the +driver. Run the upgrade against a database whose driver supports +transactions, or stay on the release you are running. `os migrate +stored-forms` still reports what the upgrade would move, and says on such a +database that the upgrade's run will be refused. A run with nothing +to move or remove is not refused. + +A form left in place is not touched, nor is a draft. Run the command again and +it finds nothing left to move. + +## Clearing a row that holds the upgrade + +| Cause | Who can clear it | What to do | +|---|---|---| +| The paired `.custom` package cannot be created: another package sits under its id or holds its namespace, or the app that carries the package is not installed | The administrator | Make the fix the quoted refusal names on the release you are running, then run the check again. | +| A `.custom` package an earlier version created for one package of the app holds the namespace | No one, on this release | The row holds the upgrade until that package is re-identified as the app's `.custom` package (ADR-0146 D3, merge question 12), and no command on this release does that. The row keeps working as it does today meanwhile. | +| The app declares no namespace, or an invalid one; its version is not SemVer; or the package belongs to several apps and its namespace picks none | The app's author | The deployment stays on the release it is running until the app ships a version without the cause. The row keeps working as it does today meanwhile. | +| The package is a kernel package, which has no `.custom` package in this version | The platform maintainers | Report it before upgrading. | +| Two rows would land in one slot of an app's `.custom` package, or one row that several packages serve would not be treated alike by all of them | No one, on this release | No exit from it was measured: the deployment stays on the release it is running, and every address keeps answering as it does today. Where the row is read at two packages of one app that would both move it, the app shipping the form from one of those packages only lets it be read at that package alone. Where the row waits on another hold of its own, it takes that hold's row above. | +| Another package ships a `form` item under the form's name, so the row would be written over a managed package's item, which is sealed | The author of the package that ships it | No exit from it was measured: the deployment stays on the release it is running, and the row keeps working as it does today. | +| The stored view's form content cannot be read | The administrator | Save the view again with its form content repaired (a `form` or `formViews` entry that is an object), then run the check again. On the release you are running, both public doors answer for the row as they do today. On the next major its links close, and that server's start-up log names each such row and points to this command. | + +## Also listed + +- **Drafts**: a draft view with form content in an old shape is neither moved + nor deleted. After the upgrade it cannot be published, so publish the drafts + you want to keep before upgrading. A form that moves names its draft, which + stays behind as stored. +- **Shared addresses**: a public address that two form names declare, such as + a retired form and the one that replaced it. diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 71244eff42d..39306d40c23 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -123,14 +123,14 @@ no declared page, **fails** validation; a `url` path whose The same gate covers the reference sites that are plain strings in the schema: an action param's record-picker target, a dashboard filter's options source, a navigation capability gate, and every surface that binds an action **by name** -(`bulkActions` / `rowActions`, a page's `record:quick_actions`, a nav action item). +(`rowActions`, an aggregate `bulkActionDefs` entry, a page's `record:quick_actions`, a nav action item). ```ts // ✗ the platform user object is `sys_user` — `user` resolves to nothing → error { name: 'owner', type: 'lookup', reference: 'user' } // ✗ no action named `mass_update` is defined anywhere → error -defineView({ /* … */ bulkActions: ['mass_update', 'mass_delete'] }) +defineView({ /* … */ list: { rowActions: ['mass_update', 'mass_delete'] } }) // ⚠ platform-shaped, but no known package registers it → warning { id: 'nav_approvals', type: 'object', objectName: 'sys_approval_process', @@ -507,8 +507,8 @@ orthogonal to both, and no cell here can carry it; it is written out in | Ordering comparands naming a date-range preset — `last_30_days` in a `>=` position (#8793) | ✓ | ✓ | ✓ | ✓ᵈᵛᵒᵖᶠʳ | | Empty filter combinators — `$and: []`, `$or: []`, `$not: {}` (#5330) | ✓ | ✓ | ✓ | ✓ᶠʳ | | Object & action name references (#3583) — and the object a seed dataset, a flow `get_record` / `create_record` / `update_record` / `delete_record` / object-form `screen` node or a standalone action is bound to (`object-reference-unknown`, #35143); a flow node's miss is a warning on the CLI, where a declared dependency may define the object, and an error at the publish door; at the publish door a seed over an unknown object is the save door's own refusal (#34864) | ✓ | ✓ | ✓ | ✓ᶠᵈᵗᵃᶜ | -| Reference integrity — flow node writes, template paths, read-only writes (#3583); at the publish door each write type runs only the members that declare it, and the flow members run on `flow` alone (#9313) | ✓ | ✓ | ✓ | ✓ᶠᵛᵒᵈᵗʳᵖᵃᶜ | -| List-view field members — a list view's `sort` (a `sortable: false` field, a `formula`, an unknown name: `sort-field-unsortable`), its `searchableFields` (`searchable-field-unknown`) and its field references, columns, filter keys, grouping and the board bindings (`list-view-field-unknown`); a filter key on a `formula` field, which the engine refuses to filter by (`list-view-filter-field-virtual`, #35143), and, advisory, a board grouped by a field with no fixed set of lanes (`list-view-kanban-group-field-uncategorical`, #35143); the row merges three members, so its codes follow no one rule's order, and the `page` door runs the sort member only (#9313, #15495, #30095) | ✓ | ✓ | ✓ | ✓ᶠᵛᵒᵖ | +| Reference integrity — flow node writes, template paths, read-only writes (#3583); at the publish door each write type runs only the members that declare it, and the flow members run on `flow` alone (#9313); a `translation` write runs only the translation-key member, advisory only and never a 422, on the families the per-write snapshot carries (objects, their fields and inline options, validation rules, milestones, permission sets) (#38623), and the apps and their navigation items against the apps the environment serves, navigation contributions included, so a platform app this deployment does not serve is reported too (#38649) | ✓ | ✓ | ✓ | ✓ᶠᵛᵒᵈᵗʳᵖᵃᶜᵗ | +| List-view field members — a list view's `sort` (a `sortable: false` field, a `formula`, an unknown name: `sort-field-unsortable`), its `searchableFields` (`searchable-field-unknown`) and its field references, columns, filter keys, grouping and the board bindings (`list-view-field-unknown`); a filter key on a `formula` field, which the engine refuses to filter by (`list-view-filter-field-virtual`, #35143), a grid list view's grouping level over a multi-valued, JSON-stored or `formula` field, which the engine refuses to group by (`list-view-group-field-ungroupable`, #38433), and, advisory, a board grouped by a field with no fixed set of lanes (`list-view-kanban-group-field-uncategorical`, #35143); the row merges three members, so its codes follow no one rule's order, and the `page` door runs the sort member only (#9313, #15495, #30095) | ✓ | ✓ | ✓ | ✓ᶠᵛᵒᵖ | | Page-component field bindings (#3583) | ✓ | ✓ | ✓ | ✓ᶠ | | React page block field bindings — §10 (#4340) | ✓ | ✓ | ✓ | ✓ᶠ | | Chart bindings outside dashboards (#3583) | ✓ | ✓ | ✓ | ✓ᶠʳᵛᵒ | @@ -522,9 +522,11 @@ orthogonal to both, and no cell here can carry it; it is written out in | Page variable declarations — each name once and never blank, a `defaultValue` of its declared type, a `source` naming a component the page holds (#28663, #28725) | ✓ | ✓ | ✓ | ✓ᵖ | | JSX / React page source parses (ADR-0080/0081) | ✓ | ✓ | ✓ | — | | Script action bodies compile in the runtime's wrapper — an L2 action's `body.source` that does not compile as the body of `(async (input, ctx) => { … })`, most often `const input = …` redeclaring a parameter; an object write runs it over its inline `actions[]`, so an object write cannot republish a refused body (`action-body-does-not-compile`, #34884) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | -| Script action bodies hold the grant they call — an L2 action body that calls a `ctx.api` write (`insert`, `update`, `delete`, `updateMany`, `deleteMany`, `upsert`) without `api.write` in its `body.capabilities`, which the sandbox refuses at every call (`action-body-write-capability-undeclared`, #35143) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | +| Script action bodies hold the grant they call — an L2 action body that calls a `ctx.api` write (`insert`, `update`, `updateById`, `delete`, `updateMany`, `deleteMany`, `upsert`) without `api.write` in its `body.capabilities`, which the sandbox refuses at every call (`action-body-write-capability-undeclared`, #35143) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | | Seed record keys — a seed record key, or a seed `columns` key, that names no field of the dataset's object, no system column injected on it and none of `id` / `created_at` / `updated_at`; the engine's insert door refuses such a record and the seed load loads the rest (`seed-record-unknown-field`, #35143) | ✓ | ✓ | ✓ | ✓ˢ | +| Script action bodies hold every other grant they call — an L2 action body (authored, or lowered by `os build` from a `target` function) that calls a member the sandbox gates behind a token other than `api.write` without that token in its `body.capabilities`: a `ctx.api.object(…)` read leaf (`api.read`), `ctx.api.transaction(…)` (`api.transaction`), `ctx.log.*` (`log`), `ctx.crypto.randomUUID()` (`crypto.uuid`), `ctx.email.send(…)` (`email.send`) or `ctx.activity.append(…)` (`activity.append`), each refused by the sandbox at every call (`action-body-capability-undeclared`, #37815) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | | Hook and job bodies compile in the runtime's wrapper — an L2 hook or job `body.source` that does not compile as the body of `(async (ctx) => { … })`, most often `const ctx = …` redeclaring the parameter or one name declared twice; no door publishes a job, so the publish column is the `hook` write alone (`hook-body-does-not-compile`, `job-body-does-not-compile`, #34987) | ✓ | ✓ | ✓ | ✓ʰ | +| Hook bodies hold the grant they call — an L2 hook body (authored, or lowered by `os build` from a `handler`) that calls a member the sandbox gates without its token in `body.capabilities`: a `ctx.api.object(…)` read or write leaf, `ctx.api.transaction(…)`, `ctx.log.*`, `ctx.crypto.randomUUID()`, `ctx.activity.append(…)` or the related-record form `ctx.title(FIELD)`, each refused by the sandbox at every call; and any `ctx.email.send(…)`, which a hook body is never granted (`hook-body-capability-undeclared`, #37815) | ✓ | ✓ | ✓ | ✓ʰ | | Approval-node approvers (ADR-0090 D3) | ✓ | ✓ | ✓ | ✓ᶠ | | Security posture (ADR-0090 — e.g. every custom object declares `sharingModel`) | ✓ | ✓ | ✓ | ✓ˢᵖᵉᵇᵒ | | Security vocabulary freeze (ADR-0090 D3 — the reserved word, replaced by `permission_set` / `position` / `business_unit`) | ✓ | ✓ | ✓ | ✓ᵒᵖᵉᵇᵖᵒᵃᵒˣ | @@ -566,12 +568,12 @@ orthogonal to both, and no cell here can carry it; it is written out in writes that rule inspects: `✓ᶠ` `flow`, `✓ᵛ` `view`, `✓ᵈ` `dashboard`, `✓ᵒ` `object`, `✓ᵖ` `page`, `✓ˢ` `seed`, `✓ᵇ` `book`, `✓ᵖᵉ` `permission`, `✓ᵖᵒ` `position`, `✓ᵃ` `app`, `✓ᵉ` `email_template`, `✓ᵈᵗ` `dataset`, `✓ʳ` `report`, -`✓ᵃᶜ` `action`, `✓ʰ` `hook`, `✓ᵐ` `mapping`, `✓ᵈˢ` `datasource`, `✓ᶜ` `connector`, `✓ᵒˣ` `object_extension`** — the two +`✓ᵃᶜ` `action`, `✓ʰ` `hook`, `✓ᵐ` `mapping`, `✓ᵈˢ` `datasource`, `✓ᶜ` `connector`, `✓ᵒˣ` `object_extension`, `✓ᵗ` `translation`** — the two `ᵖ`-initial pairs carry a second letter because `page` already holds `ᵖ` on its own, `dataset` and `datasource` carry `ᵈᵗ` and `ᵈˢ` because `dashboard` holds `ᵈ`, `action` carries `ᵃᶜ` because `app` holds `ᵃ`, and `object_extension` carries `ᵒˣ` because `object` holds `ᵒ`, while `connector` takes the bare `ᶜ`. Read the codes **longest-first**: `ᵖᵒ` is `position`, never `page` followed by `object`, `ᵖᵉ` is `permission`, never `page` followed by -`email_template`, `ᵈᵗ` is `dataset`, `ᵈˢ` is `datasource`, `ᵃᶜ` is `action` and `ᵒˣ` is `object_extension`. +`email_template`, `ᵈᵗ` is `dataset`, `ᵈˢ` is `datasource`, `ᵃᶜ` is `action`, `ᵒˣ` is `object_extension`, and a bare `ᵗ` is `translation` — `ᵈᵗ` is still `dataset`, never `dashboard` followed by `translation`. A row whose rules are members of the reference-integrity suite reads the members' own `runtimeTypes` in `packages/lint/src/reference-integrity-suite.ts`, and a member that declares none runs on `flow` writes only (the suite's frozen diff --git a/content/docs/frontend/plugins/plugin-chatbot.mdx b/content/docs/frontend/plugins/plugin-chatbot.mdx index ae23726cb94..7495729c189 100644 --- a/content/docs/frontend/plugins/plugin-chatbot.mdx +++ b/content/docs/frontend/plugins/plugin-chatbot.mdx @@ -660,6 +660,51 @@ export function TurnDrafts({ review, navigate }: { card. - Strings come from the `chatbot.draftReview.*` keys of `@object-ui/i18n`. +### Continue a stopped turn + +An ask turn can stop before it is done, on a time, token or round limit, +answering with what it read so far. When the server can carry that turn on, it +ends the turn with one `data-turn-end` part (`TURN_END_PART_TYPE`, whose data +is a `TurnEndSchema` object from `@objectstack/spec/ai`) and stores the same +object on the turn's last message (`AiConversationMessageSchema.turnEnd`). +`ChatbotEnhanced` reads it through that schema and draws a Continue control +under the answer; a part the schema refuses draws nothing. + +```tsx +import { ChatbotEnhanced, toRuntimeMessages, useObjectChat } from '@object-ui/plugin-chatbot'; + +export function AskChat({ api, conversationId }: { api: string; conversationId: string }) { + const chat = useObjectChat({ api, conversationId }); + return ( + + ); +} +``` + +- Continue is drawn only under the conversation's last answer, when the turn + end says `resumable: true` with `resumesLeft` above zero, nothing is + streaming and the view is not read-only. It shows how many resumes are left. + It is not offered while an earlier answer still holds an answered tool + approval: the chat runtime would write the resume into that answer instead. + Whether a turn may be resumed is the server's call; the chat never reads it + from `reason`. +- Pressing it calls `onResumeTurn` with the turn end's `turnId`. + `useObjectChat().resumeTurn` sends a chat request with + `resume: { turnId }` (`AiChatRequestSchema.resume`) and no new user message, + so no user bubble appears, and the rest of the answer streams into the same + answer. The newest turn end on that answer decides whether Continue is + offered again. +- A message sent after the answer makes it no longer the last one, so Continue + goes away. +- The turn end is one of `STORED_ANSWER_DATA_PARTS`, so Continue survives a + reload from server history and from the message cache. +- Strings come from the `chatbot.continueTurn.*` keys of `@object-ui/i18n`. + ## Examples ### Simple AI Chat diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index 5e8bde2e429..061957318f5 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -79,7 +79,7 @@ The scaffolder does more than copy files. It: ──────────────────────────────────────── Environment: support-desk Namespace: support_desk - Template: blank — Companies and contacts, with platform tasks and notes in the menu — ready to extend + Template: blank — Companies, contacts and help articles, with tasks and notes from the platform in the menu — ready to extend … → Installing AI skills for your coding agent from @objectstack/skills@... … @@ -111,7 +111,7 @@ language: > (open/pending/resolved/closed). Add a **Resolve** action that only shows on > tickets that aren't already resolved or closed. Add a list view (subject, > status, priority) with an "Open tickets" filter, a form for entering tickets, -> and an app with a Support nav group. Run `npm run validate` when you're done. +> and a Support nav group in the app. Run `npm run validate` when you're done. You don't specify field types in TypeScript, wire barrel exports, or remember the CEL scoping rules — the agent does, because the skills told it how. @@ -158,6 +158,13 @@ export const Ticket = ObjectSchema.create({ }), }, + // The create and edit forms lay a ticket out by these groups: one section, + // its fields in the order its `fields` list gives. No field is marked + // `showOnCreate: false`, so the create form asks for all four. + fieldGroups: [ + { key: 'ticket', label: 'Ticket', fields: ['subject', 'description', 'priority', 'status'] }, + ], + sharingModel: 'private', // org-wide default (OWD) — required by the security gate enable: { apiEnabled: true, searchable: true }, }); @@ -212,27 +219,45 @@ export const TicketViews = defineView({ sort: [{ field: 'priority', order: 'desc' }], }, }, - form: { - type: 'simple', - data, - sections: [ - { - name: 'ticket', - label: 'Ticket', - fields: [{ field: 'subject' }, { field: 'description' }, { field: 'priority' }, { field: 'status' }], - }, - ], - }, }); ``` -```typescript title="src/apps/support.app.ts" -import { defineApp } from '@objectstack/spec'; - -export const SupportApp = defineApp({ - name: 'support_desk_support', - label: 'Support', +The fourth change is an edit, not a new file. The `blank` template already +ships the project's one app, `src/apps/main.app.ts` (`support_desk_main_app` once +the scaffolder has renamed it), and its own comment says where a new object +goes: "A package whose manifest type is 'app' holds at most one app, so this is +the one: to put another object in the Console, add a navigation entry for it +below (a 'group' entry with children nests them) rather than a second app". So +the agent puts the **Support** group at the top of that app's `navigation` and +leaves the rest of the file as it was: + +```typescript title="src/apps/main.app.ts" +import * as UI from '@objectstack/spec/ui'; + +/** + * Main App + */ +// This project's app: what the Console lists beside the platform's own apps, +// and what puts an object in the Console's navigation. An object no app lists +// is still served over REST and MCP, but the Console has no route to it. A +// package whose manifest type is 'app' holds at most one app, so this is the +// one: to put another object in the Console, add a navigation entry for it +// below (a 'group' entry with children nests them) rather than a second app, +// and give it a list view — `objectstack generate view OBJECT` writes one. +// +// The menu is the platform's Starter app's: this project's companies, +// contacts and help articles, then the platform's tasks and notes. Tasks and notes are the +// platform objects `sys_task` and `sys_note`, which every environment carries; +// this project declares no copy of them, so a task or a note can be about any +// record without changing who may see that record. No entry carries a label: +// each shows the current, localized label of what it opens. +const mainApp: UI.App = { + name: 'support_desk_main_app', + label: 'Main', navigation: [ + // Added: the Support group, first in the menu. It names its own labels: + // a group opens no object to take one from, and 'Open' names the one + // list view of tickets it opens. { id: 'grp_support', type: 'group', @@ -248,10 +273,24 @@ export const SupportApp = defineApp({ }, ], }, + { id: 'nav_companies', type: 'object', objectName: 'support_desk_company', icon: 'building-2' }, + { id: 'nav_contacts', type: 'object', objectName: 'support_desk_contact', icon: 'contact' }, + { id: 'nav_articles', type: 'object', objectName: 'support_desk_article', icon: 'book-open' }, + // `requiresObject` names the object again because `defineStack` refuses a + // menu entry for an object the stack does not declare unless the entry + // says the object comes from elsewhere — here, the platform. + { id: 'nav_tasks', type: 'object', objectName: 'sys_task', requiresObject: 'sys_task', icon: 'square-check' }, + { id: 'nav_notes', type: 'object', objectName: 'sys_note', requiresObject: 'sys_note', icon: 'notebook-pen' }, ], -}); +}; + +export default mainApp; ``` +A second app file, a `support.app.ts` beside it, would not get past the gate: +`os validate` refuses a package whose manifest type is `app` and that defines +two apps, and names both of them. + The **Resolve** action is a *declarative field write*: `operation: 'update'` with `patch: { status: 'resolved' }` sets the ticket's status when it is clicked. There is no handler to write or register, and the update runs as the signed-in @@ -263,29 +302,50 @@ passes an unregistered one, the `os dev` boot log warns fails when clicked (the [two paths](/docs/ui/actions#give-it-server-behavior--two-paths) a handler takes). -The view file also declares the create and edit **form**, and the form is where the -long-text `description` is entered and shown. The list columns leave it out, so the -form is the only metadata that names it. A field that no consumer names (a view, a form, a -flow, a formula or an action, among the others the rule counts) gets an advisory -`field-no-consumers` warning from `os validate`. - -The agent also **exports each new file from its directory's barrel** — the object -from `src/objects/index.ts`, and the action, view and app from -`src/actions/index.ts`, `src/views/index.ts` and `src/apps/index.ts`. The -starter's `objectstack.config.ts` already hands every barrel to `defineStack()` -through `exportsOf()`, so that export line is the whole wiring and the config is -not edited; adding an `actions:` / `views:` / `apps:` key for the file instead -would duplicate the key and replace that barrel's wiring. There is no -filename-suffix magic: metadata exists in the app only if its barrel exports it, -so if a freshly-authored action doesn't show up, its export line is the first -thing to check. - -What it does **not** touch is what the `blank` template scaffolded in step 1: -the companies and contacts (`src/objects/company.object.ts` and -`contact.object.ts`, seven fields each). Nothing asked for them to go, so they -stay in the project — which is why the counts below read **three** objects and -**eighteen** fields, not one and four. Delete them once the ticket object has -replaced them and the same run reports `1 Objects 4 Fields`. +The view file declares lists only: no file declares a create or edit **form**. +Both forms lay a ticket out by the object's `fieldGroups`: the one **Ticket** +group's `fields` list places the four fields in that section, in the order it +lists them. No field is marked `showOnCreate: false`, so the create form asks +for all four, the long-text `description` among them. The list columns leave +`description` out, so its entry in the group's `fields` list is the only +metadata that names it, and that placement counts as a consumer: a field that +no consumer names (a view column, a field group, a flow, a formula or an +action, among the others the rule counts) gets an advisory +`field-no-consumers` warning from `os validate`, and the run below prints none +for `description`. + +The agent also **exports each new file from its directory's barrel**: one line +at the end of each of the three `index.ts` files, beside the lines the starter +already has there. + +```typescript +// src/objects/index.ts +export { Ticket } from './ticket.object.js'; + +// src/actions/index.ts +export { ResolveTicketAction } from './ticket.actions'; + +// src/views/index.ts +export { TicketViews } from './ticket.view'; +``` + +The app needs no line of its own: `src/apps/index.ts` already exports +`main.app.ts`, the file the agent edited. The starter's `objectstack.config.ts` +already hands every barrel to `defineStack()` through `exportsOf()`, so those +export lines are the whole wiring and the config is not edited; adding an +`actions:` / `views:` key for the file instead would duplicate the key and +replace that barrel's wiring. There is no filename-suffix magic: metadata exists +in the app only if its barrel exports it, so if a freshly-authored action +doesn't show up, its export line is the first thing to check. + +Apart from that one edit to the app, what it does **not** touch is what the +`blank` template scaffolded in step 1: the companies and contacts +(`src/objects/company.object.ts` and `contact.object.ts`, seven fields each) and the help articles +(`article.object.ts`, four fields, with its view and sample articles). Nothing +asked for them to go, so they stay in the project — which is why the counts +below read **four** objects and **twenty-two** fields, not one and four. Delete +them once the ticket object has replaced them and the same run reports +`1 Objects 4 Fields`. This is the same metadata that powers the REST API, the Console UI, **and the MCP tools exposed to AI** — define it once, and ObjectStack derives the rest. @@ -347,8 +407,8 @@ Once it's clean: Support Desk v0.1.0 - Data: 3 Objects 18 Fields - UI: 1 Apps 3 Views 1 Actions + Data: 4 Objects 22 Fields + UI: 1 Apps 4 Views 1 Actions Logic: 0 Flows Security: 0 Positions 0 Permissions Runtime: 3 plugins diff --git a/content/docs/getting-started/your-first-project.mdx b/content/docs/getting-started/your-first-project.mdx index 1f2cf294ea5..5ae784f09f6 100644 --- a/content/docs/getting-started/your-first-project.mdx +++ b/content/docs/getting-started/your-first-project.mdx @@ -83,7 +83,7 @@ bundle) with `--skip-skills` if you prefer — `AGENTS.md` is always written. | Template | Source | Description | |:---|:---|:---| -| `blank` *(default)* | bundled, works offline | Companies and contacts, with platform tasks and notes in the menu — ready to extend | +| `blank` *(default)* | bundled, works offline | Companies, contacts and help articles, with tasks and notes from the platform in the menu — ready to extend | ```bash npm create objectstack@latest my-app -- --template blank diff --git a/content/docs/kernel/runtime-services/queue-service.mdx b/content/docs/kernel/runtime-services/queue-service.mdx index 71699fe6789..b86952df697 100644 --- a/content/docs/kernel/runtime-services/queue-service.mdx +++ b/content/docs/kernel/runtime-services/queue-service.mdx @@ -13,6 +13,7 @@ description: Publish and subscribe to async job queues with services.queue — q ```ts services.queue.publish(queue: string, data: T, options?: QueuePublishOptions): Promise services.queue.subscribe(queue: string, handler: QueueHandler): Promise +services.queue.subscribeBatch?(queue: string, handler: QueueBatchHandler, options: QueueBatchSubscribeOptions): Promise services.queue.unsubscribe(queue: string): Promise services.queue.getQueueSize?(queue: string): Promise services.queue.purge?(queue: string): Promise @@ -21,6 +22,8 @@ services.queue.replay?(messageId: string): Promise services.queue.purgeFailed?(messageId: string): Promise ``` +`subscribeBatch` is optional. It hands the handler up to `options.maxBatch` messages of one queue per call, and the handler answers one `QueueBatchOutcome` per message, in order: `{ ok: true }`, or `{ ok: false, error }`. A failed message takes the same retry and dead-letter path alone, while its neighbours complete. A handler that throws, or answers a different number of outcomes, fails every message of that call. A queue takes either per-message handlers or one batch handler, and `unsubscribe` removes either. A queue service without `subscribeBatch` is consumed one message at a time with `subscribe`. The database queue implements it. + ## Typical Errors - `MESSAGE_NOT_FOUND` — `replay` called with an unknown message id. (`purgeFailed` is idempotent — an unknown id is a silent no-op.) diff --git a/content/docs/permissions/field-level-security.mdx b/content/docs/permissions/field-level-security.mdx index 2d8eea51216..a91c5e4cb72 100644 --- a/content/docs/permissions/field-level-security.mdx +++ b/content/docs/permissions/field-level-security.mdx @@ -189,6 +189,40 @@ For an administrator's walk-through (the editor path, the matching metadata, and when a validation rule is the better tool), see the recipe [Lock fields for a position once a record reaches a stage](/docs/permissions/access-recipes#data-lock-fields-for-a-position-once-a-record-reaches-a-stage). +## Which set opened a field + +When a field is readable that you meant to hide, ask the access explanation +(`/api/v1/security/explain`, see [Authorization](/docs/permissions/authorization)). +Its `fls` layer carries `fieldChannels`: for each field of the object, the +channel that cast the winning read vote and the one that cast the winning edit +vote, with the sets that cast it. + +| Channel | Meaning | +| :--- | :--- | +| `own_row` | A set's own field row opens it, and no held set's row closes it. | +| `other_set_row` | A set's row opens it while another held set's row closes it: grants union across sets, so that set re-opens the field. | +| `view_all_fields` | No row opens it; a set's `viewAllFields` bit casts the read vote. Read only, so it never appears as an edit channel. | +| `default` | No held set names the field, so it follows the object grant. No set is named. | + +```json +{ "field": "collected_total", + "read": { "channel": "other_set_row", "sets": ["finance"] } } +``` + +View All and Modify All never appear: they cast no field vote. `read` or +`edit` is present only where the field merge kept that vote open. A field a +row hides has no `read` entry, a field a row locks has no `edit` entry, a +capability gate closes both, and a field served only through its masking rule +has no `read` entry. A computed field the caller is not served whole has no +`edit` entry either, because a write naming it is refused. A write-only row +(`readable: false, editable: true`) on a stored field reports an `edit` +channel and no `read` channel. Whether +the object grant allows the operation at all is the `object_crud` layer's +answer. When a field one held set hides is readable through another set, the +layer's `detail` names the field and that set. To close it, remove the +re-opening row or `viewAllFields` bit, or move a sensitive field behind its +own `requiredPermissions`. + ## Hidden vs. Read-Only ```typescript diff --git a/content/docs/permissions/locked-items.mdx b/content/docs/permissions/locked-items.mdx index 391e2442a12..f5273683df1 100644 --- a/content/docs/permissions/locked-items.mdx +++ b/content/docs/permissions/locked-items.mdx @@ -78,8 +78,11 @@ There is no switch that lets an administrator lift a lock in place. - **`403 NOT_OVERRIDABLE`** refuses an in-place edit of an item a package ships because the package, not the environment, owns it. It is asked before the lock, so it is the answer you get first for the platform's own objects and - apps: a save that names no package, and the delete of an object, answer - `NOT_OVERRIDABLE` even though those items are also locked. A package you + apps: a save that names no package answers `NOT_OVERRIDABLE` even though + those items are also locked, and so does the delete of an object where the + deployment runs an environment kernel. A save that names the read-only + package instead answers `403 ITEM_LOCKED`, and its message says the package + is read-only rather than giving the item's reason. A package you installed is customized through its paired customization package instead: see [What a managed install keeps](/docs/deployment/install-modes#what-a-managed-install-keeps). Flows, actions and permission sets name their own routes, such as a clone or diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 4fb987ecf85..9522c1f49cd 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -101,7 +101,7 @@ bugs — it is the protection or the side effect that silently does not happen. |:--|:---|:---|:---|:---| | 1 | **The whole security middleware short-circuits** before any gate runs | plugin-security | Get: every CRUD/FLS/tenant/owner gate below skipped in one branch. Lose: every gate under it in this lane at once, down to and including the write-bypass row that widens the effective write scope to `org` (row 7) — this is the single largest behaviour on the page | `registerAuthzMiddleware` | | 1b | **App-authored automation's system context is REFUSED governed writes to the identity-assignment objects** — a flow run's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and an action body's; checked ahead of the middleware's short-circuit, beside the append-only refusal (`assertAppAutomationAppendOnlyWriteAllowed`) | plugin-security | Get: nothing — an insert, update, delete, transfer, restore or purge of `sys_user_position`, `sys_user_permission_set`, `sys_invitation` or `sys_member` from a context carrying `isSystem` and either a `flowRunId` (a `runAs: 'system'` flow's data nodes) or the app-automation elevation mark (`@objectstack/core`; set only by a hook's `runAs: 'system'` derivation, by the action body's execution-context builder and `ObjectRepository.execute`, and on the api of a hook bound through the hook binder, whose inherited system context and `sudo()` it marks), at any depth of their writes, is refused `PERMISSION_DENIED` before the short-circuit skips the ADR-0090 D12 gate and the identity write guard. The platform's own system api (`platformSystemApi`, objectql) takes the mark and `flowRunId` off a platform hook's api, for the audit writer's own ledger rows. On an app-authored hook's api, on the api an action door hands its handler (a host code action handler's included) and on the api `ObjectRepository.execute` hands the action it dispatches (`ctx.api.object(o).execute(name)`), and on every api derived from any of them, it answers what that api's `sudo()` answers, mark kept, so this refusal, and the action body's owner stamp in the next row, hold through it too. Lose: nothing a platform writer held — a system context with neither (the seeders, better-auth and its reconciliation, invitation placement, platform code's `sudo()`, which never sets the mark, and a hook registered in code) passes on to the short-circuit unchanged, reads are not judged, and a `runAs: 'user'` flow or hook carries no `isSystem`, so the D12 gate judges it as the user it acts for | `elevationSource`, `appAuthoredHookApi` | -| 1c | **App-authored automation's system context meets its caller's organization wall** — an action body's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and a flow run's, read by the same predicate as the identity refusal above (`applyAppAutomationOrganizationWall`, plugin-security); checked ahead of the middleware's short-circuit | plugin-security | Get: its reads and writes are judged by the organization wall of the caller it runs for, under every posture and on every object. Such a context that carries a caller (a `userId`, or the guest entry's envelope) is judged by the caller's own Layer 0 (ADR-0095 D1), computed over the caller's own context and permission sets (resolved for the caller where the context does not carry them, as a flow run's does not). An insert with no active organization on a walled tenant object is refused (`403 PERMISSION_DENIED`); for every such caller, one with an active organization included, a write whose own data names an organization outside its scope or empties a row's organization is refused (`403 PERMISSION_DENIED`); on a federated object its reads are those of the caller's organization scope and a by-id write of a row outside it answers `404 RECORD_NOT_FOUND`, the check read inside the transaction the write carries. A caller the wall denies — no active organization under `isolated`, an empty membership set under `group`, no membership under `single` — reads nothing of a tenant-scoped object, and its delete and purge are answered by that read rule as its plain door answers them (ADR-0123 D2): a predicate delete matches nothing and a by-id delete answers `404 RECORD_NOT_FOUND`. Every other write is refused `PERMISSION_DENIED` (403), naming what is missing (ADR-0123 D4). A system flow run whose own user is its caller carries that user's membership set and posture rung from run setup (a decided segment, a run that began for no caller and a child run of either carry neither); the wall asks Layer 0 alone and resolves what a context lacks once per run. Lose: nothing the caller held — a caller with an active organization keeps its organization's reach (the union of its memberships under `group`); objects outside tenancy, objects with no organization column and a platform operator crossing the wall on a posture-permitting object answer as the caller's plain door answers them. An elevation that carries no caller (a scheduled run, a record-change run fired by a write that carried no user), a system flow that began for no caller in every segment (after an approval decision too, `runCallerOf`, core) and a run a write of such a segment starts, and every platform system context are unchanged | `elevationSource` | +| 1c | **App-authored automation's system context meets its caller's organization wall** — an action body's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and a flow run's, read by the same predicate as the identity refusal above (`applyAppAutomationOrganizationWall`, plugin-security); checked ahead of the middleware's short-circuit | plugin-security | Get: its reads and writes are judged by the organization wall of the caller it runs for, under every posture and on every object. Such a context that carries a caller (a `userId`, or the guest entry's envelope) is judged by the caller's own Layer 0 (ADR-0095 D1), computed over the caller's own context and permission sets (resolved for the caller where the context does not carry them, as a flow run's does not). An insert with no active organization on a walled tenant object is refused (`403 PERMISSION_DENIED`); for every such caller, one with an active organization included, a write whose own data names an organization outside its scope or empties a row's organization is refused (`403 PERMISSION_DENIED`); a write is judged again on the rows its before-hooks leave, by the same rule, as the plain door judges it; the option bag's `tenantId` / `tenantIds` never widen it past the caller's wall — a write (an insert included) whose bag names an organization outside it, or clears the key, is refused (`403 PERMISSION_DENIED`), and a read whose bag does is answered by the read rule, the caller's wall composed onto its predicate; the bag its before-hooks leave, set, replaced or handed back, is judged by the same rule where the engine builds the driver's options (`OperationContext.driverTenantScopeCheck`): a bag naming only organizations inside the scope the engine itself projects for the caller (its active organization, or under `group` its memberships) is not judged further, and a bag beyond that scope, or one that clears a key, is judged against the caller's wall where a verdict was worked out for the operation and against its active organization alone where none was; on a federated object its reads are those of the caller's organization scope and a by-id write of a row outside it answers `404 RECORD_NOT_FOUND`, the check read inside the transaction the write carries. A caller the wall denies — no active organization under `isolated`, an empty membership set under `group`, no membership under `single` — reads nothing of a tenant-scoped object, and its delete and purge are answered by that read rule as its plain door answers them (ADR-0123 D2): a predicate delete matches nothing and a by-id delete answers `404 RECORD_NOT_FOUND`. Every other write is refused `PERMISSION_DENIED` (403), naming what is missing (ADR-0123 D4). A system flow run whose own user is its caller carries that user's membership set and posture rung from run setup (a decided segment, a run that began for no caller and a child run of either carry neither); the wall asks Layer 0 alone and resolves what a context lacks once per run. Lose: nothing the caller held — a caller with an active organization keeps its organization's reach (the union of its memberships under `group`); objects outside tenancy, objects with no organization column and a platform operator crossing the wall on a posture-permitting object answer as the caller's plain door answers them. An elevation that carries no caller (a scheduled run, a record-change run fired by a write that carried no user), a system flow that began for no caller in every segment (after an approval decision too, `runCallerOf`, core) and a run a write of such a segment starts, and every platform system context are unchanged | `elevationSource` | | 2 | **`owner_id` is not auto-stamped on INSERT** (the step 3.5 anchor guard is inside the block row 1 skips) — except an action body's insert | plugin-security | Lose: the row lands `owner_id = NULL`, so the default `owner_only_writes` policy hides it **from its own creator**. Get: nothing — this is a gap, not a capability. Except an action body's: an insert from a context carrying `isSystem` and the `'action'` app-automation elevation mark, with no `flowRunId`, has every EMPTY `owner_id` stamped with the envelope's own `userId` ahead of the short-circuit, by the same stamp step 3.5 applies (nothing for the guest; an owner the body sets is kept; an `owner_id` supplied empty beside a supplied queue parks the row). Like a direct create, such an insert is the invoker's own record, so assignment rules (ADR-0142 D5), which route only a row whose owner and queue are both still empty, route neither; a body has no spelling today that asks a rule to route its row. The mark is set on every handler an action door dispatches (a host code action handler included) and by `ObjectRepository.execute`. A flow run, a hook's `runAs: 'system'`, the seeders and every other system context still land the owner they write, or none, and an unowned, queue-less one is still routed | the step 3.5 guard block and the short-circuit that skips it are both inside `registerAuthzMiddleware`; the action-body exception is `isActionBodyElevation` | | 3 | Row-level read filter resolves to "no filter" | plugin-security | Get: unscoped reads. Lose: row-level scoping entirely | `getReadFilter` | | 4 | Field-level security returns **all** fields | plugin-security | Get: every column readable (`getReadableFields`) and writable (`getWritableFields`), and every field a disabled package withholds named to it (`getMetadataReadableWithheldFields`, so the served object's `_withheldFields` keeps every entry). Lose: field masking | `resolveProjectionFieldMask`, `computeMetadataReadableWithheldFields` | @@ -158,6 +158,8 @@ bugs — it is the protection or the side effect that silently does not happen. | 29d | The recycle bin's tenant wall does not apply: `restore`, `purge` and `empty` read and remove **every organization's** entries | objectql | Get: the bin's own doors reach any entry, as the system reaches every wall. Every caller that is not system is held to the Layer-0 verdict: one the wall denies (a signed-in caller with no active organization under a walled posture) sees no entry, so `restore` answers `null`, `purge` `false` and `empty` `0`, and the removal is scoped by the verdict the security layer recorded on the dispatch when it recorded one (#30237) | `recycleBinWallDenies` | | 29e | A restore of an entry someone else deleted asks **no recycle-bin grant** | objectql | Get: the system restores any entry. Every caller that is not system restores only the entries whose `deleted_by` is its own `userId` unless its effective permissions grant `manageRecycleBin` on the entry's object; otherwise `403 PERMISSION_DENIED`, and the same refusal when no permission resolver is registered or it throws (#30237, ADR-0148 D5) | `assertCallerMayRestoreEntry` | | 29f | Listing the recycle bin of an object asks **no recycle-bin grant** | objectql | Get: the system lists every entry of any object the bin takes. Every caller that is not system lists an object's entries only when its effective permissions grant `manageRecycleBin` on the object; otherwise `403 PERMISSION_DENIED`, and the same refusal when no permission resolver is registered or it throws (#30237, ADR-0148 D5) | `assertCallerManagesRecycleBin` | +| 29g | A validation rule message's `{{ }}` holes show **every field the system may read**, only when the write names no person | objectql | Get: a user-less system write (a schedule, a platform sweep) fills a refused write's message holes with the security service's system answer, every field less credential and `internal` ones; that sentence reaches the server log alone. An elevated write that names a person (`userId`: a `runAs: 'system'` flow they started, whose refusal reaches them as `innerRefusal`; an action body; the approvals mirror) is not read as the system: both field projections are asked for that person, with the permission sets the context carries or their own grants (`resolveUserAuthzGrants`), and every hole renders empty when those grants cannot be read (#37909) | `readerContext` | +| 29h | **The closed-state lock does not bind** — a write to a record in one of its object's `closedStates`, or to a line of one, is not judged | objectql | Get: a system context updates, deletes and restores a closed record and its `master_detail` lines, and a cascade that reaches one runs; the engine's own derived writes (the roll-up recompute, the approval status mirror) land on a closed record. Every caller that is not system, and a write with no context at all, is refused `409 RECORD_LOCKED` (ADR-0162 D5) | `boundByClosedStates` | | 30 | **Bulk data event `organizationId` OMITTED** — the batch is published "not asserted" | plugin-security | Get: nothing — the `data.records.*` event still publishes. Lose: the per-organization attribution: this exit is taken before the security middleware composes any tenant wall, so it records no Layer 0 verdict on the operation (`OperationContext.tenantLayer0Verdict`, #15813), and the engine's bulk producer — which reads that recorded verdict and nothing else — omits the key rather than filling it from the caller's `tenantId`; a tenant-scoped consumer then does not deliver the event inside an organization wall (#15225) | `registerAuthzMiddleware` | | 30b | **The import doors admit a control opt-out** — `runAutomations: false` and `treatAsHistorical: true` on `POST /data/:object/import` and `/import/jobs` | rest | Get: an import whose rows are written with `skipAutomations` (no metadata-bound hook, no record-change trigger: an app's approvals and record freezes among them) or with `skipStateMachine` and `preserveAudit`. Every other caller, every signed-in user and administrator included, is refused `403 PERMISSION_DENIED` before the body is parsed, so nothing is written and no job is created. Inbound HTTP never carries the flag, so this is an in-process caller's door. Note: the flag still suppresses none of those controls by itself (see below); it only admits the opt-outs that do | `importControlOptOutRefusal` | | 30c | **The import undo keeps the control skips** — `POST /data/import/jobs/:jobId/undo` | rest | Get: an undo whose deletes and restores are written with `skipAutomations` and `skipStateMachine`, so no metadata-bound hook, record-change trigger or `state_machine` rule refuses a reversal. Every other caller, every signed-in user and administrator included, undoes under those controls: a reversal one of them refuses is reported per row in the undo answer's `failures` and kept in the job's undo log, and the job is stamped reverted only once every row is. A historical job's `preserveAudit` belongs to the job, not the caller, and rides every undo. Inbound HTTP never carries the flag, so this is an in-process caller's door | `importUndoWriteContext` | @@ -190,6 +192,7 @@ One of the largest consumers of the flag; | 44 | Attachment access hooks return early (insert + update + delete, the referenced-file check on insert + update, and the read AST) | service-storage | Lose: attachment visibility scoping | `installAttachmentAccessHooks`, `installAttachmentFileReferenceGate`, `installAttachmentReadVisibility` | | 45 | Comment access hooks return early (insert + update + delete, and the read AST), and so do the activity and audit-log read gates (their read AST), the activity field redaction and the audit-log field redaction (the rows a read serves), the activity summary's message code (the rows a read serves), and the query guard over both objects' value-bearing columns (the read AST) | plugin-audit | Get: the whole activity row and the whole `sys_audit_log` row, its before/after snapshots included, and the activity row's stored summary code (`metadata.summary_message`), on `find` / `findOne` — the audit writer, each read gate's bounded probe and the activity backfill — and a filter, sort or grouping by those columns. Lose: comment visibility scoping, the narrowing of `sys_activity` and of `sys_audit_log` to rows whose parent record the caller can read, the redaction of a parent field's value from an activity row's text and recorded change and from a ledger row's before/after snapshots, the withholding of an activity row recording an update whose every changed field the reader is withheld, of a fired milestone row whose watched fields it is not all served, and of an unstamped row (on `count` and `aggregate` too, so a total agrees with the rows), the removal of that summary code from the activity row's `metadata` (its params are field values), and the refusal of a query over those columns for a reader withheld a field of the objects it can reach, and the withholding of those columns from such a reader's server-chosen search set (#34700) | `installCommentAccessHooks`, `installCommentReadVisibility`, `installActivityReadVisibility`, `installAuditLogReadVisibility`, `installActivityFieldRedaction`, `installAuditLogFieldRedaction`, `installActivitySummaryLocale`, `installParentFieldQueryGuard`, `withheldSearchColumns` | | 46 | Knowledge search returns hits unfiltered, and searches every source; a knowledge source is saved without its author being judged | service-knowledge, metadata-core, runtime | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched. Lose at the `/meta` and MCP save doors: the same admission asked for the author before a `knowledge_source` is saved (ADR-0161 K4), so the engine's own write saves a source over an object or a field no author was judged for. Lose at the package duplicate door: the same admission asked for the caller, for each knowledge source the copy would save. Lose at the package move-in door: the same admission asked for the caller, for each selected knowledge source the move saves again under the package | `applyPermissionFilter`, `admitSources`, `searchByKey`, `admitAuthoredSource`, `authoredKnowledgeSourceRefusal`, `refuseDuplicatedKnowledgeSources`, `handlePackagesRequest` | +| 46a | Knowledge search under the system identity is not ordered for the asker: a source's `affinity` entries move nothing | service-knowledge | Get: every hit in the order its store answered, and no read of a user or business unit. Lose: nothing a user held. The system identity is no person, so it has no unit to order by; every other caller's user id and unit chain are read as that caller may read them | `resolveAffinityFacts` | | 47 | The inbound-mail read gates return early (the read AST) | service-mailbox | Get: every `sys_mail_message` and `sys_mail_association` row on `find` / `findOne` — the ingest writer and each gate's own pre-scan, which read the association and mailbox rows a decision needs. Lose: the narrowing of a message to callers who can read a record it is associated with or who own its mailbox (so the unassociated pool is restricted), and of an association to callers who can read the record it names (on `count` and `aggregate` too, so a total agrees with the rows) | `gateMiddleware` | | 47b | The inbound-mail ingest seam: `ingest` admits the system context ALONE, and `rematch` admits it without the organization, owner or `manage_mailboxes` check | service-mailbox | Get: a mail source hands a mailbox its messages, and server code re-matches any mailbox. Lose: nothing a user held — every other caller of `ingest` is refused (`PERMISSION_DENIED`), because an ingested message is shown on every record its correspondents' addresses match and a user who could hand the seam a message could write one in a correspondent's name; every other caller of `rematch` must be in the mailbox's organization and own the mailbox or hold `manage_mailboxes` | `ingest`, `authorizeRematch` | | 47c | The inbound-mail IMAP sync: `syncMailbox` and `syncAll` admit the system context ALONE | service-mailbox | Get: the sync job reads every mailbox row (its organization, address and IMAP cursor), writes the cursor back, and hands each fetched message to `ingest` under the system context. Lose: nothing a user held — every other caller is refused (`PERMISSION_DENIED`), because a sync stores a mailbox's mail and moves its cursor | `syncMailbox`, `syncAll` | @@ -213,7 +216,7 @@ One of the largest consumers of the flag; | 54 | Package REST route capability gate bypassed | rest | Get: a marketplace publish over REST (`POST /packages/publish`, the one route the REST registrar mounts since #14503) without `manage_metadata`; the package read cohort (`studio.access` / `setup.access`) is enforced by the dispatcher `/packages` domain's own read gate, where the reads are served | `refusePackageRequest` | | 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability; and a write to a package that holds a knowledge source (the twelve doors that write an existing package) without `manage_knowledge_sources` beside it (ADR-0161 K4); and, on the move-in door, a selected `datasource` or `knowledge_source` moved without the capability its `/meta` write asks (`manage_platform_settings`, `manage_knowledge_sources`) | `requireManageMetadata`, `requireReadCapability`, `refuseKnowledgeSourcePackageWrite`, `handlePackagesRequest` | | 56 | Activation write / authoring refusals do not fire | runtime | Get: activation artifacts writable and authorable without the activation-authoring capability | `refuseUngrantedActivationWrite`, `refuseUngrantedActivationAuthoring` | -| 55b | Walled environment-metadata refusal does not fire | metadata-core, rest, runtime | Get: under `isolated` / `group`, a write of the environment's metadata, of any type, at the `/meta` write doors (save, reset, publish, rollback) and `POST /meta/_migrate-stored` on both transports, at every `/packages` write door (create, the manifest `PATCH`, enable, disable, publish, `publish-drafts`, `discard-drafts`, `revert`, `rollback`, `commits/:commitId/revert`, `duplicate`, `adopt-orphans`, delete), at the `/automation` definition writes (create, update, delete, clone), at the permission-set clone door, at the import of a remote table as an object (the REST import route and the MCP `import_object` tool), at the open MCP server's draft save and discard (`save_metadata_draft`, `delete_metadata_draft`), and at the refresh of a federated datasource's cached catalog. Every other caller below the platform-operator rung is refused `403` there (ADR-0131 D3, D12 items 7–8, D11), because one organization's write would change what every organization resolves. The seeders, the package door and migrations write the environment's metadata this way. Under `single` the refusal is inert for every caller | `walledCatalogWriteVerdict`, `walledCatalogRefusal`, `refuseWalledCatalogPackageWrite`, `refuseWalledFlowDefinitionWrite`, `registerExternalDatasourceRoutes`, `federationService`, `openWriter` | +| 55b | Walled environment-metadata refusal does not fire | metadata-core, rest, runtime | Get: under `isolated` / `group`, a write of the environment's metadata, of any type, at the `/meta` write doors (save, reset, publish, rollback) and `POST /meta/_migrate-stored` on both transports, at every `/packages` write door (create, the manifest `PATCH`, enable, disable, publish, `publish-drafts`, `discard-drafts`, `revert`, `rollback`, `commits/:commitId/revert`, `duplicate`, `move-in`, delete), at the `/automation` definition writes (create, update, delete, clone), at the permission-set clone door, at the import of a remote table as an object (the REST import route and the MCP `import_object` tool), at the open MCP server's draft save and discard (`save_metadata_draft`, `delete_metadata_draft`), and at the refresh of a federated datasource's cached catalog. Every other caller below the platform-operator rung is refused `403` there (ADR-0131 D3, D12 items 7–8, D11), because one organization's write would change what every organization resolves. The seeders, the package door and migrations write the environment's metadata this way. Under `single` the refusal is inert for every caller | `walledCatalogWriteVerdict`, `walledCatalogRefusal`, `refuseWalledCatalogPackageWrite`, `refuseWalledFlowDefinitionWrite`, `registerExternalDatasourceRoutes`, `federationService`, `openWriter` | | 57 | Automation run-state read, flow-authoring write, the paused-run caller gate (screen read and resume), the two operator run-lifecycle writes, and the elevated self-triggered start, the AI-service-account elevated start and the start-record check at every door that starts a flow by name all pass | runtime | Get: run state, flow writes, a paused run's screen and its resume with no grant and without being the run's starter — and cancelling or restoring a suspension without the platform-operator rung. The screen read and the resume ask one predicate, so this is one bypass for both. The lifecycle bypass is the in-process owner's door: plugin-approvals' revise-window recall (ADR-0044) cancels on behalf of a decision it already authorized and recorded. And starting a flow declared `runAs: 'system'` whose type is self-triggered (`autolaunched`, `record_change`, `schedule`) through any door that starts a flow by name — the trigger route, an action of `type: 'flow'` (REST `/actions` and the MCP `run_action` bridge) and a declared endpoint of `type: 'flow'` — which every other caller, the guest principal included, is refused `403 PERMISSION_DENIED` (the maintainer's rulings, letters B and A) — and starting, through the same doors, a flow whose `requiredPermissions` the caller does not hold (ruling record 6377848497, letter A) — and starting, through the same doors, a flow declared `runAs: 'system'` as an AI service account (an agent acting for itself, with no `onBehalfOf`) where the action's `ai.exposed: true` opt-in is not in hand, which that account is refused `403 PERMISSION_DENIED` (ADR-0151 Non-goals, ruling record 6812617393, letter C; a trigger route and a declared endpoint carry no opt-in, so there it is always refused, and the refusal names the action door that admits it). And starting, through the same doors, a flow on a record key the caller's own scope does not deliver, which every other caller is refused with the action door's `404 RECORD_NOT_FOUND` before the run exists (and `400 VALIDATION_FAILED` for a key that is not one id, or for an elevated start that names no object). The three doors ask one check, so this is one bypass for all of them, and it is the in-process caller's, such as a job: inbound HTTP never carries the flag | `mayReadRunState`, `refuseUngrantedFlowWrite`, `isRunStarterOrRunStateReader`, `refuseUngrantedRunLifecycleWrite`, `flowStartRefusal`, `refuseUnreadableFlowStartRecords` | | 57b | Connector credential door's capability and posture gates pass | runtime | Get: listing, setting and clearing the environment's stored connector credentials (`/automation/connectors/credential-refs`) without `manage_metadata`, and under the `group` / `isolated` postures, where the door refuses every other caller `403 PERMISSION_DENIED` naming the posture, the platform operator included, because the store is environment-level. The bypass is the in-process caller's: inbound HTTP never carries the flag. Get nothing more about the value: no answer of this door carries it | `refuseUngrantedConnectorCredentialAccess`, `refuseWalledConnectorCredentialAccess` | | 57c | Connector connection door's capability gate passes | runtime | Get: reading, beginning, completing (the OAuth callback) and revoking an organization's connection of an `oauth2` `authorization_code` connector instance (`/automation/connectors/:name/connection`, `/automation/connectors/oauth/callback`, ADR-0143 D5) without `manage_metadata`. No posture refuses it: a connection belongs to its organization. The bypass is the in-process caller's: inbound HTTP never carries the flag. Get nothing more: no answer of this door carries a token, and the callback's `state` is still bound to the user and organization that began the connect | `refuseUngrantedConnectorConnectionAccess` | @@ -549,6 +552,7 @@ and CI refuses one that differs from what the tree produces. | `packages/metadata-core/src/meta-write-capability.ts#metaWriteCapabilityVerdict` | 1 | 51 | | `packages/metadata-core/src/meta-write-capability.ts#walledCatalogWriteVerdict` | 1 | 55b | | `packages/metadata-core/src/object-schema-fls.ts#isObjectSchemaMaskExempt` | 1 | 8 | +| `packages/objectql/src/closed-state-lock.ts#boundByClosedStates` | 1 | 29h | | `packages/objectql/src/credential-evaluation-guard.ts#rejectCredentialEvaluation` | 1 | 18c | | `packages/objectql/src/engine-cascade-planning.ts#dependentCountIsDisclosable` | 1 | 28 | | `packages/objectql/src/engine-delete-cascade.ts#recordReferenceCheckElevation` | 1 | 29 | @@ -560,6 +564,7 @@ and CI refuses one that differs from what the tree produces. | `packages/objectql/src/engine-referential-integrity.ts#masterDetailHeadersCallerReads` | 1 | 29c | | `packages/objectql/src/engine-referential-integrity.ts#referencesCheckedBeforeRules` | 1 | 23 | | `packages/objectql/src/engine-referential-integrity.ts#storedReferencesCallerReads` | 1 | 23 | +| `packages/objectql/src/engine-rule-message-rendering.ts#readerContext` | 1 | 29g | | `packages/objectql/src/engine-scoped-context.ts#appAuthoredHookApi` | 1 | 1b | | `packages/objectql/src/engine-secret-internal-fields.ts#encryptSecretFields` | 1 | 23e | | `packages/objectql/src/engine-secret-internal-fields.ts#stripSearchCompanionFromRead` | 1 | 27 | @@ -707,10 +712,11 @@ and CI refuses one that differs from what the tree produces. | `packages/runtime/src/sandbox/body-doors.ts#callerScopeOf` | 1 | 65b | | `packages/runtime/src/sandbox/body-runner.ts#executionContextFromHook` | 1 | 65 | | `packages/services/service-automation/src/runtime-identity.ts#stampSystemInsertOwner` | 1 | 60 | -| `packages/services/service-knowledge/src/knowledge-service.ts#admitAuthoredSource` | 1 | 46 | -| `packages/services/service-knowledge/src/knowledge-service.ts#admitSources` | 1 | 46 | -| `packages/services/service-knowledge/src/knowledge-service.ts#applyPermissionFilter` | 1 | 46 | -| `packages/services/service-knowledge/src/knowledge-service.ts#searchByKey` | 1 | 46 | +| `packages/services/service-knowledge/src/knowledge-affinity.ts#resolveAffinityFacts` | 1 | 46a | +| `packages/services/service-knowledge/src/knowledge-service-admission.ts#admitAuthoredSource` | 1 | 46 | +| `packages/services/service-knowledge/src/knowledge-service-admission.ts#admitSources` | 1 | 46 | +| `packages/services/service-knowledge/src/knowledge-service-admission.ts#applyPermissionFilter` | 1 | 46 | +| `packages/services/service-knowledge/src/knowledge-service-search.ts#searchByKey` | 1 | 46 | | `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#authorizeRematch` | 1 | 47b | | `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#ingest` | 1 | 47b | | `packages/services/service-mailbox/src/mail-read-visibility.ts#gateMiddleware` | 1 | 47 | diff --git a/content/docs/protocol/kernel/config-resolution.mdx b/content/docs/protocol/kernel/config-resolution.mdx index 8afaa31275b..67fa1709566 100644 --- a/content/docs/protocol/kernel/config-resolution.mdx +++ b/content/docs/protocol/kernel/config-resolution.mdx @@ -76,9 +76,17 @@ configuration when nothing is stored (plugin options, a host declaration) states that value with `registerDeclaredDefault(namespace, key, provider)`; otherwise the manifest `default` answers. Either way the answer reports `source: 'default'`: nothing is stored, and a clear returns to it. The auth -plugin states `email_password_enabled`, `signup_enabled` and -`require_email_verification` this way, so Setup → Authentication shows what -the deployment runs, not a console default it never applies. +plugin states every `auth` key its runtime takes from the deployment's own +configuration this way (the sign-in switches, password, MFA, API-key, +session, network, lockout, membership and audience settings), so +Setup → Authentication shows what the deployment runs, not a console default +it never applies. It leaves three groups on the manifest default. The +rate-limit pair: with nothing stored the auth library's own per-path rules +run, or a declared `rateLimit` global pair, and neither is the per-endpoint +cap the setting writes. The Google sign-in keys: the toggle's runtime default +is the manifest's, and a declared credential outranks a saved one, so it is +not what a clear returns to. And the API-key policy start date, which the +first boot records into the store. Two rules follow from the walk, and both are enforced in `SettingsService`: diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index fe293cc7d3a..b5fd954319a 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -181,6 +181,34 @@ that name (ADR-0161 K4): `VALIDATION_ERROR` (400), naming them. The adapter is placed where it is used, so a source registered before its store started finds it. +**How a source is searched: `source.retrieval.mode`** (ADR-0161, the dated +note of 2026-11-30 under K8). `'vector'` ranks by meaning alone, `'keyword'` by +the question's words alone (the embedder is never called), `'hybrid'` runs +both and merges them; omitted (or `retrieval: {}`), the adapter's default +(`capabilities.retrieval.default`, `'hybrid'` on `turso` and `pgvector`). +That is the effective mode, handed to the adapter on every search and logged +at `debug` with where it came from; it is not in what a search answers the +caller, and an administrator reads it in the source's `index_status`. A +source is never searched in a mode other than the one it declares, so a mode +its adapter does not list (an adapter that reports none, such as `memory`, +lists none) is refused at four points: + +1. its save (Studio, `/meta`, an MCP draft): `VALIDATION_ERROR` (400), + listing the modes the store runs; +2. its registration in code (`registerSource`), when its adapter is already + registered: the same refusal. A store registers in its own `start()`, + after a source registered at `init()`, so "not registered yet" is no + verdict. A published item (a package install, the stack's + `knowledgeSources`) meets no save and is not refused by the loader: it is + registered and indexed, and the next two points hold it; +3. once after boot, at `error`, naming the source and the modes; +4. every search: the source is listed in `refused`, `SERVICE_UNAVAILABLE` + (503), as a source whose adapter is not mounted is. + +The mode is read by search alone: it enters neither the index fingerprint nor +the recipe hash, so changing it rebuilds nothing, and a refused source still +builds and syncs its index. + **What mounts the service.** A stack that ships a `knowledge_source` — any item in its `knowledgeSources`, at the top level or in a package — is served the knowledge service and the deployment's store, exactly as @@ -188,6 +216,18 @@ the knowledge service and the deployment's store, exactly as in `PLATFORM_CAPABILITY_PROVIDERS`). A host that mounts `KnowledgeServicePlugin` itself keeps its own, and the runtime adds no store. +**Mounted is not enabled** (ADR-0161 K8, the dated note on item 12). A service +the runtime mounted (`runtimeComposed` on the plugin) reads once, at +`kernel:bootstrapped`, whether an embedder is available and whether the +deployment's store is mounted. Without both, every source is held, whichever +store it names: loaded and listed, never built, synced, reconciled or searched; +no `search_knowledge` definition is handed out; `search`, `rebuildSource` and +`reindexSource` answer `503 SERVICE_UNAVAILABLE` naming the missing half; a +removed source keeps its index, and no store is called. The boot logs one line, +`info` when only a shipped source mounted the service and nothing was saved, +`warn` otherwise, and never refuses to start. A change takes effect at the next +restart. A host-mounted service is not read this way and serves from the start. + #### How a source is loaded The knowledge service reads the published `knowledge_source` items when it @@ -225,7 +265,7 @@ and the MCP draft door: imply it. Over MCP it is the human's own grant that is read, never the agent's. The package doors ask it too: every write to an existing package that holds a knowledge source (enable, disable, publish, publish-drafts, - discard-drafts, the commit revert, rollback, revert, adopt-orphans, + discard-drafts, the commit revert, rollback, revert, move-in, duplicate, the manifest update and delete) needs the capability, and is refused `403` naming it otherwise. A package that holds none is written as before. Two doors are not asked. Installing a package is one: a packaged @@ -240,7 +280,8 @@ and the MCP draft door: serve for `search`, a system object without `enable.aiReadable`, or a field the author may not query refuses the save `403`, naming the object or the field; an `adapter` naming no mounted store refuses it `400`, naming the - source, the adapter and the mounted ones. The fields judged are the ones the source serves (`content`, + source, the adapter and the mounted ones, and so does a + `source.retrieval.mode` the store does not run, listing the ones it does. The fields judged are the ones the source serves (`content`, `metadataFields`, the title field) and the ones its `where` reads. A verdict that cannot be reached, or a knowledge service that is registered and cannot be resolved, refuses `503`; nothing is written. @@ -252,9 +293,24 @@ ships, so it does not mount the service either. So on such a deployment every door above refuses an author's save `503 SERVICE_UNAVAILABLE`, and a duplicate that would copy a source is refused the same way; nothing is written. The refusal names the fix: add `requires: ['knowledge']` to the stack, restart, -then save the source. The engine's own writes (a package install, a seed, a -migration) are not refused, and a knowledge service a host mounts itself -answers for its own sources. +save an embedder provider (the service the token mounts is enabled only with +one), restart again, then save the source. The engine's own writes (a package +install, a seed, a migration) are not refused, and a knowledge service a host +mounts itself answers for its own sources. + +**A service that is not enabled saves no source either** (ADR-0161 K8, the +dated note on item 12). While a runtime-mounted service is held, its own +verdict (`admitAuthoredSource`) refuses an author's save `503 +SERVICE_UNAVAILABLE` at every door that saves one — the doors above and +`POST /packages/:id/move-in` of a package-less source — ahead of every gate, +and nothing is written: the source would be held, never built, synced or +searched. The refusal names the half that is missing: with no embedder, "save +an embedder provider, restart, then save"; where the deployment's store is not +mounted, that the boot's log names the reason, and "mount the deployment's +knowledge store, restart, then save"; both when both are missing. A duplicate +is not refused for it, since its copies are held like every other source, and +the engine's own writes are admitted, so a shipped source still installs and +is held. #### One name, one source @@ -456,7 +512,10 @@ and [3.5 The split](#35-the-split). ```ts interface IKnowledgeAdapter { readonly id: string; - readonly capabilities?: { chunks?: boolean }; // takes the service's passages + readonly capabilities?: { + chunks?: boolean; // takes the service's passages + retrieval?: { modes: readonly ('vector' | 'keyword' | 'hybrid')[]; default: 'vector' | 'keyword' | 'hybrid' }; + }; // the retrieval modes it runs, and its default readonly embedding?: { // what its embedder is maxInputTokens?: number; // longest input it accepts model?: string; dimensions?: number; variant?: string; // what its vectors are @@ -496,6 +555,11 @@ caller's organizations; an adapter that reads it ranks only those organizations' documents, filtering before it ranks — see [Organization scope](#organization-scope). `AdapterSearchOptions.scope` holds a search to chosen records the same way — see [Record scope](#record-scope). +`capabilities.retrieval` reports the retrieval modes an adapter runs +(`vector`, `keyword`, `hybrid`) and the one it runs by default; it is a +report, not configuration. `AdapterSearchOptions.retrieval` carries the mode +a search runs, a per-request parameter like `topK`, and only ever a mode the +adapter lists. `listDocuments` lists the documents the adapter holds for a source, a page of at most `limit` entries at a time, each with the `docHash` it was stored with; `nextCursor` is absent once the @@ -546,7 +610,8 @@ one that does not keeps receiving whole documents, and a `whole` document over the embedder's budget is removed and reported; and the index fingerprint of §3.6 — that every call carries one, that a write or a search under another is refused by code, a complete reindex as one build, and, for an adapter that -keeps generations, the switch at the end of a build. `implements` declares the optional members, and the suite +keeps generations, the switch at the end of a build; and, for an adapter that declares the optional +`keywordLeg`, an unspaced Chinese question that ranks the passage holding its figure and words. `implements` declares the optional members, and the suite checks the declaration against the adapter. `./testing` is a test-only, ESM-only entry that imports `vitest`; nothing in the runtime entry reaches it. `knowledge-memory` runs it as the reference implementation; `knowledge-pgvector` @@ -564,7 +629,8 @@ them. The object source's `split` key chooses how: split: { strategy: 'recursive', // 'whole' | 'recursive' | 'markdown' maxChars: 600, // optional: longest passage, in characters - minChars: 200, // optional: merge adjacent pieces shorter than this (default 200) + minChars: 200, // optional: merge adjacent pieces shorter than this (default 200); + // under 'markdown', only in a section that does not fit } ``` @@ -572,7 +638,7 @@ split: { |----------|-------------| | `whole` | One passage per document. | | `recursive` (the default) | At blank lines, then line breaks, then sentence ends, then semicolons, then characters — each next level only for a piece still too long. A Markdown table or list item is one unit while it fits; a table that does not fit is cut between rows, each piece repeating the header row. Adjacent pieces are merged while the merged piece is shorter than `minChars`; a short title block leads the text after it. | -| `markdown` | One section per heading (a `#` inside a code fence is no heading), each cut as `recursive` cuts. Every passage begins with its heading path (`Policy > Transport > Air`), which counts toward its length and is embedded with it, and carries it as `headingPath`. A heading with no text of its own joins the next passage. | +| `markdown` | One section per heading (a `#` inside a code fence is no heading); the text before the first heading, and a heading's text before its first sub-heading, are sections too. Every passage begins with its heading path (`Policy > Transport > Air`), which counts toward its length and is embedded with it, and carries it as `headingPath`. A section that fits — its text together with the heading path it is given (the whole path, or the innermost heading when the whole path is too long), within the effective `maxChars` and the token budget — is **one passage, whatever `minChars` is**; only a section that does not fit is cut as `recursive` cuts, its pieces merged up to `minChars`. A heading with no text of its own is named by the path of the section after it when it is that section's ancestor, and is a passage of its own otherwise. | **Sentence ends, for Chinese and English text.** `。?!` end a sentence wherever they stand. `. ? !` end one only before whitespace or the end of the @@ -582,15 +648,25 @@ closing quote or bracket: 「他说:“好。”然后」 stays one sentence. clause wherever it stands, `;` only before whitespace. **How long a passage may be.** `maxChars` is the source's `split.maxChars`, -else the settings page's **Knowledge → Target chunk size** +else the settings page's **Knowledge → Longest passage** (`knowledge.chunk_target`), else 800. And when the adapter reports its embedder's `maxInputTokens`, every passage's token estimate (the shared `estimateTokens` from `@objectstack/spec/shared`) also stays within **80%** of that limit. A passage keeps both bounds, so the effective length is the smaller one; with no limit known, only `maxChars` applies. A `minChars` above -the effective `maxChars` reads as `maxChars`. The splitter never overlaps +the effective `maxChars` reads as `maxChars`; under `markdown` it merges only +the pieces of a section that does not fit, so `minChars: 0` still leaves a +fitting section whole. The splitter never overlaps passages. +**One passage per unit.** Under `markdown`, text written with one heading +per unit (an article, a numbered section, a question with its answer) gives +one passage per unit that fits, and no passage ever holds two units; it +needs no `minChars` setting. Text stored in another shape is indexed through a +derived field on the same record that carries that rewrite, optionally under +one top heading that names the document; the recipe is in +[the knowledge guide](/docs/ai/knowledge-rag#one-passage-per-unit). + **`whole` over the limit.** A `whole` document whose estimate is over the 80% budget is **removed from the index and reported, never truncated**: `reindexSource` counts it in `failed` and names it in `failures` @@ -697,10 +773,10 @@ service. It takes the service's passages, embeds them with the kernel's an exact scan. - **Which database.** The `url` option when it is given, else the platform - database when that is PostgreSQL (`OS_DATABASE_URL`). Its own small pool - (`poolMax`, default 4; a connection that takes more than - `connectTimeoutMs`, default 5000, fails); no pooled connection waits on the - embedder. Where organizations + database when that is PostgreSQL (`OS_DATABASE_URL`). Its own small pool, + per process, sized by `poolMax`, else the setting `OS_KNOWLEDGE_POOL_MAX`, + else 20 (a connection that takes more than `connectTimeoutMs`, default 5000, + fails); no pooled connection waits on the embedder. Where organizations have databases of their own, the store is still the ONE database the plugin connects to; organizations are kept apart by its `organization_id` column, which every search filters on before ranking. @@ -727,11 +803,24 @@ an exact scan. scan by cosine distance, so any width works — including a 3072-wide model — and a keyword leg on `to_tsvector('simple', content)` (a GIN expression index), a word of three characters or more as a phrase, a shorter term or - one in Han, kana or Hangul script by `ILIKE`. The organization filter, the + one in Han, kana or Hangul script as a substring (`LIKE` for a term without + a cased letter, `ILIKE` otherwise); a run of Han, kana or Hangul in the + query is cut into overlapping pieces of three characters and of two. The organization filter, the [record scope](#record-scope) and the metadata `filter` (equality per key) are one `WHERE`, run in both legs before either ranks. `queryPrefix` is put before every query before it is embedded, for a model - that embeds questions and passages differently. + that embeds questions and passages differently. It runs all three + retrieval modes, `hybrid` by default: `vector` or `keyword` leaves the + other leg out of the statement and scores a hit `61 / (60 + rank)`, and + `keyword` does not embed the question. + The ranking statement runs in a transaction of its own under + `SET LOCAL statement_timeout` (`statementTimeoutMs`, else + `OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS`, else 10000 ms), so the limit holds no + session state. + A search the database fails is refused by its SQLSTATE, never answered + empty: `TIMEOUT` (504) for a statement stopped or cancelled, + `SERVICE_UNAVAILABLE` (503) when no connection or capacity was available, + `DATABASE_ERROR` (500) for any other database error. - **Re-embedding.** A passage whose text is unchanged (its `chunk_hash`) is not embedded again; its row's metadata is rewritten. - **Rebuilds.** A write or a search under another fingerprint is refused @@ -794,11 +883,16 @@ large source of one organization, through an approximate index. at most `topK`) before the service's re-check: a vector leg by cosine distance (an exact scan, or the approximate index below), and a keyword leg in a contentless FTS5 trigram index beside each passage table (kept in step by triggers), a term of three characters or - more as a quoted phrase, a shorter one by `LIKE`. The organization filter, + more as a quoted phrase, a shorter one by `LIKE`; a run of Han, kana or + Hangul in the query is cut into overlapping pieces of three characters and + of two. The organization filter, the [record scope](#record-scope) and the metadata `filter` (JSON equality per key) are one `WHERE`, run in both legs. Without the approximate index the vector leg reads every row in scope: 1,000 passages of 1,536 dimensions take 8.3 MB and a search about - 5 ms; 10,000 take 82 MB and about 50 ms. + 5 ms; 10,000 take 82 MB and about 50 ms. It runs all three retrieval + modes, `hybrid` by default: `vector` or `keyword` leaves the other leg out + of every statement and scores a hit `61 / (60 + rank)`, and `keyword` does + not embed the question or read the approximate index. - **Approximate index.** A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, makes its approximate index: each passage's vector quantized @@ -970,6 +1064,85 @@ until a complete reindex writes it again. How many hits the scope removed is logged, never returned, and an entry that reaches no source answers the same empty result a source withheld from the caller gives. +### Ordering for the asker + +A source may declare how its hits are ordered for the person asking +(`source.affinity`, ADR-0161's dated note of 2026-11-29 under K1): "the +policies of my own unit first". Each entry compares a field the source lists +in `metadataFields` with a fact the platform resolves about the caller. + +```ts +source: { + kind: 'object', + object: 'policy', + content: ['title', 'body'], + metadataFields: ['business_unit', 'owner'], + affinity: [ + // The caller's own unit first, then each parent unit in order, then the rest. + { field: 'business_unit', caller: 'business_unit', mode: 'nearest' }, + // A policy the caller owns passes up to 3 hits that match nothing. + { field: 'owner', caller: 'user', mode: 'boost', places: 3 }, + ], +}, +``` + +- **The caller facts** are a closed list of two. `user` is the caller's user + id, for a field that points at `sys_user` (a `user` field, or a lookup to + it). `business_unit` is the caller's primary business unit, then each parent + unit up to the root, for a lookup to `sys_business_unit`. A fact is + resolved at most once per search, only when a hit in the list belongs to a + source that declares an entry, and only if such an entry reads it. `user` + is the search's own user id and reads no row. `business_unit` is read by + the one resolver that also answers the MCP door's `get_current_user`: the + caller's user row for the primary unit, then each unit up the chain, every + read as the caller, so a unit the caller may not read ends the chain below + it. No organization row is read. A fault reading the units, other than a + refusal, leaves them out for that search and keeps the `user` fact. A fact + is never a tool argument, a `search` option, or a value a client or a model + supplies. The system identity has no + facts, and a caller with no primary unit has no chain: an entry that finds + no fact matches nothing. +- **`nearest`** parts the source's hits into tiers: the caller's own unit + first, then each parent in order, then every other hit together, a hit with + no value among them. A multi-value lookup takes its nearest element. A + source declares at most one, and its `caller` is `business_unit`. +- **`boost`** takes `places`, a whole number from 1 to 20 (the most hits one + `search_knowledge` answer carries). Inside a tier, with its hits numbered + from 1 in their order, a hit's key is its number minus the `places` of every + `boost` entry it matches; the tier is ordered by key, a tie going to the + larger sum, then to the earlier number. So a hit matching `places: 3` + passes at most three hits of its tier that match nothing. Several entries + add. +- **By position, never by score.** The search runs as it always did up to + its answer: the rounds, the scope check, the permission re-check and the + record-level grouping. The re-order then works on the units that could be + answered (passages, records or `groupBy` groups, each judged on the hit that + stands for it), before the cut to `topK`, so it reads no more passages than + the refill cap already allows. Only one source's units move, among the + places they hold: a hit of another source never moves. A hit keeps the + `score` its store answered, so an answer may no longer be in descending + `score`. Nothing in the answer says a hit moved; the count goes to the + `debug` log. +- **Never an access decision.** Nothing is dropped and nothing is admitted: + a hit outside the caller's unit is ordered later. Narrowing a search is the + [record scope](#record-scope); who may read a record is sharing, so there is + no `filter` mode. An entry is judged on the values the index stores, like a + scope term, and a document indexed before its source listed the field + matches nothing until a complete reindex writes it again. +- **No rebuild.** `affinity` enters neither the index fingerprint nor the + recipe hash. Listing a new field in `metadataFields` for it does change the + recipe hash, as it always did. +- **Refused when it is written**, each with a sentence that names the fix: a + `field` not listed in `metadataFields`, a `mode` other than `boost` and + `nearest` (`filter` is answered that narrowing is the search scope and + visibility is sharing), a caller fact outside the two, a second `nearest`, + `nearest` with `caller: 'user'`, `places` missing on a `boost`, present on a + `nearest`, or not a whole number from 1 to 20. Saving a source also refuses + a `field` that does not point at the object its `caller` names. A unit + read that fails for a reason other than a refusal leaves the units out of + that search, logged once at `warn`; its `business_unit` entries then match + nothing, and its `user` entries still apply. + ### Source admission: exposure and field-level rules A passage is built at index time, under a system context, from every @@ -1267,7 +1440,9 @@ handled at the source rather than after the fact For every object a source projects, the plugin registers an ADR-0057 **reap guard** with the lifecycle service. The sweep hands the guard the candidate rows before deleting them; the guard deletes each row's document and -returns the ids it confirms. Rows it does not confirm stay put. The guarded +returns the ids it confirms. Rows it does not confirm stay put. A service the runtime mounted registers +no guard until the boot reads it as enabled (above): a held service guards +nothing and calls no store, so the sweep deletes its rows on time. The guarded set follows the sources: a source added after boot for an object with no guard gets one when it is loaded, so a reaped row of that object is de-indexed too. @@ -1372,7 +1547,9 @@ followed (§4.1, §4.2) are the adapters to run in production. ### 7.1 Non-goals for Phase 1 -- Reranker hooks, hybrid retrieval toggles, MMR — adapter-private. +- Reranker hooks, MMR — adapter-private. Which legs a search runs is not: + a source declares it (`source.retrieval.mode`, §3.1); how the legs are + weighted is not authorable yet. - Field-level masking inside a passage. A source serving a field the caller may not query is not searched for that caller at all (§5, source admission); a passage is never re-projected or redacted per caller. diff --git a/content/docs/protocol/objectql/schema.mdx b/content/docs/protocol/objectql/schema.mdx index c51526ecd2a..9af0f3c0c83 100644 --- a/content/docs/protocol/objectql/schema.mdx +++ b/content/docs/protocol/objectql/schema.mdx @@ -236,7 +236,7 @@ The `enable` object controls which features are active: ```yaml enable: # Data Management - trackHistory: true # Show the audit ledger's field changes (who changed what, when) + trackHistory: true # Add the audit ledger's field changes to the record timeline (Changes filter) searchable: true # Index for global search # API & Integration apiEnabled: true # Generate REST endpoints @@ -251,11 +251,11 @@ enable: ``` **Performance Impact:** -- `trackHistory: true` adds no write overhead: the audit ledger records every write either way, and the flag only shows its field changes on the record page +- `trackHistory: true` adds no write overhead: the audit ledger records every write either way, and the flag only reads it, to add its field changes to the record page's timeline and to expose the derived `history` API verb - `searchable: true` adds search indexes (storage overhead) **When to enable:** -- **trackHistory:** Users must read who changed which field, and when, on the record page (regulated industries, compliance reviews) +- **trackHistory:** The record page's timeline must also show the audit ledger's field changes, under its Changes filter, or API clients need the `history` verb (regulated industries, compliance reviews). Not needed just to show who changed which field, and when: the default timeline already shows that through `activities`, with each changed field's old and new values (`fieldHistory`), both on by default - **searchable:** User-facing search features ## Field Definition diff --git a/content/docs/references/ai/build-progress.mdx b/content/docs/references/ai/build-progress.mdx deleted file mode 100644 index 059fe43db7a..00000000000 --- a/content/docs/references/ai/build-progress.mdx +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: Build Progress schema — AI Protocol reference -navTitle: Build Progress -description: "Build-progress PHASE vocabulary for the data-build-progress stream frame (the cloud build-progress card, ruling A)." ---- - -{/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} - -Build-progress PHASE vocabulary for the `data-build-progress` stream frame -(the cloud build-progress card, ruling A). - -## How to read the claims in this module - -This vocabulary is CLOSED, so whoever next asks whether a fifth member is -warranted has to re-measure before moving the array — and can only do that -if they can tell a reading from a ruling. Every producer claim below -therefore carries exactly one of three labels, and none is left bare: - -- **measured on a named reachable source** — a repository and path the - reader can open and re-measure, cited with the tree it was read against. -- **declared by ruling** — a maintainer decision. The authority is the - ruling; ⛔ it is not evidence the behaviour exists yet. -- **inferred** — deduced from something reachable, or carried from a record - this repository cannot open. ⛔ Never re-cite it as a measurement. - -## Producer - -The cloud AI-studio **agent loop** — deliberately not the tool it just ran. -**Declared by ruling**: the cloud build-progress card's ruling A owns WHERE in the loop a frame is -emitted; this module declares only what such a frame may SAY. - -A build turn applies its change through `apply_blueprint` / `apply_edit` and -then keeps working: the loop spends a further POST-APPLY VERIFICATION window -re-reading and re-seeding what it wrote. **Inferred.** The only record of -that window is the cloud#1838 turn, reported there as 111 seconds and 9 tool -calls *after* `apply_blueprint` returned — and `objectstack-ai/cloud` is -outside the set of repositories a reader of this file can open, so the -figure is carried here, not measured, and cannot be re-measured from this -repo. WHICH tools those 9 calls were is recorded nowhere reachable either: -neither objectstack#18451 nor objectui#7388 names them, so "one of them ran -the registered `verify_build` tool" is **inferred** as well. What is -**measured on a named reachable source** is narrower than that — only that -`verify_build` is a registered platform tool, listed in -`PLATFORM_TOOLS_BY_PACKAGE` in `../system/constants/platform-tool-names`. - -A tool's own `ctx.onProgress` handle dies when the tool returns, so a frame -emitted in that window can only come from the loop. **Inferred** from a -reachable contract: `AIToolContext.onProgress` in `../contracts/ai-service` -declares the emit as happening WHILE the tool executes, before it returns; -that the handle is gone afterwards is the deduction, not the declaration. - -## Consumer - -The objectui chat panel — `extractBuildProgress` in -`packages/plugin-chatbot/src/mapMessages.ts`, which lifts the reconciled part -onto `ChatBuildProgress` for the build panel in `ChatbotEnhanced.tsx`. That -reader recognises a fixed set and coerces everything else to `'structure'`, -which renders a "still building" spinner. So an UNDECLARED phase is not -merely unlabelled — it reads as the wrong phase, and the user watches a -build that finished two minutes ago still claim to be building -(objectui#7388). The panel's per-phase COPY is objectui's to choose; this -module fixes only the set of values it must be able to tell apart. - -## Channel - -Unchanged: the `data-`-prefixed custom part described on -`AIToolContext.onProgress` in `../contracts/ai-service`, reconciled in place -under a stable part id. This module adds the vocabulary that prose has always -assumed and never declared; it moves no transport and renames nothing. - -## Liveness watch — declared ahead, and ⛔ nothing gates it - -Three surfaces here are declared ahead of any code that uses them: the -`verify` phase, and the frame's `hop` and `tool` fields. Across every -repository reachable from here they have zero emitters and zero readers -(**measured on named reachable sources** — each reading is recorded in the -source beside its surface: on `BUILD_PROGRESS_PHASES` for the phase, and on -the `hop` / `tool` field declarations). They stand on a ruling instead -(**declared by ruling**): the cloud build-progress card ruled the vocabulary in, and -objectui#7388 asked the panel to be able to name the phase. That is a good -reason, and it is not a measurement. - -⛔ No gate watches this. The ADR-0049 liveness ledger is rooted in the -metadata-type registry, and `BuildProgressFrame` is not a registered -metadata type, so the liveness job stays green however long these three go -unused. Two named carriers are meant to close it — the cloud build-progress card for the -emitter, block 2 of the objectui build-panel card for the consumer's strict parse. If neither -lands, the three become enforce-or-remove candidates with nothing watching -them, and the only thing that notices is a person reading this paragraph. - - -**Source:** `packages/spec/src/ai/build-progress.zod.ts` - - -## TypeScript Usage - -```typescript -import { BuildProgressFrameSchema, BuildProgressPhaseSchema } from '@objectstack/spec/ai'; -import type { BuildProgressFrame, BuildProgressPhase } from '@objectstack/spec/ai'; - -// Validate data -const result = BuildProgressFrameSchema.parse(data); -``` - ---- - -## BuildProgressFrame - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **phase** | `Enum<'structure' \| 'data' \| 'verify' \| 'done'>` | ✅ | Build-turn phase this frame reports | -| **hop** | `integer` | optional | Post-apply verification hop this frame reports | -| **tool** | `string` | optional | Name of the tool the current hop is running | - - ---- - -## BuildProgressPhase - -### Allowed Values - -* `structure` -* `data` -* `verify` -* `done` - - ---- - diff --git a/content/docs/references/ai/index.mdx b/content/docs/references/ai/index.mdx index dd0bf3925c6..e1ed9e6f750 100644 --- a/content/docs/references/ai/index.mdx +++ b/content/docs/references/ai/index.mdx @@ -12,7 +12,6 @@ This section contains all protocol schemas for the ai layer of ObjectStack. - @@ -26,5 +25,6 @@ This section contains all protocol schemas for the ai layer of ObjectStack. + diff --git a/content/docs/references/ai/knowledge-document.mdx b/content/docs/references/ai/knowledge-document.mdx index 23677c0807e..626df70bfb6 100644 --- a/content/docs/references/ai/knowledge-document.mdx +++ b/content/docs/references/ai/knowledge-document.mdx @@ -44,7 +44,7 @@ const result = KnowledgeChunkSchema.parse(data); | **index** | `integer` | ✅ | | | **content** | `string` | ✅ | | | **headingPath** | `string[]` | optional | Headings the chunk sits under, outermost first (markdown strategy) | -| **metadata** | `never` | optional | [REMOVED] `KnowledgeChunk.metadata` was removed in @objectstack/spec 18 (ADR-0049, ADR-0161 K8) — nothing ever wrote or read it: the knowledge service cuts the passages and sets no per-passage metadata, and no adapter consulted one. Delete the key. A passage takes its document's `metadata` (`KnowledgeDocument.metadata`), which is what adapters filter on. | +| **metadata** | `never` | optional | [REMOVED] `KnowledgeChunk.metadata` was removed in @objectstack/spec 19.0.0 (ADR-0049, ADR-0161 K8) — nothing ever wrote or read it: the knowledge service cuts the passages and sets no per-passage metadata, and no adapter consulted one. Delete the key. A passage takes its document's `metadata` (`KnowledgeDocument.metadata`), which is what adapters filter on. | --- @@ -75,7 +75,7 @@ const result = KnowledgeChunkSchema.parse(data); | **index** | `integer` | ✅ | | | **content** | `string` | ✅ | | | **headingPath** | `string[]` | optional | Headings the chunk sits under, outermost first (markdown strategy) | -| **metadata** | `never` | optional | [REMOVED] `KnowledgeChunk.metadata` was removed in @objectstack/spec 18 (ADR-0049, ADR-0161 K8) — nothing ever wrote or read it: the knowledge service cuts the passages and sets no per-passage metadata, and no adapter consulted one. Delete the key. A passage takes its document's `metadata` (`KnowledgeDocument.metadata`), which is what adapters filter on. | +| **metadata** | `never` | optional | [REMOVED] `KnowledgeChunk.metadata` was removed in @objectstack/spec 19.0.0 (ADR-0049, ADR-0161 K8) — nothing ever wrote or read it: the knowledge service cuts the passages and sets no per-passage metadata, and no adapter consulted one. Delete the key. A passage takes its document's `metadata` (`KnowledgeDocument.metadata`), which is what adapters filter on. | --- diff --git a/content/docs/references/ai/knowledge-source.mdx b/content/docs/references/ai/knowledge-source.mdx index 70b56ddcce5..2e11a10f60a 100644 --- a/content/docs/references/ai/knowledge-source.mdx +++ b/content/docs/references/ai/knowledge-source.mdx @@ -23,13 +23,47 @@ See `content/docs/protocol/knowledge.mdx` for the design. ## TypeScript Usage ```typescript -import { KnowledgeRefreshPolicySchema, KnowledgeSourceSchema, KnowledgeSplitSchema, KnowledgeSplitStrategySchema, ObjectKnowledgeSourceSchema } from '@objectstack/spec/ai'; -import type { KnowledgeRefreshPolicy, KnowledgeSource, KnowledgeSplit, KnowledgeSplitStrategy, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { KnowledgeAffinityCallerSchema, KnowledgeAffinityEntrySchema, KnowledgeAffinityModeSchema, KnowledgeRefreshPolicySchema, KnowledgeRetrievalSchema, KnowledgeRetrievalModeSchema, KnowledgeSourceSchema, KnowledgeSplitSchema, KnowledgeSplitStrategySchema, ObjectKnowledgeSourceSchema } from '@objectstack/spec/ai'; +import type { KnowledgeAffinityCaller, KnowledgeAffinityEntry, KnowledgeAffinityMode, KnowledgeRefreshPolicy, KnowledgeRetrieval, KnowledgeRetrievalMode, KnowledgeSource, KnowledgeSplit, KnowledgeSplitStrategy, ObjectKnowledgeSource } from '@objectstack/spec/ai'; // Validate data -const result = KnowledgeRefreshPolicySchema.parse(data); +const result = KnowledgeAffinityCallerSchema.parse(data); ``` +--- + +## KnowledgeAffinityCaller + +### Allowed Values + +* `user` +* `business_unit` + + +--- + +## KnowledgeAffinityEntry + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **field** | `string` | ✅ | A field listed in metadataFields, compared with the caller fact | +| **caller** | `Enum<'user' \| 'business_unit'>` | ✅ | The caller fact compared: user or business_unit | +| **mode** | `Enum<'boost' \| 'nearest'>` | ✅ | boost lifts a match by places; nearest puts the caller's own unit first, then its parents | +| **places** | `integer` | optional | boost only: how many non-matching hits a match may pass, 1 to 20 | + + +--- + +## KnowledgeAffinityMode + +### Allowed Values + +* `boost` +* `nearest` + + --- ## KnowledgeRefreshPolicy @@ -42,6 +76,28 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | **cron** | `never` | optional | [REMOVED] `knowledge_source.refresh.cron` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — it was parsed and reached no engine: nothing ever scheduled a reindex from it. Delete the key. To rebuild on a schedule, call `reindexSource` from a flow or a job; keeping the index correct between events is the service's reconcile pass. A source registered in code (`KnowledgeServicePlugin({ sources })`, `registerSource`) is in no stack collection, so `os migrate meta` lists no edit for it: make this edit in the registration itself. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +--- + +## KnowledgeRetrieval + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **mode** | `Enum<'vector' \| 'keyword' \| 'hybrid'>` | optional | Which legs a search runs: vector, keyword or hybrid; omitted means the store's default | + + +--- + +## KnowledgeRetrievalMode + +### Allowed Values + +* `vector` +* `keyword` +* `hybrid` + + --- ## KnowledgeSource @@ -78,8 +134,11 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | **content** | `string[]` | ✅ | Fields whose text is indexed, in order; every name is listed (no wildcard) | | **contentFields** | `never` | optional | [REMOVED] `knowledge_source.source.contentFields` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — the key is spelled `content` now that a source is a metadata item; use `content`. Rename the key; the value (a list of field names) is unchanged, except that a `'*'` member is no longer accepted and is replaced by the field names it stood for. A source registered in code (`KnowledgeServicePlugin({ sources })`, `registerSource`) is in no stack collection, so `os migrate meta` lists no edit for it: make this edit in the registration itself. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **metadataFields** | `string[]` | optional (default: `[]`) | | +| **documentBy** | `string` | optional | Field linking each record to its parent document (a lookup or master_detail listed in metadataFields); record-level search answers one hit per parent | | **where** | `Record` | optional | | | **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | +| **affinity** | `{ field: string; caller: Enum<'user' \| 'business_unit'>; mode: Enum<'boost' \| 'nearest'>; places?: integer }[]` | optional | How this source's hits are ordered for the caller: boost (by places) or nearest (own business unit first), by position, never by score | +| **retrieval** | `{ mode?: Enum<'vector' \| 'keyword' \| 'hybrid'> }` | optional | How this source is searched: mode vector, keyword or hybrid; omitted means the store's default, and changing it rebuilds nothing | ### Nested Shape: `KnowledgeSource.refresh` @@ -99,7 +158,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | :--- | :--- | :--- | :--- | | **strategy** | `Enum<'whole' \| 'recursive' \| 'markdown'>` | ✅ | Split strategy: whole, recursive or markdown | | **maxChars** | `integer` | optional | Longest passage in characters; wins over the settings default, the embedder limit can lower it | -| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); a value above the effective maxChars reads as maxChars | +| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); under markdown, only in a section that does not fit, since a section that fits is one passage; a value above the effective maxChars reads as maxChars | --- @@ -126,8 +185,11 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | **content** | `string[]` | ✅ | Fields whose text is indexed, in order; every name is listed (no wildcard) | | **contentFields** | `never` | optional | [REMOVED] `knowledge_source.source.contentFields` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — the key is spelled `content` now that a source is a metadata item; use `content`. Rename the key; the value (a list of field names) is unchanged, except that a `'*'` member is no longer accepted and is replaced by the field names it stood for. A source registered in code (`KnowledgeServicePlugin({ sources })`, `registerSource`) is in no stack collection, so `os migrate meta` lists no edit for it: make this edit in the registration itself. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **metadataFields** | `string[]` | optional (default: `[]`) | | +| **documentBy** | `string` | optional | Field linking each record to its parent document (a lookup or master_detail listed in metadataFields); record-level search answers one hit per parent | | **where** | `Record` | optional | | | **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | +| **affinity** | `{ field: string; caller: Enum<'user' \| 'business_unit'>; mode: Enum<'boost' \| 'nearest'>; places?: integer }[]` | optional | How this source's hits are ordered for the caller: boost (by places) or nearest (own business unit first), by position, never by score | +| **retrieval** | `{ mode?: Enum<'vector' \| 'keyword' \| 'hybrid'> }` | optional | How this source is searched: mode vector, keyword or hybrid; omitted means the store's default, and changing it rebuilds nothing | ### Nested Shape: `ObjectKnowledgeSource.split` @@ -135,7 +197,22 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | :--- | :--- | :--- | :--- | | **strategy** | `Enum<'whole' \| 'recursive' \| 'markdown'>` | ✅ | Split strategy: whole, recursive or markdown | | **maxChars** | `integer` | optional | Longest passage in characters; wins over the settings default, the embedder limit can lower it | -| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); a value above the effective maxChars reads as maxChars | +| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); under markdown, only in a section that does not fit, since a section that fits is one passage; a value above the effective maxChars reads as maxChars | + +### Nested Shape: `ObjectKnowledgeSource.affinity[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **field** | `string` | ✅ | A field listed in metadataFields, compared with the caller fact | +| **caller** | `Enum<'user' \| 'business_unit'>` | ✅ | The caller fact compared: user or business_unit | +| **mode** | `Enum<'boost' \| 'nearest'>` | ✅ | boost lifts a match by places; nearest puts the caller's own unit first, then its parents | +| **places** | `integer` | optional | boost only: how many non-matching hits a match may pass, 1 to 20 | + +### Nested Shape: `ObjectKnowledgeSource.retrieval` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **mode** | `Enum<'vector' \| 'keyword' \| 'hybrid'>` | optional | Which legs a search runs: vector, keyword or hybrid; omitted means the store's default | --- diff --git a/content/docs/references/ai/meta.json b/content/docs/references/ai/meta.json index d77e258852b..f94117bc2d7 100644 --- a/content/docs/references/ai/meta.json +++ b/content/docs/references/ai/meta.json @@ -17,11 +17,11 @@ "---More---", "ai-context", "ask-question", - "build-progress", "dataset-tools", "draft-review", "object-query-source", "record-citation", - "record-context-tools" + "record-context-tools", + "turn-end" ] } \ No newline at end of file diff --git a/content/docs/references/ai/turn-end.mdx b/content/docs/references/ai/turn-end.mdx new file mode 100644 index 00000000000..f21923a973d --- /dev/null +++ b/content/docs/references/ai/turn-end.mdx @@ -0,0 +1,70 @@ +--- +title: Turn End schema — AI Protocol reference +navTitle: Turn End +description: "The turn end — why an ask turn stopped, and whether the person may ask the server to carry the same turn on from where it stopped." +--- + +{/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} + +The turn end — why an ask turn stopped, and whether the person may ask the +server to carry the same turn on from where it stopped. + +## Who writes it, who reads it + +- **Producer:** the host that runs the ask turn. At the end of a streamed + turn, before the stream's `finish`, it sends one UI-message-stream data + part named `TURN_END_PART_TYPE` whose `data` is a + `TurnEndSchema` object. It stores the same object with the turn's + last message, and the conversation routes return it there as + `AiConversationMessageSchema.turnEnd`, so a reloaded conversation knows + it too. A turn replayed by its `turnId` (nothing ran) sends none. +- **Reader:** the console's chat (`extractTurnEnd` in + `@object-ui/plugin-chatbot`). It reads the part, or the stored field, + through this schema; one the schema refuses is no turn end at all, and the + answer renders as it does without one. + +## What the chat does with it + +Under the conversation's last answer, while nothing is streaming, the chat +offers a Continue control when `resumable` is `true` and `resumesLeft` is +above zero. Pressing it sends a chat request carrying +`resume: { turnId }` (`AiChatRequestSchema.resume`) and no new user message; +the server rebuilds the stopped turn from what it stored and streams the +rest of the answer into the same turn. The request carries no top-level +`turnId` (a resume names its turn itself), and its `messageId` is the +answer's id: the resume stream's `start` chunk carries that id or none, or +the chat draws the rest as a second answer. Whether a turn may be resumed +is the server's decision alone: the chat never infers it from `reason`, and +the server refuses a resume it did not offer. + + +**Source:** `packages/spec/src/ai/turn-end.zod.ts` + + +## TypeScript Usage + +```typescript +import { TurnEndSchema } from '@objectstack/spec/ai'; +import type { TurnEnd } from '@objectstack/spec/ai'; + +// Validate data +const result = TurnEndSchema.parse(data); +``` + +--- + +## TurnEnd + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **reason** | `string` | ✅ | Why the turn ended, in the producer's own words: `answered` when the model ended it, `tool_ended` when a tool did, the limit that sent it to a wrap-up answer (`time_limit`, `token_budget`, `max_iterations`, …), or the kind of refusal that stopped it. Informational: the chat decides nothing from it | +| **wrapUp** | `boolean` | ✅ | `true` when the answer is the wrap-up the turn gave on reaching a limit, written from what the turn had read so far, rather than an answer the model finished on its own | +| **resumable** | `boolean` | ✅ | The server's verdict that a resume of this turn would be accepted now. The chat offers Continue only when it is `true` and `resumesLeft` is above zero | +| **resumesLeft** | `integer` | ✅ | How many more times this turn may be resumed; `0` once none are left | +| **turnId** | `string` | ✅ | The turn this end belongs to: the `turnId` a resume names in `AiChatRequestSchema.resume.turnId` | + + +--- + diff --git a/content/docs/references/automation/execution.mdx b/content/docs/references/automation/execution.mdx index 610c160b022..8f402a0cbf2 100644 --- a/content/docs/references/automation/execution.mdx +++ b/content/docs/references/automation/execution.mdx @@ -150,6 +150,8 @@ const result = CheckpointSchema.parse(data); | **skippedBy** | `{ nodeId: string; edgeId?: string; label?: string }` | optional | The gate that closed, when `status` is `skipped` | | **warnings** | `string[]` | optional | Advisory warnings from the node executor. A `success` step may carry them — e.g. a write whose requested fields the data engine legally stripped — so a step that partially did not land never reads as a clean success. Absent when the executor raised none | | **droppedFields** | `{ object: string; fields: string[]; reason: Enum<'readonly' \| 'readonly_when' \| 'primary_key' \| 'computed' \| 'stored_expression'> }[]` | optional | The data engine's own drop events behind those warnings: which caller-supplied fields of which object the write did not store, and why. Absent when the step dropped nothing | +| **childRunIds** | `string[]` | optional | Run ids of the child runs this step started: the one run of a `subflow`, and for a `map` the item runs this execution of the step started, at most 200, the first ones started. Absent for a step that started none, and where `childRunIdsTruncated` says the links were shed | +| **childRunIdsTruncated** | `true` | optional | Set when this step started more child runs than `childRunIds` names: its execution started more than 200, or the run's history row shed the step's links to fit its size limit, leaving `childRunIds` absent. Absent when `childRunIds` names every child run the step started | ### Nested Shape: `ExecutionLog.summary` @@ -210,6 +212,8 @@ const result = CheckpointSchema.parse(data); | **skippedBy** | `{ nodeId: string; edgeId?: string; label?: string }` | optional | The gate that closed, when `status` is `skipped` | | **warnings** | `string[]` | optional | Advisory warnings from the node executor. A `success` step may carry them — e.g. a write whose requested fields the data engine legally stripped — so a step that partially did not land never reads as a clean success. Absent when the executor raised none | | **droppedFields** | `{ object: string; fields: string[]; reason: Enum<'readonly' \| 'readonly_when' \| 'primary_key' \| 'computed' \| 'stored_expression'> }[]` | optional | The data engine's own drop events behind those warnings: which caller-supplied fields of which object the write did not store, and why. Absent when the step dropped nothing | +| **childRunIds** | `string[]` | optional | Run ids of the child runs this step started: the one run of a `subflow`, and for a `map` the item runs this execution of the step started, at most 200, the first ones started. Absent for a step that started none, and where `childRunIdsTruncated` says the links were shed | +| **childRunIdsTruncated** | `true` | optional | Set when this step started more child runs than `childRunIds` names: its execution started more than 200, or the run's history row shed the step's links to fit its size limit, leaving `childRunIds` absent. Absent when `childRunIds` names every child run the step started | ### Nested Shape: `ExecutionStepLog.error` diff --git a/content/docs/references/data/data-engine.mdx b/content/docs/references/data/data-engine.mdx index 7b603eab15c..00a619378bb 100644 --- a/content/docs/references/data/data-engine.mdx +++ b/content/docs/references/data/data-engine.mdx @@ -70,6 +70,7 @@ const result = BaseEngineOptionsSchema.parse(data); | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -128,6 +129,7 @@ Options for DataEngine.aggregate operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -184,6 +186,7 @@ Options for DataEngine.count operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -241,6 +244,7 @@ Options for DataEngine.delete operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -320,6 +324,7 @@ Options for DataEngine.insert operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -382,6 +387,7 @@ Query options for IDataEngine.find() operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -470,6 +476,7 @@ Options for DataEngine.update operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -547,6 +554,7 @@ QueryAST-aligned options for DataEngine.aggregate operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -636,6 +644,7 @@ QueryAST-aligned options for DataEngine.count operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -707,6 +716,7 @@ QueryAST-aligned options for DataEngine.delete operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -773,6 +783,7 @@ QueryAST-aligned query options for IDataEngine.find() operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -867,6 +878,7 @@ QueryAST-aligned options for DataEngine.update operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index c94c8d6d665..349cf06f66b 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -95,7 +95,7 @@ const result = CurrencyConfigSchema.parse(data); | **lookupColumns** | `(string \| { field: string; label?: string; width?: string; type?: string })[]` | optional | Explicit columns for the record-picker table; auto-derived from the referenced object when omitted. | | **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). | | **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | -| **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | +| **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For a reference field (`lookup`, `master_detail`, `user`, `tree`) it scopes the candidate query and an import's lookup of the column by equality on the referenced object (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is reference-only), so that key must be a stored field of the referenced object, never one computed on read. For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. CURRENCY RULE: an amount of money (a `currency` field, or a `formula` returning `currency`) is copied only into a target in the same currency, both in the home currency or both naming the same ISO 4217 code (a `fixed` code, or the code the record or its `master_detail` parent holds). Otherwise the target is left as it is and the form says why, naming both currencies and the picked amount; nothing is converted. A `number` carries no currency and copies as before. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy, under the same currency rule; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | diff --git a/content/docs/references/data/hook.mdx b/content/docs/references/data/hook.mdx index 6dac1015ed2..f599774da6d 100644 --- a/content/docs/references/data/hook.mdx +++ b/content/docs/references/data/hook.mdx @@ -115,7 +115,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | **submitted** | `Record` | optional | What the caller submitted, as sent (update only) — diagnostics only, never the persist image | | **dispatch** | `{ mode: Enum<'record' \| 'per-row'>; index: integer; scope: Record }` | optional | How this hook call relates to the caller's write (engine-produced) | | **session** | `{ userId?: string; actor?: string; organizationId?: string; accessToken?: string; … }` | optional | Current session context | -| **provenance** | `{ flowRunId?: string; attributedUserId?: string; performedByClientId?: string; performedByAgentId?: string; … }` | optional | Server-stamped write provenance (never client-supplied, never an authorization input) | +| **provenance** | `{ flowRunId?: string; flowRootRunId?: string; attributedUserId?: string; performedByClientId?: string; … }` | optional | Server-stamped write provenance (never client-supplied, never an authorization input) | | **referentialFieldClear** | `boolean` | optional | Engine-produced marker: true exactly when this write is the engine's own referential cleanup (the set_null cascade UPDATE clearing — or, for multiple: true, removing the deleted member from — a lookup, tree or user field that references a record being deleted, where a user field takes part only when it declares its deleteBehavior). Absent on every other write, including a user hand-clearing the same field; read as `ctx.referentialFieldClear === true`. The declared projection of the operation-private `__referentialFieldClear`, carried across the sandbox boundary by contract; server-derived and never client-supplied. | | **referentialCascadeDelete** | `boolean` | optional | Engine-produced marker: true exactly when this delete is one the engine's cascade issued (the child delete removing a row that references a record being deleted through a relation whose deleteBehavior resolves to cascade, at any depth), in both phases of that delete. Absent on every other delete, including a user hand-deleting the same child and a delete a hook issues through ctx.api; read as `ctx.referentialCascadeDelete === true`. The delete twin of referentialFieldClear, carried across the sandbox boundary by contract; server-derived, never client-supplied, and with no operation-private spelling to read instead. | | **transaction** | `any` | optional | Database transaction handle | @@ -155,6 +155,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **flowRunId** | `string` | optional | Id of the automation flow run performing this write, when it originates from a flow data node. Lets a hook recognize the run that OWNS state that run itself opened — the approvals record lock exempts the run holding the pending request. | +| **flowRootRunId** | `string` | optional | Id of the root run of the flow-run tree `flowRunId` belongs to: the run the tree was started on, above every `subflow` child and `map` item run (equal to `flowRunId` on a run with no parent). Copied from `ExecutionContext.flowRootRunId`, which only the automation engine sets, beside `flowRunId`. Provenance, not authorization: lets a hook recognize a write by any run of one tree — the approvals plugin passes the runs of an approval through the hold it keeps between two steps on an object that declares `closedStates` (ADR-0162 D5). | | **attributedUserId** | `string` | optional | The real human credited for a write whose authorization subject was the SYSTEM — e.g. the admin whose better-auth `update-member-role` call the identity adapter executes as `isSystem`. ATTRIBUTION ONLY: the audit writer records it as `sys_audit_log.user_id`; no security middleware reads it, and it never becomes the subject the write is authorized as. | | **performedByClientId** | `string` | optional | [ADR-0090 D10 rule 4] The AGENT that performed this write — the OAuth client (`azp`, the `client_id` of a registered sys_oauth_application) the access token was issued to, when an AI client acted on behalf of the human in `session.userId`. Copied from `ExecutionContext.performedBy.clientId`, which only the /mcp OAuth door sets. ATTRIBUTION ONLY, exactly like `attributedUserId`: the audit writer records it in `sys_audit_log.metadata` as `performed_by` beside `on_behalf_of`; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every non-delegated write, so a hook tells the two apart by the key being there rather than by guesswork. | | **performedByAgentId** | `string` | optional | The in-product AI agent that performed this write for the signed-in person in `session.userId`, whose write it runs as: the agent the chat runs as. Copied from `ExecutionContext.performedBy.agentId`, which only the server-constructed in-product AI path sets, after resolving it as the agent it actually ran. ATTRIBUTION ONLY, exactly like `performedByClientId`: the record-write audit writer records it in `sys_audit_log.metadata` as `performed_by` beside `on_behalf_of`, the key an OAuth client id is also recorded in (when `performedByClientId` is also present the row records the client instead). A value matching the `client_id` of an existing `sys_oauth_application` row is an OAuth client, and a row carrying `conversation_id` or `confirmation_id` names an in-product agent; a row meeting neither may name an agent or the client of a since-deleted application, which the row alone cannot tell apart, and the contract does not keep an agent name and a `client_id` from being the same string (where both tells apply the mark decides, and a matching value with no mark is the client unless an agent shares that string); no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every write the person made themselves. | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 13c27fe5b97..7c60c56deea 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -1,7 +1,7 @@ --- title: Object schema — Data Protocol reference navTitle: Object -description: "Object schemas of the ObjectStack Data Protocol: ApiMethod, ApiOperation, Index and 21 more — each property with its type, default and a TypeScript example." +description: "Object schemas of the ObjectStack Data Protocol: ApiMethod, ApiOperation, Index and 22 more — each property with its type, default and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -13,8 +13,8 @@ description: "Object schemas of the ObjectStack Data Protocol: ApiMethod, ApiOpe ## TypeScript Usage ```typescript -import { ApiMethod, ApiOperationSchema, IndexSchema, LifecycleSchema, LifecycleClassSchema, ObjectSchema, ObjectAccessConfigSchema, ObjectCapabilities, ObjectExtensionSchema, ObjectExtensionFieldPlacementSchema, ObjectExtensionGroupPlacementSchema, ObjectExtensionListPlacementSchema, ObjectExtensionPlacementSchema, ObjectExtensionRelatedListEntrySchema, ObjectExtensionRelatedListEntryObjectSchema, ObjectExternalBindingSchema, ObjectFieldGroupSchema, ObjectOwnershipEnum, ObjectRequiredPermissionsSchema, PerOperationRequiredPermissionsSchema, RelatedListEntrySchema, RelatedListEntryObjectSchema, RowCrudActionOverrideSchema, TenancyConfigSchema } from '@objectstack/spec/data'; -import type { ApiMethod, ApiOperation, Lifecycle, LifecycleClass, ObjectAccessConfig, ObjectCapabilities, ObjectExtension, ObjectExtensionFieldPlacement, ObjectExtensionGroupPlacement, ObjectExtensionListPlacement, ObjectExtensionPlacement, ObjectExtensionRelatedListEntry, ObjectExtensionRelatedListEntryObject, ObjectExternalBinding, ObjectFieldGroup, ObjectRequiredPermissions, PerOperationRequiredPermissions, RelatedListEntry, RelatedListEntryObject, RowCrudActionOverride, TenancyConfig } from '@objectstack/spec/data'; +import { ApiMethod, ApiOperationSchema, IndexSchema, LifecycleSchema, LifecycleClassSchema, ObjectSchema, ObjectAccessConfigSchema, ObjectCapabilities, ObjectExtensionSchema, ObjectExtensionFieldPlacementSchema, ObjectExtensionGroupPlacementSchema, ObjectExtensionListPlacementSchema, ObjectExtensionPlacementSchema, ObjectExtensionRelatedListEntrySchema, ObjectExtensionRelatedListEntryObjectSchema, ObjectExternalBindingSchema, ObjectFieldGroupSchema, ObjectFieldTabSchema, ObjectOwnershipEnum, ObjectRequiredPermissionsSchema, PerOperationRequiredPermissionsSchema, RelatedListEntrySchema, RelatedListEntryObjectSchema, RowCrudActionOverrideSchema, TenancyConfigSchema } from '@objectstack/spec/data'; +import type { ApiMethod, ApiOperation, Lifecycle, LifecycleClass, ObjectAccessConfig, ObjectCapabilities, ObjectExtension, ObjectExtensionFieldPlacement, ObjectExtensionGroupPlacement, ObjectExtensionListPlacement, ObjectExtensionPlacement, ObjectExtensionRelatedListEntry, ObjectExtensionRelatedListEntryObject, ObjectExternalBinding, ObjectFieldGroup, ObjectFieldTab, ObjectRequiredPermissions, PerOperationRequiredPermissions, RelatedListEntry, RelatedListEntryObject, RowCrudActionOverride, TenancyConfig } from '@objectstack/spec/data'; // Validate data const result = ApiMethod.parse(data); @@ -151,7 +151,7 @@ const result = ApiMethod.parse(data); | **description** | `string` | optional | Developer documentation / description | | **icon** | `string` | optional | Icon name (Lucide/Material) for UI representation | | **color** | `Enum<'gray' \| 'blue' \| 'teal' \| 'green' \| 'amber' \| 'orange' \| 'red' \| 'pink' \| 'purple'>` | optional | Object colour, one name from the fixed palette (gray, blue, teal, green, amber, orange, red, pink, purple). The console draws the object's icon as a white glyph on a rounded square of this colour, so one object looks the same wherever its icon appears. No free colour values. Omit to draw the neutral `gray`. | -| **actionLayout** | `{ list?: object; record?: object }` | optional | The order of the object's actions and which are buttons, per action scope (`list`, `record`): `pinned` (at most 3 buttons, in order) and `more` (the 「More」 menu order; unnamed actions follow in their default order). Omit to keep each surface's own choice (each action's `order`). | +| **actionLayout** | `{ list?: object; record?: object; selection?: object }` | optional | The order of the object's actions and which are buttons, per action scope (`list`, `record`, `selection`): `pinned` (at most 3 buttons, in order) and `more` (the 「More」 menu order; unnamed actions follow in their default order). Omit to keep each surface's own choice (each action's `order`). | | **isSystem** | `boolean` | optional (default: `false`) | Is system object (protected from deletion; defaults its org-wide sharing to public when no sharingModel is set — plugin-sharing) | | **managedBy** | `Enum<'platform' \| 'config' \| 'system-data' \| 'engine-owned' \| 'append-only' \| 'synced' \| 'better-auth'>` | optional | Lifecycle bucket — platform (user CRUD) \| config (admin authored) \| system-data (platform-defined schema, admin/user-writable data) \| engine-owned (engine owns the lifecycle, no user writes) \| append-only (audit) \| synced (rows copied by a pull from a connector or federated source; read-only to members, and userActions cannot open a write) \| better-auth (identity). UI clients honour the resolved affordance matrix. | | **ownership** | `Enum<'user' \| 'business_unit' \| 'org' \| 'none'>` | optional | Record-ownership model: user (default — injects reassignable owner_id plus owning_business_unit_id) \| business_unit (unit-owned: owning_business_unit_id only, no owner_id) \| org \| none (no per-record owner, neither anchor). Distinct from the package own/extend contribution kind. | @@ -172,12 +172,15 @@ const result = ApiMethod.parse(data); | **validations** | `any[]` | optional | Object-level validation rules | | **activityMilestones** | `{ field: string; value: string; summary: string; type?: string }[]` | optional | Declarative semantic activity milestones — emit a templated timeline row when a field transitions into a value, no hook code (ADR-0052 §5b.2). | | **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — every field of an existing record is read-only BY HAND while TRUE: the console surfaces a field's own `uiReadonlyWhen` locks (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt, the timesheet cell, the line-item grid) do not let a person edit the record, while REST, import, action and flow writes keep every field, judged by the object's validations. e.g. P`record.status in ['confirmed', 'done']` on an order moved by Confirm / Cancel actions. A default for every field: a field that declares `uiReadonly: true` or its own `uiReadonlyWhen` is judged by that instead, so a field whose own `uiReadonlyWhen` is P`false` stays editable inside a locked record; `uiReadonly: false` is not such a declaration and the field follows the object lock. A create is not judged. A predicate the console cannot evaluate locks every field that inherits it. Same scope as a field's `readonlyWhen`: the record's OWN columns. The engine never reads this key. | +| **closedStates** | `Record` | optional | States in which a record is CLOSED: a map from a stored, single-value `select` field of this object to the list of that field's option values that close the record, e.g. `{ status: ['paid', 'void'], approval_status: ['approved'] }`. A record is closed when ANY listed field holds one of its listed values, read off the stored row. While closed, the record and its direct master_detail lines are closed to change for every caller that is not a system context: the record is not updated or deleted, and no line is created, updated, deleted or moved. The field must declare inline options; each listed value is one of them; a list is not empty and repeats nothing. A field or option a declaration names cannot be removed or retyped while it names it. A line object declares nothing to be closed with its master, and may declare its own. Independent of any state_machine rule on the field. | | **nameField** | `string` | optional | [ADR-0079] Canonical primary title field — the stored field used as the record display name (e.g. "name", "title"). | | **displayNameField** | `string` | optional | [DEPRECATED → nameField] Field to use as the record display name (e.g., "name", "title"). Accepted as an alias for nameField. | | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | | **imageField** | `string` | optional | The record's picture: names the field the record page header (record chrome) draws beside the title — one object-level declaration every record detail page reads, not a per-page header prop. Must name a field of this object whose type is `image` or `avatar`; any other name is refused. A record whose field is empty shows no picture (no initials or placeholder). | | **highlightFields** | `string[]` | optional | [ADR-0085] Ordered most-important fields; first entry wins where only one fits. Drives default list and related-list columns, cards, hover cards, previews and the record picker; the default record page draws no strip from it. Renamed from compactLayout. | | **relatedLists** | `(string \| { list: string; label?: string; columns?: string[] })[]` | optional | The record page's tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. A child list another package brings is not hidden by it: that package places the list with its object extension's place entry (an `{ list, after \| before }` entry), and an unplaced one shows at the end of the tabs, before approvals and the activity stream; this object may also name it, which a build accepts only when that package is in the stack, and then its own position wins. Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be `{ list, label?, columns? }` to give that list its own title and child-field columns (wins over the child FK's relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused by os validate / os build (which leave a sys_ / cloud_ / ai_ name to the runtime) and by a metadata write that names no package; a write into a package stores it and the record page places nothing for it. A columns name that resolves to no field of the child (a dotted name is walked through the child's relationships, as relatedListColumns is) is refused. | +| **pinOverview** | `boolean` | optional | Whether the desktop full standard record page pins the overview (the record's own fields) to a left column beside its other tabs. Absent or true: derived as before (a full page wide enough for both columns, with another tab and no related table among the fields, pins). false: the desktop full page never pins, at any width; the overview is its first tab, open by default, and its fields lay out by width in up to three columns, also when the overview holds a related table. Read by the desktop full standard record page alone: the side preview and a phone draw the same either way, and print pages and authored kind: full \| html \| react pages do not read it. Not accepted on an object extension. | +| **fieldTabs** | `{ key: string; groups: string[] }[]` | optional | Field groups the standard record page draws as tabs of their own, right after the overview and before the related-list tabs, in this order. Each entry is `{ key, groups }`: key names the tab (snake_case; its page address is fields:``), groups lists keys of this object's fieldGroups, drawn in that order and taken out of the overview. The tab's title and icon are its first group's. The reader cannot move or hide these tabs. Refused: a group the object does not declare, a group two tabs name, a group with relatedList (body tables stay in the overview), a repeated key. Absent: unchanged. The entry form, print pages and authored kind: full \| html \| react pages are not affected. Not accepted on an object extension. Not the form-level FormSchema.fieldTabs, which lists field names. | | **stageField** | `string \| false` | optional | [ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed. When the named field carries options, it must be a single-value `select` / `radio` with inline `options`, each declaring its `kind` ('open' / 'won' / 'lost'); a picklist-backed or multi-value stage field is refused. A name that resolves to no declared field, or a field with no options, is not judged at parse. | | **editMode** | `Enum<'modal' \| 'page'>` | optional | Edit-interaction intent for records of this object: 'modal' opens the edit form as a dialog over the current view; 'page' navigates to a dedicated full-page edit route. Absent = the renderer picks its own default (objectui defaults to modal). Cross-renderer intent, not pixel styling (family). | | **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | @@ -205,6 +208,7 @@ const result = ApiMethod.parse(data); | :--- | :--- | :--- | :--- | | **list** | `{ pinned: string[]; more?: string[] }` | optional | The list scope's arrangement: actions of the object placed at `list`, as drawn on the list page toolbar, and `$import` / `$export` as pinned buttons (not pinned, they stay in the page's own Import / Export menu). Omit to draw it as before. | | **record** | `{ pinned: string[]; more?: string[] }` | optional | The record scope's arrangement: actions of the object placed at `record` or `record_page`, as drawn in the record header (record page, side preview, a phone's bottom bar). The same order leads the actions a grid row already offers, adding none: the row's ⋮ menu, its right-click menu and, on a list page, the selection bar's actions for one selected record (`pinned` names first, then `more` names, then the rest as before). The selection bar's buttons, at most three, are the first of that order; a row's own inline button does not change. Omit to draw each as before. | +| **selection** | `{ pinned: string[]; more?: string[] }` | optional | The selection scope's arrangement: actions of the object placed at `selection`, as drawn on the selection bar a grid shows once two or more rows are selected, on every grid view of the object. `pinned` names the bar's buttons, in order; the rest, Delete included, are in the bar's 「More」: a view's own `bulkActionDefs` first, then the actions `more` names, then the others. Omit to draw a view's own `bulkActionDefs` first and then the actions in their default order, the first three entries as buttons. | ### Nested Shape: `Object.userActions` @@ -284,7 +288,7 @@ const result = ApiMethod.parse(data); | **lookupColumns** | `(string \| { field: string; label?: string; width?: string; type?: string })[]` | optional | Explicit columns for the record-picker table; auto-derived from the referenced object when omitted. | | **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). | | **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | -| **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | +| **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For a reference field (`lookup`, `master_detail`, `user`, `tree`) it scopes the candidate query and an import's lookup of the column by equality on the referenced object (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is reference-only), so that key must be a stored field of the referenced object, never one computed on read. For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. CURRENCY RULE: an amount of money (a `currency` field, or a `formula` returning `currency`) is copied only into a target in the same currency, both in the home currency or both naming the same ISO 4217 code (a `fixed` code, or the code the record or its `master_detail` parent holds). Otherwise the target is left as it is and the form says why, naming both currencies and the picked amount; nothing is converted. A `number` carries no currency and copies as before. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy, under the same currency rule; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | @@ -405,6 +409,13 @@ const result = ApiMethod.parse(data); | **label** | `string` | optional | This list's title on the record page (its tab and its table heading). Wins over the child FK's relatedListTitle; absent = that key, else the child object's plural label. | | **columns** | `string[]` | optional | This list's columns, as field names of the child object (e.g. ['product', 'quantity', 'amount']). Wins over the child FK's relatedListColumns; absent = that key, else the child object's derived columns. Used wherever this list is drawn: its tab, and the body table a field group places. A name that is no field of the child is refused where the child is known. | +### Nested Shape: `Object.fieldTabs[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **key** | `string` | ✅ | The tab's key (snake_case). The record page addresses the tab as fields:``. | +| **groups** | `string[]` | ✅ | The field groups this tab holds: keys of this object's fieldGroups, in the order the tab draws them. The first one's label and icon title the tab. | + ### Nested Shape: `Object.listViews[string]` | Property | Type | Required | Description | @@ -442,8 +453,8 @@ const result = ApiMethod.parse(data); | **hiddenFields** | `string[]` | optional | Fields to hide in this specific view — the SUBTRACTION of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: each name listed here is removed from the `columns` projection before `fieldOrder` orders the remainder. A name `columns` never projected subtracts nothing. | | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | -| **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActions** | `never` | optional | [REMOVED] `view.list.bulkActions` was removed in @objectstack/spec 19.0.0 (ADR-0085) — the actions a selection of records offers are the object's, not one view's: the selection bar a grid shows once two or more rows are selected draws the same actions on every view of the object. Delete the key, and add `'selection'` to the `locations` of each action it named; to order the bar, or to choose its buttons, write the object's `actionLayout.selection` (`{ pinned, more }`). A view's own `bulkActionDefs` stay on the view: they lead the bar without the arm, and its 「More」 with it. The built-in bulk Delete no longer follows the list: a grid draws it wherever the object allows a delete, on every view with no `bulkActionDefs`, and a view with authored defs draws it only through a `{ name: 'delete', operation: 'delete' }` def. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch place the action at `selection` instead — it is promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | @@ -522,7 +533,7 @@ const result = ApiMethod.parse(data); | **description** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object } \| string \| Record` | optional | Explanatory line shown under the title in the action's param dialog. Carries the confirm question for an action that collects params (one dialog, not two). Not the LLM-facing `ai.description`. It is a `template` slot (ADR-0032): a bare string is shorthand for `{ dialect: 'template', source }`, and text with no hole is shown as written. Holes are `{{ path }}` or `{{ path \| formatter[:arg] }}` over `record`, the record the action runs against (the clicked row on a list, else the page's record); the values the dialog collects are not bound, since the line shows before they exist. Formatters come from the template engine's whitelist (`TEMPLATE_FORMATTERS`, `@objectstack/formula`); a hole holds no logic (no CEL, no arithmetic). Example: 'Choose the new role for `{{ record.name }}`.'. A hole over any other root, a `${…}` or single-brace `{x}` token (each named with its `{{ }}` spelling), a hole holding logic or an unknown formatter, and a blank sentence are named and refused at `objectstack validate`, `compile` and the publish gate; the text still parses, so a stored one loads until its next save. An inline locale map (`{ en, "zh-CN" }`) is accepted too, each value such a sentence. | | **objectName** | `string` | optional | Target object this action belongs to. When set, the action is auto-merged into the object's actions array by defineStack(). | | **icon** | `string` | optional | Icon name | -| **locations** | `Enum<'list' \| 'record' \| 'record_page' \| 'record_row' \| 'record_related' \| 'record_section'>[]` | optional | Locations where this action is visible. `record_section` is drawn only by an authored record page block that renders it; the standard record page (on a phone, in the side preview, and for an object with no authored page) does not draw it, so an action that must reach every surface adds `record_page` as well, with `component: 'action:menu'` to sit in the record page's ⋯ menu rather than be a header button. `list` acts on no record (the list page toolbar); `record` acts on one record, on the record page and on each list row; `record_page` and `record_row` are one of those two only. | +| **locations** | `Enum<'list' \| 'record' \| 'record_page' \| 'record_row' \| 'record_related' \| …>[]` | optional | Locations where this action is visible. `record_section` is drawn only by an authored record page block that renders it; the standard record page (on a phone, in the side preview, and for an object with no authored page) does not draw it, so an action that must reach every surface adds `record_page` as well, with `component: 'action:menu'` to sit in the record page's ⋯ menu rather than be a header button. `list` acts on no record (the list page toolbar); `record` acts on one record, on the record page and on each list row; `record_page` and `record_row` are one of those two only. `selection` acts on many records: the selection bar a grid shows once two or more rows are selected, on every grid view of the object, run once per selected record (the object's `actionLayout.selection` orders that bar). | | **component** | `Enum<'action:button' \| 'action:icon' \| 'action:menu' \| 'action:group'>` | optional | Visual component override | | **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | | **target** | `string` | optional | URL, Script Name, Flow ID, or API Endpoint. Supports $`{param.X}` and $`{ctx.X}` interpolation. For type:'url': an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ (a console route; a record is /apps/APP/OBJECT/record/ID, APP being the app's route segment — see onSuccess.navigate) — every other scheme and a protocol-relative //host are refused. | @@ -532,7 +543,7 @@ const result = ApiMethod.parse(data); | **texts** | `Record` | optional | Texts the action's js body writes into records, keyed by the snake_case key it asks for with ctx.text(KEY, params): `{ message, params? }`. ctx.text answers the sentence in the organization's language (the Localization setting when somebody set it, else the app's i18n.defaultLocale), translated through objects.``._actions.``.texts.``.message (globalActions.``.texts.``.message for an object-less action) with the declared message as the fallback, its holes filled from params. A key not declared here is refused — at save when the body asks for it literally, otherwise at run time. Only a type: 'script' action with a js body declares one | | **operation** | `Enum<'update'>` | optional | The declarative single-record field write, mirroring a list view's `bulkActionDefs`: `'update'` applies `patch` (merged under the collected `params`) to the current record on the data plane AS THE CALLER — never system-elevated — so the caller's permissions, the object's hooks and its validations fire as for a user edit. `type` stays at its default `'script'` (the platform action route the write is performed on); `target`/`body`/`method`/`bodyExtra` are refused beside it. `'delete'` and `'custom'` have no row-level form. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values written to the current record, merged UNDER the user-supplied `params` so a fixed value can be declared without exposing it in the dialog. Written on the data plane as the caller: object permissions, hooks and validations fire as for a user edit. Refused on an action without `operation: 'update'` (it would be silently dropped). | -| **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the view's `bulkActions: ['']` bare-string form); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. A list view wiring a declared action under the other contract is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | +| **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the action placed at `selection`); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. An action placed at `selection` that declares 'aggregate', or a list view wiring a declared action under the other contract, is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | | **params** | `{ name?: string; field?: string; objectOverride?: string; label?: string \| Record; … }[]` | optional | Input parameters required from user — an ActionParam[] DEFINITION array, never a payload map (a static request body goes in `bodyExtra`). A param name (its `name`, or the `field` a field-backed param reads) may repeat only for per-gate variants of ONE input (declarations that differ in `visible` / `requiresFeature`, e.g. one optional and one required); the params check treats the name as `required` only when EVERY declaration of it requires it, and judges its value by the FIRST declaration's shape (`type`, `multiple`, `options`), so keep that shape identical across them. | | **submitText** | `string \| Record` | optional | Label of the submit button in the action's param dialog, the verb the button performs (e.g. "Send", "Log Call"), in place of the default "Confirm" — the default-language string, or an inline locale map; translated at `objects.OBJECT._actions.ACTION.submitText` (`globalActions.ACTION.submitText` for an object-less action). Only on an action with a non-empty `params`: without one no param dialog opens, so it is refused. Not `confirmText`, which is the message of a param-less action's confirm dialog. A blank label is refused. | | **cancelText** | `string \| Record` | optional | Label of the dismiss button on the dialog the action opens before it runs — the confirm dialog of a param-less action that declares `confirmText`, or the param dialog of an action with a non-empty `params` — in place of the default "Cancel". Name what dismissing keeps where the action's own verb is "Cancel …" or "Close …" (e.g. "Keep invitation" beside "Cancel Invitation"). The default-language string, or an inline locale map; translated at `objects.OBJECT._actions.ACTION.cancelText` (`globalActions.ACTION.cancelText` for an object-less action). Only on an action that opens one of those dialogs: with neither `confirmText` nor a non-empty `params` no dialog opens, so it is refused. The dismiss twin of `submitText`, as on `object-form`. A blank label is refused. | @@ -628,12 +639,12 @@ const result = ApiMethod.parse(data); | **label** | `string` | optional | Override label for the extended object | | **pluralLabel** | `string` | optional | Override plural label for the extended object | | **description** | `string` | optional | Override description for the extended object | -| **actionLayout** | `{ list?: object; record?: object }` | optional | The arrangement of the extended object's actions, per scope (`list`, `record`), in the object's own shape. Written only by the object extension of the paired `.custom` package of the App the object belongs to (ADR-0146 D10). An extension in a package that is not a `.custom` package is refused at publish, by `os validate` / `os build` and at install, and the registry merge skips it with a warning; an action that package brings is placed by its own `locations` and `order`. A `.custom` package that is not this object's pair is not applied. Each arm written replaces the arm the object serves for that scope, whole, after every other layer; an arm not written stays as the object gives it, and removing the key, or uninstalling or disabling the package, restores it. | +| **actionLayout** | `{ list?: object; record?: object; selection?: object }` | optional | The arrangement of the extended object's actions, per scope (`list`, `record`), in the object's own shape. Written only by the object extension of the paired `.custom` package of the App the object belongs to (ADR-0146 D10). An extension in a package that is not a `.custom` package is refused at publish, by `os validate` / `os build` and at install, and the registry merge skips it with a warning; an action that package brings is placed by its own `locations` and `order`. A `.custom` package that is not this object's pair is refused at publish (and so at a package duplicate) and at install, the refusal naming the pair, and is not applied where it reaches the registry past them. Each arm written replaces the arm the object serves for that scope, whole, after every other layer; an arm not written stays as the object gives it, and removing the key, or uninstalling or disabling the package, restores it. | | **validations** | `any[]` | optional | Additional validation rules to merge into the target object | | **indexes** | `{ name?: string; fields: string[]; unique?: false \| 'global' \| 'organization' }[]` | optional | Additional indexes to merge into the target object | | **place** | `({ field: string; group: string; after?: string; before?: string } \| { list: string; after?: string; before?: string; label?: string; … } \| { group: object; after?: string; before?: string })[]` | optional | Where the fields, groups and child lists this extension brings go on the extended object. Each entry is one of: `{ field, group, after \| before }` — a field of this extension's own `fields`, into a field group (the extended object's, or one this extension adds), right after or before a member of that group; `{ group: { key, label, … }, after \| before }` — a field group of this extension's own (its `fields` may name only fields this extension adds, its `relatedList` only a child list of this package), right after or before a group of the extended object; `{ list, after \| before, label?, columns? }` — a child list of this package (a child object of the same package that points at the extended object, or object.field), right after or before a tab of the extended object (a relatedLists entry name, a built-in tab included), with that tab's own title and columns (each column a field of the child, judged as a relatedLists entry's columns are). Write `after` or `before`, or neither for the end. An anchor may be an item another placement brings, whatever order the two are written or registered in. An anchor nobody has puts the item at the end of its group, of the groups, or of the tabs (before the approvals and activity-stream tabs); a group that does not exist puts the field among the ungrouped fields. Nothing is dropped. Several items at one anchor follow ascending `priority`, then package name, so every build gives the same order. Placement arranges what the extended object declares: list placements apply when it declares `relatedLists`, group and field placements when it declares `fieldGroups`. Where it declares none, its automatic arrangement stays as it is and the item still shows there: the list in the automatic tab order, with this entry's `label` and `columns` not applied either (write them on the child's own lookup field as `relatedListTitle` / `relatedListColumns`, which apply on every parent), and the field among the fields in declaration order, its `after` / `before` not applied. The boot log names each placement that did not apply, with the object and the package; `os validate` names it too when the extended object is in the same stack. A child list another package brings shows even when the extended object's `relatedLists` does not name it: placed, at its place; unplaced, at the end of the tabs. An extension places only its own items: a field outside its own `fields` is refused here; a field the extended object declares (an owner field this extension redeclares for its display is still the owner's), a group key the extended object declares, and a list (or a group's `relatedList`) that is not a child object of its package are refused at `defineStack` where the objects are known; the merge skips each of them too, with a warning naming whose item it is. A group key another package's extension already adds is not refused: the merge adds it once and names the second. Applied once, by the registry merge, so the record page, the forms and Studio show one arrangement; uninstalling the package removes its items and leaves the extended object's own order as it was. Example: `place: [{ field: 'tax_id', group: 'basic', after: 'industry' }, { list: 'contract', after: 'opportunity', columns: ['name', 'amount'] }]`. | -| **fieldGroups** | `{ key: string; label: string; fields?: string[]; icon?: string; … }[]` | optional | The whole field arrangement of the extended object on the record page, the forms and the preview: an object's `fieldGroups`, in the same shape. Written only by the object extension of the paired `.custom` package of the App the object belongs to (ADR-0146 D10). An extension in a package that is not a `.custom` package is refused at publish, by `os validate` / `os build` and at install, with the prescription to place what it brings with `place`, and the registry merge skips it with a warning. A `.custom` package that is not this object's pair is not refused at those doors: the registry merge does not apply what it writes here, alone or beside the pair, and the boot log names it. A group may list any field the object has, whoever declares it (its owner, another package's extension, or this extension's own `__c` fields), and a group's `relatedList` may place any body table. Written, it replaces the groups the owner declares and the other extensions' `place` entries add, whole: no group, member or order of that arrangement is kept unless written here, and nothing is merged entry by entry. A group that lists `fields` shows exactly its list. A field no group here lists is never dropped: it shows after the last group, whatever group its owner or another extension had put it in. That covers a field a later version of the base adds and a field another package's extension brings. A group that lists no `fields` keeps the object's older rule (the fields whose `group` names it), and a field this extension adds keeps the `group` it declares. Not written, the arrangement stays as the owner and the `place` entries give it, and removing this key, or uninstalling or disabling the package, restores that. To keep a field off the record page and the forms, list it in a group whose `visibleWhen` is false: `hidden` is not a display property a `fieldPatches` entry may set, because it also changes what search indexes and what a form requires. Such a group is presentation only, not access control: the field stays readable and writable through the API. Do not use it for a `required` field that has no default: the create form no longer shows the field while the save still requires it, so the form cannot be submitted. Example: `fieldGroups: [{ key: 'contact', label: 'Contact', fields: ['email', 'phone', 'region__c'] }, { key: 'basic', label: 'Basics', fields: ['name', 'company'] }]`. | -| **relatedLists** | `(string \| { list: string; label?: string; columns?: string[]; hidden?: boolean })[]` | optional | The whole tab list of the extended object's record page, in order: an object's `relatedLists`, in the same shape, whose object form also takes `hidden`. Written only by the object extension of the paired `.custom` package of the App the object belongs to (ADR-0146 D10). An extension in a package that is not a `.custom` package is refused at publish, by `os validate` / `os build` and at install, with the prescription to place what it brings with `place`, and the registry merge skips it with a warning. A `.custom` package that is not this object's pair is not refused at those doors: the registry merge does not apply what it writes here, alone or beside the pair, and the boot log names it. An entry may name any list the object has, whoever brings it (a child object, object.field, or a built-in tab; `{ list, label?, columns?, hidden? }` gives the list its own title and columns, or hides it). Written, it replaces the tab list the owner declares and the other extensions' `place` entries add to, whole, and nothing is merged entry by entry. A tab this list does not name is not hidden, the reverse of an object's own `relatedLists`: where the object had a declared tab list, each of its tabs not named here follows the listed ones (before a trailing approvals / activity-stream run), with the title and columns it had; where the object declared none (every list shows), every list not named here follows the listed ones, and so does the attachments tab. That covers a tab a later version of the base adds and a child list a package installed later brings. Hiding is written: `{ list: 'task', hidden: true }` hides that list's tab, whoever brings the list, and a bare child name hides every list of that child. A list the object's own `relatedLists` hides by leaving it out stays hidden until this list names it. A built-in tab is written only as its bare name, keeps its own rule (approvals and the activity stream follow the listed tabs when unlisted) and cannot be hidden here. `relatedList: false` on the child's field still hides a list whatever this says, and body tables a field group places are the groups' to place. A reader's own tab order and hidden tabs (kept per user) are laid over this list, as over an object's. Not written, the tabs stay as the owner and the `place` entries give them, and removing this key, or uninstalling or disabling the package, restores that. Example: `relatedLists: ['opportunity', { list: 'contact', label: 'People' }, { list: 'task', hidden: true }]`. | +| **fieldGroups** | `{ key: string; label: string; fields?: string[]; icon?: string; … }[]` | optional | The whole field arrangement of the extended object on the record page, the forms and the preview: an object's `fieldGroups`, in the same shape. Written only by the object extension of the paired `.custom` package of the App the object belongs to (ADR-0146 D10). An extension in a package that is not a `.custom` package is refused at publish, by `os validate` / `os build` and at install, with the prescription to place what it brings with `place`. A `.custom` package that is not this object's pair is refused at publish (and so at a package duplicate) and at install, the refusal naming the object's pair; `os validate` / `os build` cannot read the installed packages and judge it by suffix alone. What reaches the registry past these doors is not applied, alone or beside the pair, and the boot log names it. A group may list any field the object has, whoever declares it (its owner, another package's extension, or this extension's own `__c` fields), and a group's `relatedList` may place any body table. Written, it replaces the groups the owner declares and the other extensions' `place` entries add, whole: no group, member or order of that arrangement is kept unless written here, and nothing is merged entry by entry. A group that lists `fields` shows exactly its list. A field no group here lists is never dropped: it shows after the last group, whatever group its owner or another extension had put it in. That covers a field a later version of the base adds and a field another package's extension brings. A group that lists no `fields` keeps the object's older rule (the fields whose `group` names it), and a field this extension adds keeps the `group` it declares. Not written, the arrangement stays as the owner and the `place` entries give it, and removing this key, or uninstalling or disabling the package, restores that. To keep a field off the record page and the forms, list it in a group whose `visibleWhen` is false: `hidden` is not a display property a `fieldPatches` entry may set, because it also changes what search indexes and what a form requires. Such a group is presentation only, not access control: the field stays readable and writable through the API. Do not use it for a `required` field that has no default: the create form no longer shows the field while the save still requires it, so the form cannot be submitted. Example: `fieldGroups: [{ key: 'contact', label: 'Contact', fields: ['email', 'phone', 'region__c'] }, { key: 'basic', label: 'Basics', fields: ['name', 'company'] }]`. | +| **relatedLists** | `(string \| { list: string; label?: string; columns?: string[]; hidden?: boolean })[]` | optional | The whole tab list of the extended object's record page, in order: an object's `relatedLists`, in the same shape, whose object form also takes `hidden`. Written only by the object extension of the paired `.custom` package of the App the object belongs to (ADR-0146 D10). An extension in a package that is not a `.custom` package is refused at publish, by `os validate` / `os build` and at install, with the prescription to place what it brings with `place`. A `.custom` package that is not this object's pair is refused at publish (and so at a package duplicate) and at install, the refusal naming the object's pair; `os validate` / `os build` cannot read the installed packages and judge it by suffix alone. What reaches the registry past these doors is not applied, alone or beside the pair, and the boot log names it. An entry may name any list the object has, whoever brings it (a child object, object.field, or a built-in tab; `{ list, label?, columns?, hidden? }` gives the list its own title and columns, or hides it). Written, it replaces the tab list the owner declares and the other extensions' `place` entries add to, whole, and nothing is merged entry by entry. A tab this list does not name is not hidden, the reverse of an object's own `relatedLists`: where the object had a declared tab list, each of its tabs not named here follows the listed ones (before a trailing approvals / activity-stream run), with the title and columns it had; where the object declared none (every list shows), every list not named here follows the listed ones, and so does the attachments tab. That covers a tab a later version of the base adds and a child list a package installed later brings. Hiding is written: `{ list: 'task', hidden: true }` hides that list's tab, whoever brings the list, and a bare child name hides every list of that child. A list the object's own `relatedLists` hides by leaving it out stays hidden until this list names it. A built-in tab is written only as its bare name, keeps its own rule (approvals and the activity stream follow the listed tabs when unlisted) and cannot be hidden here. `relatedList: false` on the child's field still hides a list whatever this says, and body tables a field group places are the groups' to place. A reader's own tab order and hidden tabs (kept per user) are laid over this list, as over an object's. Not written, the tabs stay as the owner and the `place` entries give them, and removing this key, or uninstalling or disabling the package, restores that. Example: `relatedLists: ['opportunity', { list: 'contact', label: 'People' }, { list: 'task', hidden: true }]`. | | **priority** | `integer` | optional (default: `200`) | Merge priority (higher = applied later) | ### Nested Shape: `ObjectExtension.fields[string]` @@ -685,7 +696,7 @@ const result = ApiMethod.parse(data); | **lookupColumns** | `(string \| { field: string; label?: string; width?: string; type?: string })[]` | optional | Explicit columns for the record-picker table; auto-derived from the referenced object when omitted. | | **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). | | **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | -| **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | +| **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For a reference field (`lookup`, `master_detail`, `user`, `tree`) it scopes the candidate query and an import's lookup of the column by equality on the referenced object (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is reference-only), so that key must be a stored field of the referenced object, never one computed on read. For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. CURRENCY RULE: an amount of money (a `currency` field, or a `formula` returning `currency`) is copied only into a target in the same currency, both in the home currency or both naming the same ISO 4217 code (a `fixed` code, or the code the record or its `master_detail` parent holds). Otherwise the target is left as it is and the form says why, naming both currencies and the picked amount; nothing is converted. A `number` carries no currency and copies as before. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy, under the same currency rule; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | @@ -746,6 +757,7 @@ const result = ApiMethod.parse(data); | :--- | :--- | :--- | :--- | | **list** | `{ pinned: string[]; more?: string[] }` | optional | The list scope's arrangement: actions of the object placed at `list`, as drawn on the list page toolbar, and `$import` / `$export` as pinned buttons (not pinned, they stay in the page's own Import / Export menu). Omit to draw it as before. | | **record** | `{ pinned: string[]; more?: string[] }` | optional | The record scope's arrangement: actions of the object placed at `record` or `record_page`, as drawn in the record header (record page, side preview, a phone's bottom bar). The same order leads the actions a grid row already offers, adding none: the row's ⋮ menu, its right-click menu and, on a list page, the selection bar's actions for one selected record (`pinned` names first, then `more` names, then the rest as before). The selection bar's buttons, at most three, are the first of that order; a row's own inline button does not change. Omit to draw each as before. | +| **selection** | `{ pinned: string[]; more?: string[] }` | optional | The selection scope's arrangement: actions of the object placed at `selection`, as drawn on the selection bar a grid shows once two or more rows are selected, on every grid view of the object. `pinned` names the bar's buttons, in order; the rest, Delete included, are in the bar's 「More」: a view's own `bulkActionDefs` first, then the actions `more` names, then the others. Omit to draw a view's own `bulkActionDefs` first and then the actions in their default order, the first three entries as buttons. | ### Nested Shape: `ObjectExtension.indexes[number]` @@ -1033,6 +1045,18 @@ External datasource binding (ADR-0015) * `developerEditionCreate` +--- + +## ObjectFieldTab + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **key** | `string` | ✅ | The tab's key (snake_case). The record page addresses the tab as fields:``. | +| **groups** | `string[]` | ✅ | The field groups this tab holds: keys of this object's fieldGroups, in the order the tab draws them. The first one's label and icon title the tab. | + + --- ## ObjectOwnershipEnum diff --git a/content/docs/references/data/validation.mdx b/content/docs/references/data/validation.mdx index eac8ee194c5..2afcd8b5295 100644 --- a/content/docs/references/data/validation.mdx +++ b/content/docs/references/data/validation.mdx @@ -133,7 +133,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -158,7 +158,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -181,7 +181,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -206,7 +206,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -231,7 +231,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -255,7 +255,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -279,7 +279,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -302,7 +302,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -327,7 +327,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -352,7 +352,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -376,7 +376,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -405,7 +405,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -434,7 +434,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -464,7 +464,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -493,7 +493,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -521,7 +521,7 @@ const result = ConditionalValidationSchema.parse(data); | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -559,7 +559,7 @@ This schema accepts one of the following structures: | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -588,7 +588,7 @@ This schema accepts one of the following structures: | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -619,7 +619,7 @@ This schema accepts one of the following structures: | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -650,7 +650,7 @@ This schema accepts one of the following structures: | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -680,7 +680,7 @@ This schema accepts one of the following structures: | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | @@ -710,7 +710,7 @@ This schema accepts one of the following structures: | **priority** | `integer` | optional (default: `100`) | Execution priority (lower runs first, default: 100) | | **tags** | `string[]` | optional | Categorization tags (e.g., "compliance", "billing") | | **severity** | `Enum<'error' \| 'warning' \| 'info'>` | optional (default: `"error"`) | | -| **message** | `string` | ✅ | Error message to display to the user | +| **message** | `string` | ✅ | The sentence a refused write returns to the person: a `{{ }}` template (ADR-0032 §3) over the judged record. A hole names one of the object's own fields, one segment deep, under `record` (the merged record the rule judged) or, on update, `previous` (the stored row), with an optional whitelisted formatter: `Total {{ record.total_price \| currency }} is below what was received ({{ record.received_amount \| currency }}).` A single-brace `{…}` token, a hole over any other root or field, and logic in a hole are refused at `objectstack validate`, `compile` and the publish gate. Stays a string; translate it at `objects.OBJECT._validations.RULE.message`, which reads the same holes. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | | **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 04a0cd9dd38..c9e2b5de14e 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1744 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1750 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -22,10 +22,10 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | -| [AI Protocol](/docs/references/ai) | 18 | 104 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | -| [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 37 | 529 | REST contracts, endpoints, routing, realtime, batch, discovery. | +| [AI Protocol](/docs/references/ai) | 18 | 108 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 37 | 528 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | -| [Data Protocol](/docs/references/data) | 35 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | +| [Data Protocol](/docs/references/data) | 35 | 198 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | | [Integration Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/integration) | 1 | 23 | The single connector protocol (ADR-0097) — catalog descriptors and provider-bound instances. | | [Kernel Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/kernel) | 30 | 153 | Plugin lifecycle and manifests, capabilities and security, metadata loading, service registry. | @@ -35,14 +35,14 @@ counts are sums of the rows they head. Regenerate with | [Shared Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/shared) | 10 | 31 | Primitives used across every protocol — identifiers, HTTP, expressions, error maps, enums. | | [Studio Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | -| [UI Protocol](/docs/references/ui) | 17 | 186 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **224** | **1744** | 14 protocol modules | +| [UI Protocol](/docs/references/ui) | 17 | 188 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | +| **Total** | **224** | **1750** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **18 pages, 104 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **18 pages, 108 schemas** Agents, tools, skills, RAG and knowledge sources, model registry, conversations. @@ -51,12 +51,11 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | [`agent.zod.ts`](/docs/references/ai/agent) | `AIModelConfig`, `Agent`, `StructuredOutputConfig`, `StructuredOutputFormat`, `TransformPipelineStep` | | [`ai-context.zod.ts`](/docs/references/ai/ai-context) | `AiContext`, `AiContextBody`, `AiContextRelated`, `AiContextRelatedWhere` | | [`ask-question.zod.ts`](/docs/references/ai/ask-question) | `AskQuestion`, `AskQuestionEnvelope`, `AskQuestionOption` | -| [`build-progress.zod.ts`](/docs/references/ai/build-progress) | `BuildProgressFrame`, `BuildProgressPhase` | | [`conversation.zod.ts`](/docs/references/ai/conversation) | `CodeContent`, `ConversationAnalytics`, `ConversationContext`, `ConversationMessage`, `ConversationSession`, `ConversationSummary`, `FileContent`, `FunctionCall`, `ImageContent`, `MessageContent`, `MessageContentType`, `MessagePruningEvent`, `MessageRole`, `TextContent`, `TokenBudgetConfig`, `TokenBudgetStrategy`, `TokenUsageStats`, `ToolCall` | | [`dataset-tools.zod.ts`](/docs/references/ai/dataset-tools) | `DatasetNextStep`, `DatasetNextStepDecision`, `DatasetProvenance`, `DatasetTermCandidate`, `DatasetTermMatch`, `DatasetTermMatchedOn`, `DatasetToolCatalogDimension`, `DatasetToolCatalogEntry`, `DatasetToolCatalogMeasure`, `ListDatasetsInput`, `ListDatasetsOutput`, `QueryDatasetInput`, `QueryDatasetOutput` | | [`draft-review.zod.ts`](/docs/references/ai/draft-review) | `DraftReviewItem`, `DraftReviewLinks`, `DraftReviewList`, `DraftReviewVerdict`, `DraftReviewVerdictRefusal` | | [`knowledge-document.zod.ts`](/docs/references/ai/knowledge-document) | `KnowledgeChunk`, `KnowledgeDocument`, `KnowledgeHit` | -| [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `KnowledgeRefreshPolicy`, `KnowledgeSource`, `KnowledgeSplit`, `KnowledgeSplitStrategy`, `ObjectKnowledgeSource` | +| [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `KnowledgeAffinityCaller`, `KnowledgeAffinityEntry`, `KnowledgeAffinityMode`, `KnowledgeRefreshPolicy`, `KnowledgeRetrieval`, `KnowledgeRetrievalMode`, `KnowledgeSource`, `KnowledgeSplit`, `KnowledgeSplitStrategy`, `ObjectKnowledgeSource` | | [`mcp.zod.ts`](/docs/references/ai/mcp) | `MCPApprovalPolicy`, `MCPServerRef`, `MCPToolBinding`, `MCPTransport`, `McpActionNamespace`, `McpListedActionAddress` | | [`model-registry.zod.ts`](/docs/references/ai/model-registry) | `ModelCapability`, `ModelConfig`, `ModelLimits`, `ModelPricing`, `ModelProvider`, `ModelRegistry`, `ModelRegistryEntry`, `ModelSelectionCriteria`, `PromptTemplate`, `PromptVariable` | | [`object-query-source.zod.ts`](/docs/references/ai/object-query-source) | `ObjectQuerySource` | @@ -65,13 +64,14 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | [`skill.zod.ts`](/docs/references/ai/skill) | `Skill`, `SkillTriggerCondition` | | [`solution-blueprint.zod.ts`](/docs/references/ai/solution-blueprint) | `BlueprintApp`, `BlueprintCondition`, `BlueprintDashboard`, `BlueprintField`, `BlueprintNavItem`, `BlueprintObject`, `BlueprintSeed`, `BlueprintSummaryOperations`, `BlueprintView`, `BlueprintWidgetCondition`, `SolutionBlueprint`, `SolutionBlueprintStrict` | | [`tool.zod.ts`](/docs/references/ai/tool) | `Tool` | +| [`turn-end.zod.ts`](/docs/references/ai/turn-end) | `TurnEnd` | | [`usage.zod.ts`](/docs/references/ai/usage) | `AIUsageRecord`, `TokenUsage` | --- ## API Protocol -**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **37 pages, 529 schemas** +**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **37 pages, 528 schemas** REST contracts, endpoints, routing, realtime, batch, discovery. @@ -99,7 +99,7 @@ REST contracts, endpoints, routing, realtime, batch, discovery. | [`odata.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/odata.md) | `ODataConfig`, `ODataError`, `ODataFilterFunction`, `ODataMetadata`, `ODataQuery`, `ODataResponse` | | [`package-api.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/package-api.md) | `GetInstalledPackageRequest`, `ListInstalledPackagesRequest`, `PackageApiErrorCode`, `PackageInstallBody`, `PackageInstallManifest`, `PackageInstallRequest`, `PackageInstallResponse`, `PackagePathParams`, `PackageRollbackRequest`, `PackageUpgradeRequest`, `PackageUpgradeResponse`, `ResolveDependenciesRequest`, `ResolveDependenciesResponse`, `UninstallPackageApiRequest`, `UninstallPackageApiResponse`, `UploadArtifactRequest`, `UploadArtifactResponse` | | [`package-api-assembled.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/package-api-assembled.md) | `AssembledInstalledPackage`, `GetInstalledPackageResponse`, `InstalledPackageAtEitherStage`, `ListInstalledPackagesResponse` | -| [`package-lifecycle.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/package-lifecycle.md) | `DiscardPackageDraftsResponse`, `DuplicatePackageResponse`, `EnsureCustomizationPackageRequest`, `EnsureCustomizationPackageResponse`, `GetPackageCustomizationsRequest`, `GetPackageCustomizationsResponse`, `ImportUnmanagedPackageRequest`, `ImportUnmanagedPackageResponse`, `ListPackageCommitsResponse`, `MoveIntoPackageItem`, `MoveIntoPackageMovedItem`, `MoveIntoPackageRefusedItem`, `MoveIntoPackageRequest`, `MoveIntoPackageResponse`, `PackageExportBundle`, `PackageExportManifest`, `PackagePublishResult`, `ReassignOrphanedMetadataResponse`, `RevertPackageCommitResponse`, `RollbackToPackageCommitResponse` | +| [`package-lifecycle.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/package-lifecycle.md) | `DiscardPackageDraftsResponse`, `DuplicatePackageResponse`, `EnsureCustomizationPackageRequest`, `EnsureCustomizationPackageResponse`, `GetPackageCustomizationsRequest`, `GetPackageCustomizationsResponse`, `ImportUnmanagedPackageRequest`, `ImportUnmanagedPackageResponse`, `ListPackageCommitsResponse`, `MoveIntoPackageItem`, `MoveIntoPackageMovedItem`, `MoveIntoPackageRefusedItem`, `MoveIntoPackageRequest`, `MoveIntoPackageResponse`, `PackageExportBundle`, `PackageExportManifest`, `PackagePublishResult`, `RevertPackageCommitResponse`, `RollbackToPackageCommitResponse` | | [`plugin-rest-api.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/plugin-rest-api.md) | `ErrorHandlingConfig`, `OpenApiGenerationConfig`, `RequestValidationConfig`, `ResponseEnvelopeConfig`, `RestApiEndpoint`, `RestApiPluginConfig`, `RestApiRouteCategory`, `RestApiRouteRegistration`, `ValidationMode` | | [`protocol.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/protocol.md) | `AiAgentCapabilities`, `AiAgentChatRequest`, `AiAgentSummary`, `AiAgentsResponse`, `AiChatRequest`, `AiChatResponse`, `AiCompleteRequest`, `AiConversation`, `AiConversationMessage`, `AiMessage`, `AiModelsResponse`, `AiPendingAction`, `AiPendingActionStatus`, `AiStreamChunk`, `ApproveAiPendingActionResponse`, `AuditMetaItemRequest`, `AuditMetaItemResponse`, `AutomationActionsResponse`, `AutomationTriggerRequest`, `AutomationTriggerResponse`, `BatchDataRequest`, `BatchDataResponse`, `BuildProbeReport`, `CheckPermissionRequest`, `CheckPermissionResponse`, `CloneDataResponse`, `CreateAiConversationRequest`, `CreateDataRequest`, `CreateDataResponse`, `CreateManyDataRequest`, `CreateManyDataResponse`, `DeleteDataRequest`, `DeleteDataResponse`, `DeleteManyDataRequest`, `DeleteManyDataResponse`, `DeleteMetaItemRequest`, `DeleteMetaItemResponse`, `DestructiveChangeIssue`, `DiffMetaItemRequest`, `DiffMetaItemResponse`, `DisablePackageRequest`, `DisablePackageResponse`, `EnablePackageRequest`, `EnablePackageResponse`, `FieldStillShownBy`, `FindDataRequest`, `FindDataResponse`, `FindReferencesToMetaResponse`, `FlowRegistration`, `FlowRegistrationRefusal`, `GetDataRequest`, `GetDataResponse`, `GetDiscoveryRequest`, `GetDiscoveryResponse`, `GetEffectivePermissionsRequest`, `GetEffectivePermissionsResponse`, `GetFieldLabelsRequest`, `GetFieldLabelsResponse`, `GetLocalesRequest`, `GetLocalesResponse`, `GetMetaDiagnosticsResponse`, `GetMetaItemCachedRequest`, `GetMetaItemCachedResponse`, `GetMetaItemLayeredRequest`, `GetMetaItemLayeredResponse`, `GetMetaItemRequest`, `GetMetaItemResponse`, `GetMetaItemsRequest`, `GetMetaItemsResponse`, `GetMetaTypesRequest`, `GetMetaTypesResponse`, `GetNotificationPreferencesRequest`, `GetNotificationPreferencesResponse`, `GetObjectPermissionsRequest`, `GetObjectPermissionsResponse`, `GetPackageRequest`, `GetPackageResponse`, `GetPresenceRequest`, `GetPresenceResponse`, `GetPublishedMetaItemResponse`, `GetRecordFieldAccessResponse`, `GetTranslationsRequest`, `GetTranslationsResponse`, `GetUiViewRequest`, `GetUiViewResponse`, `HistoryMetaItemRequest`, `HistoryMetaItemResponse`, `HttpFindQueryParams`, `InstallPackageRequest`, `InstallPackageResponse`, `ListAiConversationsRequest`, `ListAiConversationsResponse`, `ListAiPendingActionsRequest`, `ListAiPendingActionsResponse`, `ListDraftsResponse`, `ListNotificationsRequest`, `ListNotificationsResponse`, `ListPackagesRequest`, `ListPackagesResponse`, `MarkAllNotificationsReadRequest`, `MarkAllNotificationsReadResponse`, `MarkNotificationsReadRequest`, `MarkNotificationsReadResponse`, `MetadataAuthoringClient`, `MetadataAuthoringSurface`, `MetadataConflictError`, `Notification`, `NotificationPreferences`, `PublicFormSubmitResponse`, `PublishMetaItemRequest`, `PublishMetaItemResponse`, `PublishPackageDraftsRequest`, `PublishPackageDraftsResponse`, `RealtimeConnectRequest`, `RealtimeConnectResponse`, `RealtimeDisconnectRequest`, `RealtimeDisconnectResponse`, `RealtimeSubscribeRequest`, `RealtimeSubscribeResponse`, `RealtimeUnsubscribeRequest`, `RealtimeUnsubscribeResponse`, `RegisterDeviceRequest`, `RegisterDeviceResponse`, `RejectAiPendingActionResponse`, `RollbackMetaItemRequest`, `RollbackMetaItemResponse`, `RuntimeAuthoringIssue`, `RuntimeBuildIssue`, `SaveMetaItemRequest`, `SaveMetaItemResponse`, `SearchAllHit`, `SearchAllPageHit`, `SearchAllResponse`, `SeedAppliedIdList`, `SeedAppliedLanded`, `SetPresenceRequest`, `SetPresenceResponse`, `UninstallPackageRequest`, `UninstallPackageResponse`, `UnregisterDeviceRequest`, `UnregisterDeviceResponse`, `UpdateAiConversationRequest`, `UpdateDataRequest`, `UpdateDataResponse`, `UpdateManyDataRequest`, `UpdateManyDataResponse`, `UpdateNotificationPreferencesRequest`, `UpdateNotificationPreferencesResponse`, `ValidateDataIssue`, `ValidateDataRequest`, `ValidateDataResponse` | | [`push-delivery.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/push-delivery.md) | `PushDeliveryData`, `PushRoute` | @@ -146,7 +146,7 @@ Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execu ## Data Protocol -**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 197 schemas** +**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 198 schemas** Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. @@ -179,7 +179,7 @@ Objects, fields, queries, filters, datasources and drivers — the ObjectQL laye | [`hook-body.zod.ts`](/docs/references/data/hook-body) | `ExpressionBody`, `HookBody`, `HookBodyCapability`, `ScriptBody` | | [`hook-body-doors.zod.ts`](/docs/references/data/hook-body-doors) | `BodyActivityAppendInput`, `BodyDoorRecordRef`, `BodyMailSendInput` | | [`mapping.zod.ts`](/docs/references/data/mapping) | `ImportFieldMapping`, `Mapping`, `TransformType` | -| [`object.zod.ts`](/docs/references/data/object) | `ApiMethod`, `ApiOperation`, `Index`, `Lifecycle`, `LifecycleClass`, `Object`, `ObjectAccessConfig`, `ObjectCapabilities`, `ObjectExtension`, `ObjectExtensionFieldPlacement`, `ObjectExtensionGroupPlacement`, `ObjectExtensionListPlacement`, `ObjectExtensionPlacement`, `ObjectExtensionRelatedListEntry`, `ObjectExtensionRelatedListEntryObject`, `ObjectExternalBinding`, `ObjectFieldGroup`, `ObjectOwnershipEnum`, `ObjectRequiredPermissions`, `PerOperationRequiredPermissions`, `RelatedListEntry`, `RelatedListEntryObject`, `RowCrudActionOverride`, `TenancyConfig` | +| [`object.zod.ts`](/docs/references/data/object) | `ApiMethod`, `ApiOperation`, `Index`, `Lifecycle`, `LifecycleClass`, `Object`, `ObjectAccessConfig`, `ObjectCapabilities`, `ObjectExtension`, `ObjectExtensionFieldPlacement`, `ObjectExtensionGroupPlacement`, `ObjectExtensionListPlacement`, `ObjectExtensionPlacement`, `ObjectExtensionRelatedListEntry`, `ObjectExtensionRelatedListEntryObject`, `ObjectExternalBinding`, `ObjectFieldGroup`, `ObjectFieldTab`, `ObjectOwnershipEnum`, `ObjectRequiredPermissions`, `PerOperationRequiredPermissions`, `RelatedListEntry`, `RelatedListEntryObject`, `RowCrudActionOverride`, `TenancyConfig` | | [`picklist.zod.ts`](/docs/references/data/picklist) | `Picklist`, `PicklistExtension`, `PicklistServedField` | | [`query.zod.ts`](/docs/references/data/query) | `AggregationFunction`, `AggregationNode`, `DateGranularity`, `FieldNode`, `FullTextSearch`, `GroupByNode`, `Query`, `SortNode` | | [`recycle-bin.zod.ts`](/docs/references/data/recycle-bin) | `RecycleBinClearedReference`, `RecycleBinEntry`, `RecycleBinRetentionDays`, `RecycleBinRetentionDaysEnv`, `RecycleBinSnapshot`, `RecycleBinSnapshotRow` | @@ -392,13 +392,13 @@ The runtime environment — logging, jobs, cache, metrics, notifications, i18n a ## UI Protocol -**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **17 pages, 186 schemas** +**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **17 pages, 188 schemas** Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | File | Schemas | | :--- | :--- | -| [`action.zod.ts`](/docs/references/ui/action) | `Action`, `ActionAi`, `ActionLocation`, `ActionParam`, `ActionRefusal`, `ActionText`, `ActionType`, `InlineAction` | +| [`action.zod.ts`](/docs/references/ui/action) | `Action`, `ActionAi`, `ActionLocation`, `ActionParam`, `ActionRefusal`, `ActionText`, `ActionType`, `InlineAction`, `PageComponentActionLocation`, `RecordQuickActionsLocation` | | [`action-params.zod.ts`](/docs/references/ui/action-params) | `ActionSession` | | [`ai-chat-nav-params.zod.ts`](/docs/references/ui/ai-chat-nav-params) | `AiChatNavParams` | | [`app.zod.ts`](/docs/references/ui/app) | `ActionNavItem`, `App`, `AppBranding`, `AppContextSelector`, `AppLandingEntry`, `ComponentNavItem`, `DashboardNavItem`, `DocNavItem`, `GroupNavItem`, `NavigationArea`, `NavigationContribution`, `NavigationItem`, `ObjectNavItem`, `PageNavItem`, `ReportNavItem`, `UrlNavItem` | diff --git a/content/docs/references/security/explain.mdx b/content/docs/references/security/explain.mdx index baf3b4fb6eb..25793fb5739 100644 --- a/content/docs/references/security/explain.mdx +++ b/content/docs/references/security/explain.mdx @@ -132,6 +132,7 @@ ADR-0095 D2 posture rung — PLATFORM_ADMIN crosses the tenant wall where object | **verdict** | `Enum<'grants' \| 'denies' \| 'narrows' \| 'widens' \| 'neutral' \| 'not_applicable'>` | ✅ | | | **detail** | `string` | ✅ | | | **contributors** | `{ kind: Enum<'permission_set' \| 'position' \| 'system'>; name: string; via?: string; state?: Enum<'active' \| 'expired' \| 'deactivated'> }[]` | optional (default: `[]`) | | +| **fieldChannels** | `{ field: string; read?: object; edit?: object }[]` | optional | fls layer only: per field, the channel that cast the winning read and edit vote — own_row, other_set_row (re-opens a field another held set hides), view_all_fields (read axis only) or default (no held set names the field) — with the voting set names. | | **record** | `{ outcome: Enum<'admitted' \| 'excluded' \| 'not_evaluated'>; rowFilter?: any; matchesRecord?: boolean; rules?: object[]; … }` | optional | Row-level determination for the specific record under explanation; set only for record-grained requests. | ### Nested Shape: `ExplainDecision.record` @@ -164,8 +165,17 @@ ADR-0095 D2 posture rung — PLATFORM_ADMIN crosses the tenant wall where object | **verdict** | `Enum<'grants' \| 'denies' \| 'narrows' \| 'widens' \| 'neutral' \| 'not_applicable'>` | ✅ | | | **detail** | `string` | ✅ | | | **contributors** | `{ kind: Enum<'permission_set' \| 'position' \| 'system'>; name: string; via?: string; state?: Enum<'active' \| 'expired' \| 'deactivated'> }[]` | optional (default: `[]`) | | +| **fieldChannels** | `{ field: string; read?: object; edit?: object }[]` | optional | fls layer only: per field, the channel that cast the winning read and edit vote — own_row, other_set_row (re-opens a field another held set hides), view_all_fields (read axis only) or default (no held set names the field) — with the voting set names. | | **record** | `{ outcome: Enum<'admitted' \| 'excluded' \| 'not_evaluated'>; rowFilter?: any; matchesRecord?: boolean; rules?: object[]; … }` | optional | Row-level determination for the specific record under explanation; set only for record-grained requests. | +### Nested Shape: `ExplainLayer.fieldChannels[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **field** | `string` | ✅ | The field name, without the object prefix. | +| **read** | `{ channel: Enum<'own_row' \| 'other_set_row' \| 'view_all_fields' \| 'default'>; sets?: string[] }` | optional | The channel that cast the winning read vote; present when the field merge kept the read vote open and the value is served whole, absent otherwise. The object grant is the object_crud layer's answer. | +| **edit** | `{ channel: Enum<'own_row' \| 'other_set_row' \| 'default'>; sets?: string[] }` | optional | The channel that cast the winning edit vote; present when the field merge kept the edit vote open, absent otherwise. The object grant is the object_crud layer's answer. | + ### Nested Shape: `ExplainLayer.record` | Property | Type | Required | Description | diff --git a/content/docs/references/ui/action.mdx b/content/docs/references/ui/action.mdx index 7213e69513f..b362c01d8b6 100644 --- a/content/docs/references/ui/action.mdx +++ b/content/docs/references/ui/action.mdx @@ -28,8 +28,8 @@ declared inline on a page element instead of registered by name). ## TypeScript Usage ```typescript -import { ActionSchema, ActionAiSchema, ActionLocationSchema, ActionParamSchema, ActionRefusalSchema, ActionTextSchema, ActionType, InlineActionSchema } from '@objectstack/spec/ui'; -import type { Action, ActionAi, ActionLocation, ActionParam, ActionRefusal, ActionText, ActionType, InlineAction } from '@objectstack/spec/ui'; +import { ActionSchema, ActionAiSchema, ActionLocationSchema, ActionParamSchema, ActionRefusalSchema, ActionTextSchema, ActionType, InlineActionSchema, PageComponentActionLocationSchema, RecordQuickActionsLocationSchema } from '@objectstack/spec/ui'; +import type { Action, ActionAi, ActionLocation, ActionParam, ActionRefusal, ActionText, ActionType, InlineAction, PageComponentActionLocation, RecordQuickActionsLocation } from '@objectstack/spec/ui'; // Validate data const result = ActionSchema.parse(data); @@ -48,7 +48,7 @@ const result = ActionSchema.parse(data); | **description** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object } \| string \| Record` | optional | Explanatory line shown under the title in the action's param dialog. Carries the confirm question for an action that collects params (one dialog, not two). Not the LLM-facing `ai.description`. It is a `template` slot (ADR-0032): a bare string is shorthand for `{ dialect: 'template', source }`, and text with no hole is shown as written. Holes are `{{ path }}` or `{{ path \| formatter[:arg] }}` over `record`, the record the action runs against (the clicked row on a list, else the page's record); the values the dialog collects are not bound, since the line shows before they exist. Formatters come from the template engine's whitelist (`TEMPLATE_FORMATTERS`, `@objectstack/formula`); a hole holds no logic (no CEL, no arithmetic). Example: 'Choose the new role for `{{ record.name }}`.'. A hole over any other root, a `${…}` or single-brace `{x}` token (each named with its `{{ }}` spelling), a hole holding logic or an unknown formatter, and a blank sentence are named and refused at `objectstack validate`, `compile` and the publish gate; the text still parses, so a stored one loads until its next save. An inline locale map (`{ en, "zh-CN" }`) is accepted too, each value such a sentence. | | **objectName** | `string` | optional | Target object this action belongs to. When set, the action is auto-merged into the object's actions array by defineStack(). | | **icon** | `string` | optional | Icon name | -| **locations** | `Enum<'list' \| 'record' \| 'record_page' \| 'record_row' \| 'record_related' \| 'record_section'>[]` | optional | Locations where this action is visible. `record_section` is drawn only by an authored record page block that renders it; the standard record page (on a phone, in the side preview, and for an object with no authored page) does not draw it, so an action that must reach every surface adds `record_page` as well, with `component: 'action:menu'` to sit in the record page's ⋯ menu rather than be a header button. `list` acts on no record (the list page toolbar); `record` acts on one record, on the record page and on each list row; `record_page` and `record_row` are one of those two only. | +| **locations** | `Enum<'list' \| 'record' \| 'record_page' \| 'record_row' \| 'record_related' \| 'record_section' \| 'selection'>[]` | optional | Locations where this action is visible. `record_section` is drawn only by an authored record page block that renders it; the standard record page (on a phone, in the side preview, and for an object with no authored page) does not draw it, so an action that must reach every surface adds `record_page` as well, with `component: 'action:menu'` to sit in the record page's ⋯ menu rather than be a header button. `list` acts on no record (the list page toolbar); `record` acts on one record, on the record page and on each list row; `record_page` and `record_row` are one of those two only. `selection` acts on many records: the selection bar a grid shows once two or more rows are selected, on every grid view of the object, run once per selected record (the object's `actionLayout.selection` orders that bar). | | **component** | `Enum<'action:button' \| 'action:icon' \| 'action:menu' \| 'action:group'>` | optional | Visual component override | | **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | | **target** | `string` | optional | URL, Script Name, Flow ID, or API Endpoint. Supports $`{param.X}` and $`{ctx.X}` interpolation. For type:'url': an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ (a console route; a record is /apps/APP/OBJECT/record/ID, APP being the app's route segment — see onSuccess.navigate) — every other scheme and a protocol-relative //host are refused. | @@ -58,7 +58,7 @@ const result = ActionSchema.parse(data); | **texts** | `Record` | optional | Texts the action's js body writes into records, keyed by the snake_case key it asks for with ctx.text(KEY, params): `{ message, params? }`. ctx.text answers the sentence in the organization's language (the Localization setting when somebody set it, else the app's i18n.defaultLocale), translated through objects.``._actions.``.texts.``.message (globalActions.``.texts.``.message for an object-less action) with the declared message as the fallback, its holes filled from params. A key not declared here is refused — at save when the body asks for it literally, otherwise at run time. Only a type: 'script' action with a js body declares one | | **operation** | `Enum<'update'>` | optional | The declarative single-record field write, mirroring a list view's `bulkActionDefs`: `'update'` applies `patch` (merged under the collected `params`) to the current record on the data plane AS THE CALLER — never system-elevated — so the caller's permissions, the object's hooks and its validations fire as for a user edit. `type` stays at its default `'script'` (the platform action route the write is performed on); `target`/`body`/`method`/`bodyExtra` are refused beside it. `'delete'` and `'custom'` have no row-level form. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values written to the current record, merged UNDER the user-supplied `params` so a fixed value can be declared without exposing it in the dialog. Written on the data plane as the caller: object permissions, hooks and validations fire as for a user edit. Refused on an action without `operation: 'update'` (it would be silently dropped). | -| **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the view's `bulkActions: ['']` bare-string form); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. A list view wiring a declared action under the other contract is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | +| **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the action placed at `selection`); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. An action placed at `selection` that declares 'aggregate', or a list view wiring a declared action under the other contract, is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | | **params** | `{ name?: string; field?: string; objectOverride?: string; label?: string \| Record; … }[]` | optional | Input parameters required from user — an ActionParam[] DEFINITION array, never a payload map (a static request body goes in `bodyExtra`). A param name (its `name`, or the `field` a field-backed param reads) may repeat only for per-gate variants of ONE input (declarations that differ in `visible` / `requiresFeature`, e.g. one optional and one required); the params check treats the name as `required` only when EVERY declaration of it requires it, and judges its value by the FIRST declaration's shape (`type`, `multiple`, `options`), so keep that shape identical across them. | | **submitText** | `string \| Record` | optional | Label of the submit button in the action's param dialog, the verb the button performs (e.g. "Send", "Log Call"), in place of the default "Confirm" — the default-language string, or an inline locale map; translated at `objects.OBJECT._actions.ACTION.submitText` (`globalActions.ACTION.submitText` for an object-less action). Only on an action with a non-empty `params`: without one no param dialog opens, so it is refused. Not `confirmText`, which is the message of a param-less action's confirm dialog. A blank label is refused. | | **cancelText** | `string \| Record` | optional | Label of the dismiss button on the dialog the action opens before it runs — the confirm dialog of a param-less action that declares `confirmText`, or the param dialog of an action with a non-empty `params` — in place of the default "Cancel". Name what dismissing keeps where the action's own verb is "Cancel …" or "Close …" (e.g. "Keep invitation" beside "Cancel Invitation"). The default-language string, or an inline locale map; translated at `objects.OBJECT._actions.ACTION.cancelText` (`globalActions.ACTION.cancelText` for an object-less action). Only on an action that opens one of those dialogs: with neither `confirmText` nor a non-empty `params` no dialog opens, so it is refused. The dismiss twin of `submitText`, as on `object-form`. A blank label is refused. | @@ -266,6 +266,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities * `record_row` * `record_related` * `record_section` +* `selection` --- @@ -471,3 +472,30 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities --- +## PageComponentActionLocation + +### Allowed Values + +* `list` +* `record` +* `record_page` +* `record_row` +* `record_related` +* `record_section` + + +--- + +## RecordQuickActionsLocation + +### Allowed Values + +* `list` +* `record_page` +* `record_row` +* `record_related` +* `record_section` + + +--- + diff --git a/content/docs/references/ui/bulk-action.mdx b/content/docs/references/ui/bulk-action.mdx index 4c857d76386..b88853451b3 100644 --- a/content/docs/references/ui/bulk-action.mdx +++ b/content/docs/references/ui/bulk-action.mdx @@ -14,9 +14,9 @@ action expresses (`operation: 'update'` with a patch, or `'delete'`), or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection. -For the per-record dispatch, name the action in the view's -`bulkActions: ['']` instead — the bare-string form, promoted with the -action's own label, params and `visible`. +For the per-record dispatch, place the action at `selection` instead +(until protocol 19, a view's `bulkActions: ['']`) — it is promoted +with the action's own label, params and `visible`. **Source:** `packages/spec/src/ui/bulk-action.zod.ts` @@ -41,17 +41,17 @@ const result = BulkActionDefSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **name** | `string` | ✅ | Stable identifier — the audit-log action key, and (for an aggregate def) the name of the object action to dispatch. | -| **label** | `string` | optional | Button + dialog-header text. Plain string: an authored def is not i18n-resolved (declare a real action and name it in `bulkActions` to get localization). | +| **label** | `string` | optional | Button + dialog-header text. Plain string: an authored def is not i18n-resolved (declare a real action and place it at `selection` to get localization). | | **icon** | `string` | optional | Lucide icon name (e.g. "user-check", "trash"). | | **variant** | `Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>` | optional | Visual treatment of the button. | | **operation** | `Enum<'update' \| 'delete' \| 'custom'>` | ✅ | What the executor does: 'update'/'delete' are data-plane mass mutations; 'custom' dispatches an object action (see `execution`). | -| **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | For `operation: 'custom'` — 'aggregate' dispatches the named action ONCE for the whole selection, carrying every id in `params._selectedIds`. Required on a custom def: the per-record form is declared as `bulkActions: ['']` instead. | +| **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | For `operation: 'custom'` — 'aggregate' dispatches the named action ONCE for the whole selection, carrying every id in `params._selectedIds`. Required on a custom def: the per-record form is the action placed at `selection` instead. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values applied to every selected record, merged UNDER the user-supplied params so a fixed value can be declared without exposing it in the dialog. | | **params** | `{ name: string; label?: string; help?: string; type: Enum<'text' \| 'textarea' \| 'email' \| 'url' \| 'phone' \| 'password' \| 'secret' \| …>; … }[]` | optional | Inputs collected once before the run. Omit to skip the params step and go straight to confirm. | | **confirmText** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object } \| string` | optional | Confirmation text shown above the affected-record summary — a `template` slot (ADR-0032): a bare string is shorthand for `{ dialect: 'template', source }`, and text with no hole is shown as written. Holes are `{{ path }}` or `{{ path \| formatter[:arg] }}` over two kinds of root, written bare: `count`, the number of records the run covers, and each of the def's params by `name` (`{{ tier }}`, never `{{ params.tier }}`; `count` wins over a param of that name). A param hole renders that param's DISPLAY value: the chosen option's `label` for an option-bearing param (a multi-value param's labels joined with ', '), the picked record's display name for a `lookup` / user param, and the entered value otherwise, so a number, date or currency value takes a formatter (`{{ amount \| currency:EUR }}`, `{{ due \| date:long }}`). Formatters come from the template engine's whitelist (`TEMPLATE_FORMATTERS`, `@objectstack/formula`); a hole holds no logic (no CEL, no arithmetic). Example: 'Update tier on `{{ count }}` account(s) to `{{ tier }}`?'. A hole over any other root, and a single-brace `{x}` token, are refused by name at `objectstack validate`, `compile` and the publish gate, as are a hole holding logic or an unknown formatter and a blank sentence. | | **confirmLabel** | `string` | optional | Custom Confirm button label (default: "Run"). | | **visible** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Eligibility predicate (CEL) — a string or a `{dialect, source}` envelope, i.e. `action.visible` without its boolean-literal arm: a per-record predicate has nothing to say as a constant. Evaluated once PER SELECTED RECORD with that record bound: the button is offered when at least one passes, the run covers only those, and the rest are reported as skipped. A record-free predicate (`features.x`, `current_user.y`) therefore behaves as a plain button-level gate. Fail-closed — a predicate that faults excludes the record. | -| **requiredPermissions** | `string[]` | optional | [ADR-0066 D4] Capability gate on the button, `action.requiredPermissions` semantics verbatim: absent or empty always passes, several are AND-ed, and a client that cannot resolve the caller's capabilities fails OPEN (the server stays the authority). This key exists for INLINE defs — notably the `update`/`delete` data-plane forms, which dispatch no action and so have nothing to inherit a gate from; a def promoted from `bulkActions: ['']` (or an aggregate def naming a declared action) inherits the action's own declaration instead. On a data-plane def the gate governs visibility only — the write itself is still authorized by the data API's object permissions and server hooks. | +| **requiredPermissions** | `string[]` | optional | [ADR-0066 D4] Capability gate on the button, `action.requiredPermissions` semantics verbatim: absent or empty always passes, several are AND-ed, and a client that cannot resolve the caller's capabilities fails OPEN (the server stays the authority). This key exists for INLINE defs — notably the `update`/`delete` data-plane forms, which dispatch no action and so have nothing to inherit a gate from; a def promoted from an action placed at `selection` (or an aggregate def naming a declared action) inherits the action's own declaration instead. On a data-plane def the gate governs visibility only — the write itself is still authorized by the data API's object permissions and server hooks. | | **maxRecords** | `integer` | optional | Selection size above which the run is blocked. Set it on defs whose server work is expensive — an aggregate def carries every selected id in one request. | | **batchSize** | `integer` | optional | Records per executor batch (default 200). Data-plane operations only — an aggregate run is a single call by definition. | diff --git a/content/docs/references/ui/component.mdx b/content/docs/references/ui/component.mdx index b8801c7f38b..396f590d682 100644 --- a/content/docs/references/ui/component.mdx +++ b/content/docs/references/ui/component.mdx @@ -75,7 +75,7 @@ const result = ActionButtonPropsSchema.parse(data); | :--- | :--- | :--- | :--- | | **actions** | `{ name?: string; label?: string; icon?: string; type?: string; … }[]` | optional | The actions in this group, in order — each an action object the group draws and runs itself (`name`, `label`, `icon`, `type`, `target`, `visible`, `disabled`, `size`, …); a member's executor is its `type` | | **display** | `Enum<'inline' \| 'dropdown'>` | optional | Display mode: `inline` renders every action as a button row; `dropdown` renders one trigger button and lists the actions in its menu (renderer default: `inline`) | -| **location** | `Enum<'list' \| 'record' \| 'record_page' \| 'record_row' \| 'record_related' \| 'record_section'>` | optional | Render only the members whose `locations` include this location. Omit to render every member | +| **location** | `Enum<'list' \| 'record' \| 'record_page' \| 'record_row' \| 'record_related' \| 'record_section'>` | optional | Render only the members whose `locations` include this location — any action location but `selection`, which places a declared action on a grid's selection bar. Omit to render every member | | **label** | `string` | optional | Dropdown trigger text (renderer default: `Actions`). Inline mode renders no group label. A literal string — localize through the translation bundle entry for this component id | | **icon** | `string` | optional | Lucide icon name on the dropdown trigger. Inline mode renders no group icon | | **variant** | `Enum<'default' \| 'danger' \| 'outline' \| 'secondary' \| 'ghost' \| 'link'>` | optional | Button variant for the dropdown trigger and for every inline member that sets none — the Button primitive's vocabulary with its destructive arm spelled `danger`, the action runner's word (renderer default: `outline`) | @@ -842,12 +842,12 @@ Sort field and direction pair | **selection** | `{ type?: Enum<'none' \| 'single' \| 'multiple'> }` | optional | Selection config `{ type }` — `none`, `single` or `multiple`, the same block a list view's `selection` declares | | **selectable** | `boolean \| Enum<'single' \| 'multiple'>` | optional | Legacy selection shorthand, read only when `selection` is absent — `true` (multiple), `false` (off), `'single'` or `'multiple'`. Prefer `selection` | | **rowActions** | `string[]` | optional | Per-row action names — `edit` / `delete` select the generic entries, any other name resolves against the object's actions; the same list a list view's `rowActions` declares | -| **bulkActions** | `string[]` | optional | Bulk action names shown on selection — the same list a list view's `bulkActions` declares; a full def goes on `bulkActionDefs` | +| **bulkActions** | `string[]` | optional | Bulk action names shown on selection; a full def goes on `bulkActionDefs` | | **batchActions** | `string[]` | optional | Alternate spelling of `bulkActions` that the renderer reads FIRST (`batchActions ?? bulkActions`) — the same action-name list. Prefer `bulkActions` | | **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Inline bulk-action definitions (full defs, not names) — the same `BulkActionDef` entries a list view's `bulkActionDefs` declares | | **navigation** | `{ mode?: Enum<'drawer' \| 'page' \| 'new_window' \| 'none'>; preventNavigation?: boolean; openNewTab?: boolean; size?: Enum<'auto' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'full'>; … }` | optional | Row-click navigation config — the same block `ListViewSchema.navigation` declares (`{ mode, size, openNewTab, preventNavigation }`) | | **editable** | `boolean` | optional | Enable inline cell editing | -| **singleClickEdit** | `never` | optional | [REMOVED] `object-grid` property `singleClickEdit` was removed in @objectstack/spec 19.0.0 (ADR-0049) — a grid that renders editable now selects a cell on a click and opens its editor on double-click, Enter, F2 or typing, so a single-click entry no longer exists for this key to switch. Delete the key; `editable` (with the viewer's write verdict) decides whether the grid edits. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **singleClickEdit** | `never` | optional | [REMOVED] `object-grid` property `singleClickEdit` was removed in @objectstack/spec 19.0.0 (ADR-0049) — a grid that renders editable now selects a cell on a click and opens its editor on double-click, Enter, F2 or typing, so a single-click entry no longer exists for this key to switch. Delete the key; `editable` (with the viewer's write verdict) decides whether the grid edits. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **keyboardNavigation** | `boolean` | optional | Arrow-key cell navigation on the WAI-ARIA grid pattern: the grid's data cells become one Tab stop that the arrow keys, Home / End and Ctrl+Home / Ctrl+End move between. Always on when the grid renders editable — `editable` set and the viewer allowed to edit — because that grid selects a cell first and moves the selection with these keys; a grid that renders read-only keeps every cell its own Tab stop unless this is `true` | | **resizable** | `boolean` | optional | Allow column resize (the renderer default is on) | | **resizableColumns** | `never` | optional | [REMOVED] `object-grid` property `resizableColumns` was removed in @objectstack/spec 17.7.0 (ADR-0049) — it was the legacy second spelling of `resizable`, read only when `resizable` was absent, so one switch had two spellings and a grid authoring both silently ignored this one. Use `resizable`. Rename the key; the value (a boolean) is unchanged. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | @@ -952,17 +952,17 @@ Sort field and direction pair | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **name** | `string` | ✅ | Stable identifier — the audit-log action key, and (for an aggregate def) the name of the object action to dispatch. | -| **label** | `string` | optional | Button + dialog-header text. Plain string: an authored def is not i18n-resolved (declare a real action and name it in `bulkActions` to get localization). | +| **label** | `string` | optional | Button + dialog-header text. Plain string: an authored def is not i18n-resolved (declare a real action and place it at `selection` to get localization). | | **icon** | `string` | optional | Lucide icon name (e.g. "user-check", "trash"). | | **variant** | `Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>` | optional | Visual treatment of the button. | | **operation** | `Enum<'update' \| 'delete' \| 'custom'>` | ✅ | What the executor does: 'update'/'delete' are data-plane mass mutations; 'custom' dispatches an object action (see `execution`). | -| **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | For `operation: 'custom'` — 'aggregate' dispatches the named action ONCE for the whole selection, carrying every id in `params._selectedIds`. Required on a custom def: the per-record form is declared as `bulkActions: ['']` instead. | +| **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | For `operation: 'custom'` — 'aggregate' dispatches the named action ONCE for the whole selection, carrying every id in `params._selectedIds`. Required on a custom def: the per-record form is the action placed at `selection` instead. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values applied to every selected record, merged UNDER the user-supplied params so a fixed value can be declared without exposing it in the dialog. | | **params** | `{ name: string; label?: string; help?: string; type: Enum<'text' \| 'textarea' \| 'email' \| 'url' \| 'phone' \| 'password' \| 'secret' \| …>; … }[]` | optional | Inputs collected once before the run. Omit to skip the params step and go straight to confirm. | | **confirmText** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object } \| string` | optional | Confirmation text shown above the affected-record summary — a `template` slot (ADR-0032): a bare string is shorthand for `{ dialect: 'template', source }`, and text with no hole is shown as written. Holes are `{{ path }}` or `{{ path \| formatter[:arg] }}` over two kinds of root, written bare: `count`, the number of records the run covers, and each of the def's params by `name` (`{{ tier }}`, never `{{ params.tier }}`; `count` wins over a param of that name). A param hole renders that param's DISPLAY value: the chosen option's `label` for an option-bearing param (a multi-value param's labels joined with ', '), the picked record's display name for a `lookup` / user param, and the entered value otherwise, so a number, date or currency value takes a formatter (`{{ amount \| currency:EUR }}`, `{{ due \| date:long }}`). Formatters come from the template engine's whitelist (`TEMPLATE_FORMATTERS`, `@objectstack/formula`); a hole holds no logic (no CEL, no arithmetic). Example: 'Update tier on `{{ count }}` account(s) to `{{ tier }}`?'. A hole over any other root, and a single-brace `{x}` token, are refused by name at `objectstack validate`, `compile` and the publish gate, as are a hole holding logic or an unknown formatter and a blank sentence. | | **confirmLabel** | `string` | optional | Custom Confirm button label (default: "Run"). | | **visible** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Eligibility predicate (CEL) — a string or a `{dialect, source}` envelope, i.e. `action.visible` without its boolean-literal arm: a per-record predicate has nothing to say as a constant. Evaluated once PER SELECTED RECORD with that record bound: the button is offered when at least one passes, the run covers only those, and the rest are reported as skipped. A record-free predicate (`features.x`, `current_user.y`) therefore behaves as a plain button-level gate. Fail-closed — a predicate that faults excludes the record. | -| **requiredPermissions** | `string[]` | optional | [ADR-0066 D4] Capability gate on the button, `action.requiredPermissions` semantics verbatim: absent or empty always passes, several are AND-ed, and a client that cannot resolve the caller's capabilities fails OPEN (the server stays the authority). This key exists for INLINE defs — notably the `update`/`delete` data-plane forms, which dispatch no action and so have nothing to inherit a gate from; a def promoted from `bulkActions: ['']` (or an aggregate def naming a declared action) inherits the action's own declaration instead. On a data-plane def the gate governs visibility only — the write itself is still authorized by the data API's object permissions and server hooks. | +| **requiredPermissions** | `string[]` | optional | [ADR-0066 D4] Capability gate on the button, `action.requiredPermissions` semantics verbatim: absent or empty always passes, several are AND-ed, and a client that cannot resolve the caller's capabilities fails OPEN (the server stays the authority). This key exists for INLINE defs — notably the `update`/`delete` data-plane forms, which dispatch no action and so have nothing to inherit a gate from; a def promoted from an action placed at `selection` (or an aggregate def naming a declared action) inherits the action's own declaration instead. On a data-plane def the gate governs visibility only — the write itself is still authorized by the data API's object permissions and server hooks. | | **maxRecords** | `integer` | optional | Selection size above which the run is blocked. Set it on defs whose server work is expensive — an aggregate def carries every selected id in one request. | | **batchSize** | `integer` | optional | Records per executor batch (default 200). Data-plane operations only — an aggregate run is a single call by definition. | @@ -1996,7 +1996,7 @@ Sort field and direction pair | :--- | :--- | :--- | :--- | | **actionNames** | `string[]` | optional | Names of actions declared on this object (`actions[]`), in display order. The engine still location-filters named actions. Measured: when omitted (and the host supplies nothing) the bar resolves NO actions and renders its empty placeholder — it does not fall back to "every action at this location", whatever the registration's input list claims. | | **requiredPermissions** | `string[]` | optional | [ADR-0066] Capabilities the user must ALL hold — names that permission sets grant through `systemPermissions`, not object actions: `read` or `update` here is an ordinary capability name, not the object's read or edit permission. When the client has resolved the user's capabilities and any of these is missing, this block does not render its content; wherever it would otherwise render, an insufficient-permissions notice takes its place. Presentation only: it authorises nothing, and the data API still serves the same data to the same user. A client that cannot resolve the user's capabilities (no permission provider, or one that does not report `systemPermissions`) renders this block as if they were held — it fails open. | -| **location** | `Enum<'list' \| 'record' \| 'record_page' \| 'record_row' \| 'record_related' \| 'record_section'>` | optional | Which declared action location this bar renders (renderer default: `record_page`). At `record_page` it draws the record page's actions that are not folded into its ⋯ menu (`component: 'action:menu'`); an action placed at `record` is drawn at `record_page` and at `record_row`. | +| **location** | `Enum<'list' \| 'record_page' \| 'record_row' \| 'record_related' \| 'record_section'>` | optional | Which single place this bar draws actions for (renderer default: `record_page`) — any action location but `record` and `selection`: on an action those words say what the action acts on (one record, on the record page and each list row; many selected records, on a grid's selection bar), and a bar sits in one place. At `record_page` it draws the record page's actions that are not folded into its ⋯ menu (`component: 'action:menu'`); an action placed at `record` is drawn by a bar at `record_page` and at `record_row`. | | **align** | `Enum<'start' \| 'center' \| 'end'>` | optional | Horizontal alignment of the button row (renderer default: `end`). | | **inline** | `boolean` | optional | Render in the flow instead of pulling up into the record-header band. The page header sets this itself when it hosts the bar in its own action slot. | | **variant** | `Enum<'default' \| 'destructive' \| 'outline' \| 'secondary' \| 'ghost' \| 'link'>` | optional | Button variant for every action — the Button primitive's own vocabulary; a per-action `variant` on the resolved def wins (renderer default: `default`). | diff --git a/content/docs/references/ui/view.mdx b/content/docs/references/ui/view.mdx index fc91e505279..daa45afc79b 100644 --- a/content/docs/references/ui/view.mdx +++ b/content/docs/references/ui/view.mdx @@ -1077,8 +1077,8 @@ Map view configuration | **hiddenFields** | `string[]` | optional | Fields to hide in this specific view — the SUBTRACTION of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: each name listed here is removed from the `columns` projection before `fieldOrder` orders the remainder. A name `columns` never projected subtracts nothing. | | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | -| **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActions** | `never` | optional | [REMOVED] `view.list.bulkActions` was removed in @objectstack/spec 19.0.0 (ADR-0085) — the actions a selection of records offers are the object's, not one view's: the selection bar a grid shows once two or more rows are selected draws the same actions on every view of the object. Delete the key, and add `'selection'` to the `locations` of each action it named; to order the bar, or to choose its buttons, write the object's `actionLayout.selection` (`{ pinned, more }`). A view's own `bulkActionDefs` stay on the view: they lead the bar without the arm, and its 「More」 with it. The built-in bulk Delete no longer follows the list: a grid draws it wherever the object allows a delete, on every view with no `bulkActionDefs`, and a view with authored defs draws it only through a `{ name: 'delete', operation: 'delete' }` def. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch place the action at `selection` instead — it is promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | @@ -1328,17 +1328,17 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **name** | `string` | ✅ | Stable identifier — the audit-log action key, and (for an aggregate def) the name of the object action to dispatch. | -| **label** | `string` | optional | Button + dialog-header text. Plain string: an authored def is not i18n-resolved (declare a real action and name it in `bulkActions` to get localization). | +| **label** | `string` | optional | Button + dialog-header text. Plain string: an authored def is not i18n-resolved (declare a real action and place it at `selection` to get localization). | | **icon** | `string` | optional | Lucide icon name (e.g. "user-check", "trash"). | | **variant** | `Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>` | optional | Visual treatment of the button. | | **operation** | `Enum<'update' \| 'delete' \| 'custom'>` | ✅ | What the executor does: 'update'/'delete' are data-plane mass mutations; 'custom' dispatches an object action (see `execution`). | -| **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | For `operation: 'custom'` — 'aggregate' dispatches the named action ONCE for the whole selection, carrying every id in `params._selectedIds`. Required on a custom def: the per-record form is declared as `bulkActions: ['']` instead. | +| **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | For `operation: 'custom'` — 'aggregate' dispatches the named action ONCE for the whole selection, carrying every id in `params._selectedIds`. Required on a custom def: the per-record form is the action placed at `selection` instead. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values applied to every selected record, merged UNDER the user-supplied params so a fixed value can be declared without exposing it in the dialog. | | **params** | `{ name: string; label?: string; help?: string; type: Enum<'text' \| 'textarea' \| 'email' \| 'url' \| 'phone' \| 'password' \| 'secret' \| …>; … }[]` | optional | Inputs collected once before the run. Omit to skip the params step and go straight to confirm. | | **confirmText** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object } \| string` | optional | Confirmation text shown above the affected-record summary — a `template` slot (ADR-0032): a bare string is shorthand for `{ dialect: 'template', source }`, and text with no hole is shown as written. Holes are `{{ path }}` or `{{ path \| formatter[:arg] }}` over two kinds of root, written bare: `count`, the number of records the run covers, and each of the def's params by `name` (`{{ tier }}`, never `{{ params.tier }}`; `count` wins over a param of that name). A param hole renders that param's DISPLAY value: the chosen option's `label` for an option-bearing param (a multi-value param's labels joined with ', '), the picked record's display name for a `lookup` / user param, and the entered value otherwise, so a number, date or currency value takes a formatter (`{{ amount \| currency:EUR }}`, `{{ due \| date:long }}`). Formatters come from the template engine's whitelist (`TEMPLATE_FORMATTERS`, `@objectstack/formula`); a hole holds no logic (no CEL, no arithmetic). Example: 'Update tier on `{{ count }}` account(s) to `{{ tier }}`?'. A hole over any other root, and a single-brace `{x}` token, are refused by name at `objectstack validate`, `compile` and the publish gate, as are a hole holding logic or an unknown formatter and a blank sentence. | | **confirmLabel** | `string` | optional | Custom Confirm button label (default: "Run"). | | **visible** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Eligibility predicate (CEL) — a string or a `{dialect, source}` envelope, i.e. `action.visible` without its boolean-literal arm: a per-record predicate has nothing to say as a constant. Evaluated once PER SELECTED RECORD with that record bound: the button is offered when at least one passes, the run covers only those, and the rest are reported as skipped. A record-free predicate (`features.x`, `current_user.y`) therefore behaves as a plain button-level gate. Fail-closed — a predicate that faults excludes the record. | -| **requiredPermissions** | `string[]` | optional | [ADR-0066 D4] Capability gate on the button, `action.requiredPermissions` semantics verbatim: absent or empty always passes, several are AND-ed, and a client that cannot resolve the caller's capabilities fails OPEN (the server stays the authority). This key exists for INLINE defs — notably the `update`/`delete` data-plane forms, which dispatch no action and so have nothing to inherit a gate from; a def promoted from `bulkActions: ['']` (or an aggregate def naming a declared action) inherits the action's own declaration instead. On a data-plane def the gate governs visibility only — the write itself is still authorized by the data API's object permissions and server hooks. | +| **requiredPermissions** | `string[]` | optional | [ADR-0066 D4] Capability gate on the button, `action.requiredPermissions` semantics verbatim: absent or empty always passes, several are AND-ed, and a client that cannot resolve the caller's capabilities fails OPEN (the server stays the authority). This key exists for INLINE defs — notably the `update`/`delete` data-plane forms, which dispatch no action and so have nothing to inherit a gate from; a def promoted from an action placed at `selection` (or an aggregate def naming a declared action) inherits the action's own declaration instead. On a data-plane def the gate governs visibility only — the write itself is still authorized by the data API's object permissions and server hooks. | | **maxRecords** | `integer` | optional | Selection size above which the run is blocked. Set it on defs whose server work is expensive — an aggregate def carries every selected id in one request. | | **batchSize** | `integer` | optional | Records per executor batch (default 200). Data-plane operations only — an aggregate run is a single call by definition. | @@ -1555,8 +1555,8 @@ One column of a metadata type list | **hiddenFields** | `string[]` | optional | Fields to hide in this specific view — the SUBTRACTION of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: each name listed here is removed from the `columns` projection before `fieldOrder` orders the remainder. A name `columns` never projected subtracts nothing. | | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | -| **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActions** | `never` | optional | [REMOVED] `view.list.bulkActions` was removed in @objectstack/spec 19.0.0 (ADR-0085) — the actions a selection of records offers are the object's, not one view's: the selection bar a grid shows once two or more rows are selected draws the same actions on every view of the object. Delete the key, and add `'selection'` to the `locations` of each action it named; to order the bar, or to choose its buttons, write the object's `actionLayout.selection` (`{ pinned, more }`). A view's own `bulkActionDefs` stay on the view: they lead the bar without the arm, and its 「More」 with it. The built-in bulk Delete no longer follows the list: a grid draws it wherever the object allows a delete, on every view with no `bulkActionDefs`, and a view with authored defs draws it only through a `{ name: 'delete', operation: 'delete' }` def. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch place the action at `selection` instead — it is promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | @@ -1797,17 +1797,17 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **name** | `string` | ✅ | Stable identifier — the audit-log action key, and (for an aggregate def) the name of the object action to dispatch. | -| **label** | `string` | optional | Button + dialog-header text. Plain string: an authored def is not i18n-resolved (declare a real action and name it in `bulkActions` to get localization). | +| **label** | `string` | optional | Button + dialog-header text. Plain string: an authored def is not i18n-resolved (declare a real action and place it at `selection` to get localization). | | **icon** | `string` | optional | Lucide icon name (e.g. "user-check", "trash"). | | **variant** | `Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>` | optional | Visual treatment of the button. | | **operation** | `Enum<'update' \| 'delete' \| 'custom'>` | ✅ | What the executor does: 'update'/'delete' are data-plane mass mutations; 'custom' dispatches an object action (see `execution`). | -| **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | For `operation: 'custom'` — 'aggregate' dispatches the named action ONCE for the whole selection, carrying every id in `params._selectedIds`. Required on a custom def: the per-record form is declared as `bulkActions: ['']` instead. | +| **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | For `operation: 'custom'` — 'aggregate' dispatches the named action ONCE for the whole selection, carrying every id in `params._selectedIds`. Required on a custom def: the per-record form is the action placed at `selection` instead. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values applied to every selected record, merged UNDER the user-supplied params so a fixed value can be declared without exposing it in the dialog. | | **params** | `{ name: string; label?: string; help?: string; type: Enum<'text' \| 'textarea' \| 'email' \| 'url' \| 'phone' \| 'password' \| 'secret' \| …>; … }[]` | optional | Inputs collected once before the run. Omit to skip the params step and go straight to confirm. | | **confirmText** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object } \| string` | optional | Confirmation text shown above the affected-record summary — a `template` slot (ADR-0032): a bare string is shorthand for `{ dialect: 'template', source }`, and text with no hole is shown as written. Holes are `{{ path }}` or `{{ path \| formatter[:arg] }}` over two kinds of root, written bare: `count`, the number of records the run covers, and each of the def's params by `name` (`{{ tier }}`, never `{{ params.tier }}`; `count` wins over a param of that name). A param hole renders that param's DISPLAY value: the chosen option's `label` for an option-bearing param (a multi-value param's labels joined with ', '), the picked record's display name for a `lookup` / user param, and the entered value otherwise, so a number, date or currency value takes a formatter (`{{ amount \| currency:EUR }}`, `{{ due \| date:long }}`). Formatters come from the template engine's whitelist (`TEMPLATE_FORMATTERS`, `@objectstack/formula`); a hole holds no logic (no CEL, no arithmetic). Example: 'Update tier on `{{ count }}` account(s) to `{{ tier }}`?'. A hole over any other root, and a single-brace `{x}` token, are refused by name at `objectstack validate`, `compile` and the publish gate, as are a hole holding logic or an unknown formatter and a blank sentence. | | **confirmLabel** | `string` | optional | Custom Confirm button label (default: "Run"). | | **visible** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Eligibility predicate (CEL) — a string or a `{dialect, source}` envelope, i.e. `action.visible` without its boolean-literal arm: a per-record predicate has nothing to say as a constant. Evaluated once PER SELECTED RECORD with that record bound: the button is offered when at least one passes, the run covers only those, and the rest are reported as skipped. A record-free predicate (`features.x`, `current_user.y`) therefore behaves as a plain button-level gate. Fail-closed — a predicate that faults excludes the record. | -| **requiredPermissions** | `string[]` | optional | [ADR-0066 D4] Capability gate on the button, `action.requiredPermissions` semantics verbatim: absent or empty always passes, several are AND-ed, and a client that cannot resolve the caller's capabilities fails OPEN (the server stays the authority). This key exists for INLINE defs — notably the `update`/`delete` data-plane forms, which dispatch no action and so have nothing to inherit a gate from; a def promoted from `bulkActions: ['']` (or an aggregate def naming a declared action) inherits the action's own declaration instead. On a data-plane def the gate governs visibility only — the write itself is still authorized by the data API's object permissions and server hooks. | +| **requiredPermissions** | `string[]` | optional | [ADR-0066 D4] Capability gate on the button, `action.requiredPermissions` semantics verbatim: absent or empty always passes, several are AND-ed, and a client that cannot resolve the caller's capabilities fails OPEN (the server stays the authority). This key exists for INLINE defs — notably the `update`/`delete` data-plane forms, which dispatch no action and so have nothing to inherit a gate from; a def promoted from an action placed at `selection` (or an aggregate def naming a declared action) inherits the action's own declaration instead. On a data-plane def the gate governs visibility only — the write itself is still authorized by the data API's object permissions and server hooks. | | **maxRecords** | `integer` | optional | Selection size above which the run is blocked. Set it on defs whose server work is expensive — an aggregate def carries every selected id in one request. | | **batchSize** | `integer` | optional | Records per executor batch (default 200). Data-plane operations only — an aggregate run is a single call by definition. | @@ -2163,8 +2163,8 @@ Tab configuration for multi-tab view interface | **hiddenFields** | `string[]` | optional | Fields to hide in this specific view — the SUBTRACTION of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: each name listed here is removed from the `columns` projection before `fieldOrder` orders the remainder. A name `columns` never projected subtracts nothing. | | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | -| **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActions** | `never` | optional | [REMOVED] `view.list.bulkActions` was removed in @objectstack/spec 19.0.0 (ADR-0085) — the actions a selection of records offers are the object's, not one view's: the selection bar a grid shows once two or more rows are selected draws the same actions on every view of the object. Delete the key, and add `'selection'` to the `locations` of each action it named; to order the bar, or to choose its buttons, write the object's `actionLayout.selection` (`{ pinned, more }`). A view's own `bulkActionDefs` stay on the view: they lead the bar without the arm, and its 「More」 with it. The built-in bulk Delete no longer follows the list: a grid draws it wherever the object allows a delete, on every view with no `bulkActionDefs`, and a view with authored defs draws it only through a `{ name: 'delete', operation: 'delete' }` def. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch place the action at `selection` instead — it is promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | @@ -2243,8 +2243,8 @@ Tab configuration for multi-tab view interface | **hiddenFields** | `string[]` | optional | Fields to hide in this specific view — the SUBTRACTION of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: each name listed here is removed from the `columns` projection before `fieldOrder` orders the remainder. A name `columns` never projected subtracts nothing. | | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | -| **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActions** | `never` | optional | [REMOVED] `view.list.bulkActions` was removed in @objectstack/spec 19.0.0 (ADR-0085) — the actions a selection of records offers are the object's, not one view's: the selection bar a grid shows once two or more rows are selected draws the same actions on every view of the object. Delete the key, and add `'selection'` to the `locations` of each action it named; to order the bar, or to choose its buttons, write the object's `actionLayout.selection` (`{ pinned, more }`). A view's own `bulkActionDefs` stay on the view: they lead the bar without the arm, and its 「More」 with it. The built-in bulk Delete no longer follows the list: a grid draws it wherever the object allows a delete, on every view with no `bulkActionDefs`, and a view with authored defs draws it only through a `{ name: 'delete', operation: 'delete' }` def. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch place the action at `selection` instead — it is promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | @@ -2541,8 +2541,8 @@ This schema accepts one of the following structures: | **hiddenFields** | `string[]` | optional | Fields to hide in this specific view — the SUBTRACTION of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: each name listed here is removed from the `columns` projection before `fieldOrder` orders the remainder. A name `columns` never projected subtracts nothing. | | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | -| **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActions** | `never` | optional | [REMOVED] `view.list.bulkActions` was removed in @objectstack/spec 19.0.0 (ADR-0085) — the actions a selection of records offers are the object's, not one view's: the selection bar a grid shows once two or more rows are selected draws the same actions on every view of the object. Delete the key, and add `'selection'` to the `locations` of each action it named; to order the bar, or to choose its buttons, write the object's `actionLayout.selection` (`{ pinned, more }`). A view's own `bulkActionDefs` stay on the view: they lead the bar without the arm, and its 「More」 with it. The built-in bulk Delete no longer follows the list: a grid draws it wherever the object allows a delete, on every view with no `bulkActionDefs`, and a view with authored defs draws it only through a `{ name: 'delete', operation: 'delete' }` def. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch place the action at `selection` instead — it is promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | @@ -2689,7 +2689,7 @@ This schema accepts one of the following structures: | **isPinned** | `boolean` | optional | Console round-trip: the view is pinned in the object's view switcher. Written by the console's pin toggle through the `view` metadata API and read back to draw the pinned group. Stored on the view's row, which has no per-user scope. Not authored. | | **sortOrder** | `integer` | optional | Console round-trip: the view's position among the object's saved views in the switcher, 0-based and counted over saved views only (a code-defined view carries none). Written by the console's drag-reorder and read back to order the tabs. Not authored: `order` is the authored default position. | | **visibility** | `Enum<'private' \| 'team' \| 'organization' \| 'public'>` | optional | Console round-trip: the group the switcher files this view's tab under (private, team, organization or public). Display grouping only, NOT access control: nothing restricts who can list or open the view by this value. No console control sets it; the console carries a stored value forward when it re-saves the row. Not authored. | -| **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 19.0.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 19.0.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **options** | `never` | optional | Refused: a view item record carries no top-level `options` bag. Its per-kind blocks live under `config` (`config.kanban`, `config.timeline`, …); the legacy `options.KIND` bag belongs to the flattened list overlay only. | ### Nested Shape: `ViewItemWire[viewKind='list'].config` @@ -2730,8 +2730,8 @@ This schema accepts one of the following structures: | **hiddenFields** | `string[]` | optional | Fields to hide in this specific view — the SUBTRACTION of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: each name listed here is removed from the `columns` projection before `fieldOrder` orders the remainder. A name `columns` never projected subtracts nothing. | | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | -| **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActions** | `never` | optional | [REMOVED] `view.list.bulkActions` was removed in @objectstack/spec 19.0.0 (ADR-0085) — the actions a selection of records offers are the object's, not one view's: the selection bar a grid shows once two or more rows are selected draws the same actions on every view of the object. Delete the key, and add `'selection'` to the `locations` of each action it named; to order the bar, or to choose its buttons, write the object's `actionLayout.selection` (`{ pinned, more }`). A view's own `bulkActionDefs` stay on the view: they lead the bar without the arm, and its 「More」 with it. The built-in bulk Delete no longer follows the list: a grid draws it wherever the object allows a delete, on every view with no `bulkActionDefs`, and a view with authored defs draws it only through a `{ name: 'delete', operation: 'delete' }` def. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch place the action at `selection` instead — it is promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | @@ -2789,7 +2789,7 @@ This schema accepts one of the following structures: | **isPinned** | `boolean` | optional | Console round-trip: the view is pinned in the object's view switcher. Written by the console's pin toggle through the `view` metadata API and read back to draw the pinned group. Stored on the view's row, which has no per-user scope. Not authored. | | **sortOrder** | `integer` | optional | Console round-trip: the view's position among the object's saved views in the switcher, 0-based and counted over saved views only (a code-defined view carries none). Written by the console's drag-reorder and read back to order the tabs. Not authored: `order` is the authored default position. | | **visibility** | `Enum<'private' \| 'team' \| 'organization' \| 'public'>` | optional | Console round-trip: the group the switcher files this view's tab under (private, team, organization or public). Display grouping only, NOT access control: nothing restricts who can list or open the view by this value. No console control sets it; the console carries a stored value forward when it re-saves the row. Not authored. | -| **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 19.0.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 19.0.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **options** | `never` | optional | Refused: a view item record carries no top-level `options` bag. Its per-kind blocks live under `config` (`config.kanban`, `config.timeline`, …); the legacy `options.KIND` bag belongs to the flattened list overlay only. | ### Nested Shape: `ViewItemWire[viewKind='form'].config` diff --git a/content/docs/releases/v19/index.mdx b/content/docs/releases/v19/index.mdx index 7202f7cacc2..886581303a7 100644 --- a/content/docs/releases/v19/index.mdx +++ b/content/docs/releases/v19/index.mdx @@ -3,13 +3,14 @@ title: v19 description: "The v19 line, which opens with the 19.0.0-next prereleases: the breaking changes it carries over 18.6.0, each with its pull request, and the path from 18.x — protocol 19, an engines.protocol range of '^19', and the build that tells you what else to fix." --- -> **Release status: no 19.x version is published yet.** This page covers the -> `19.0.0-next.N` prerelease line, starting with `19.0.0-next.0`, the first -> cut of the line. It was written on 2026-11-26, before that cut was -> published: npm's `latest` tag carries 18.6.0, and no `19.x` version is on -> npm. A plain install stays on 18.x until 19.0 GA; a prerelease is installed -> only on request, at an exact `19.0.0-next.N`. The [v18](/docs/releases/v18) -> line is the current release. +> **Release status: prereleases only.** This page covers the +> `19.0.0-next.N` prerelease line. Read on 2026-11-29, npm's `latest` tag +> carries 18.6.0 and its `next` tag `19.0.0-next.2`. The line's prereleases on +> npm are `19.0.0-next.0` (2026-11-26) and `19.0.0-next.2` (2026-11-28); +> `19.0.0-next.1` was versioned on `main` and is not on npm, so its changes +> first ship in `19.0.0-next.2`. A plain install stays on 18.x until 19.0 GA; +> a prerelease is installed only on request, at an exact `19.0.0-next.N`. The +> [v18](/docs/releases/v18) line is the current release. **The v19 line** opened on `main` with two changes. The first, [#37230](https://github.com/objectstack-ai/objectstack/pull/37230) (merged @@ -19,27 +20,31 @@ whole train moves to 19, and each cut until 19.0 GA is a `19.0.0-next.N` prerelease. The second, [#37314](https://github.com/objectstack-ai/objectstack/pull/37314) (merged 2026-11-26), moved `PROTOCOL_VERSION` to `19.0.0`. Every other breaking change -below landed on `main` after 18.6.0 and ships in `19.0.0-next.0`, each with -its own changeset saying what breaks and how to move. +below landed on `main` after 18.6.0, each with its own changeset saying what +breaks and how to move. It ships in a `19.0.0-next.N` prerelease, except a +line marked "on `main`": that one landed after `19.0.0-next.2` and ships in +the next cut. ## Breaking changes -**How this list was built.** From the 950 changesets pending on `main` at -`a46efa8c`, the input of the `19.0.0-next.0` version pass. Each changeset -body was classified by `classifyReleaseBullet` in -`scripts/release-github-releases.mjs`, the function that groups a GitHub -Release body: **102 are breaking**, from 101 pull requests. 71 need you to act -and 31 carry a registered ADR-0087 entry that `os migrate meta` lists for -you. Of the rest, 278 add capabilities, 7 declare a semantic change and 563 -are other fixes; they are not listed here. Each line below is the changeset's -own summary, shortened, with the pull request that landed it; the changeset, -and the `CHANGELOG.md` entry the version pass writes from it, carries the -whole before and after. The 87 pull requests titled with `!` since 18.6.0 are -all in this list. -One entry landed after that measurement and is listed with them: the grid's -staged edit retirement, -[#37437](https://github.com/objectstack-ai/objectstack/pull/37437), under -[自动迁移](#migrated-for-you). +**How this list was built.** From the 1,404 changesets on `main` at +`6eb23c87` (2026-11-29): the 1,185 that the `19.0.0-next.0`, `next.1` and +`next.2` version passes consumed (`.changeset/pre/`), and the 219 still +pending for the next cut. Each changeset body was classified by +`classifyReleaseBullet` in `scripts/release-github-releases.mjs`, the +function that groups a GitHub Release body: **159 are breaking**, from 155 +pull requests. 98 need you to act and 61 carry a registered ADR-0087 entry +that `os migrate meta` lists for you. 30 of the 159 (13 to act on, 17 +registered) are among the pending changesets, and their lines say "on +`main`". Of the rest, 403 add capabilities, 12 declare a semantic change and +830 are other fixes; they are not listed here. Each line below is the +changeset's own summary, shortened, with the pull request that landed it; the +changeset, and the `CHANGELOG.md` entry the version pass writes from it, +carries the whole before and after. The 135 pull requests titled with `!` +since 18.6.0 are all in this list. The page's first count, at `a46efa8c` +(2026-11-26) over the 950 changesets that were the input of the +`19.0.0-next.0` version pass, found 102 breaking; the same function finds +the same 102 among those changesets at `6eb23c87`. ### What makes it a major @@ -84,6 +89,18 @@ staged edit retirement, connects only to addresses that are public at connect time. [#35697](https://github.com/objectstack-ai/objectstack/pull/35697), [#35781](https://github.com/objectstack-ai/objectstack/pull/35781) +- A cloud-managed runtime keeps email and password sign-in off when its + deployment declares it off: a save turning it on is refused + `400 SETTINGS_VALIDATION`, and a value stored earlier no longer turns it on. + [#38028](https://github.com/objectstack-ai/objectstack/pull/38028) +- Setup → Authentication's switches, and `GET /api/settings/auth`, show what + the deployment runs when nothing is saved. + [#38180](https://github.com/objectstack-ai/objectstack/pull/38180) — on + `main` +- `createAuthClient().updateUser` declares `Promise`, because the server + answers a receipt, not the user. + [#38431](https://github.com/objectstack-ai/objectstack/pull/38431) — on + `main` #### Access: security, sharing, approvals and the data doors @@ -100,8 +117,16 @@ staged edit retirement, - An app-authored elevation's reads and writes are judged by its caller's organization wall. [#36386](https://github.com/objectstack-ai/objectstack/pull/36386) +- An app-authored elevation's write is judged as it will be stored, and its + option bag never widens it past its caller's organization wall. + [#38268](https://github.com/objectstack-ai/objectstack/pull/38268) — on + `main` - An action's selection is read in the caller's scope before the action runs. [#36132](https://github.com/objectstack-ai/objectstack/pull/36132) +- An action not bound to an object accepts no record: a call carrying a + `recordId` or a `params._selectedIds` is refused `400 VALIDATION_FAILED`. + [#37896](https://github.com/objectstack-ai/objectstack/pull/37896) — on + `main` - Every data door judges environment membership. [#36134](https://github.com/objectstack-ai/objectstack/pull/36134) - The restriction profile is served on the unscoped route only; its @@ -138,6 +163,9 @@ staged edit retirement, - Change Owner refuses an object of a disabled package with `404 OBJECT_PACKAGE_DISABLED`. [#36674](https://github.com/objectstack-ai/objectstack/pull/36674) +- The MCP stdio data bridge refuses a disabled package's data to every caller, + a system context included, with `404 OBJECT_PACKAGE_DISABLED`. + [#37900](https://github.com/objectstack-ai/objectstack/pull/37900) #### Namespaces, bundles and metadata saves @@ -154,6 +182,18 @@ staged edit retirement, and the history selector never addresses the package-less row for a package that neither holds nor ships the name. [#37423](https://github.com/objectstack-ai/objectstack/pull/37423) +- A version the platform registered is never restored into a package's row, + and adopting orphans leaves the platform's own record where the platform + keeps it. + [#37640](https://github.com/objectstack-ai/objectstack/pull/37640) +- The per-item publish and rollback naming no package are refused at a name + only disabled packages hold, with or without a package-less row stored. + [#37818](https://github.com/objectstack-ai/objectstack/pull/37818), + [#37948](https://github.com/objectstack-ai/objectstack/pull/37948) +- The served type schemas (`GET /meta/types`) no longer offer the keys the + platform stamps. + [#38209](https://github.com/objectstack-ai/objectstack/pull/38209) — on + `main` - A refused metadata save and a refused data-API request no longer list zod's bare "Invalid input" union entry ahead of the entries that explain it; a query `where` of the wrong kind is refused with one `fields[]` entry that @@ -202,6 +242,14 @@ staged edit retirement, - A flow condition that hands `timestamp()` a date field through `record.FIELD` or `previous.FIELD` is refused, as the bare field name was. [#34935](https://github.com/objectstack-ai/objectstack/pull/34935) +- `os validate` and the publish gate refuse an option label in a flow's query + filter, edge condition or decision branch; write the option's value. + [#37491](https://github.com/objectstack-ai/objectstack/pull/37491) +- The audit log is sealed on every deployment, and sealed rows expire by whole + checkpoints: `os migrate audit-* --apply` on SQLite or Turso needs + `--sealer-stopped`, and `os audit verify` exits `1` or `2` in cases where it + exited `0`. + [#37605](https://github.com/objectstack-ai/objectstack/pull/37605) - A relationship-path dashboard drill is sent as one nested-relation condition, joined in the database. [#35423](https://github.com/objectstack-ai/objectstack/pull/35423) @@ -258,6 +306,49 @@ staged edit retirement, - A partly failed bulk approve or reject in the Approval Center says why each row failed. [#37282](https://github.com/objectstack-ai/objectstack/pull/37282) +- The build chat's frontend is retired, with its plan, change, build-result + and handoff cards, their detectors and the props that fed them; the 280 + translation keys `@object-ui/i18n@18.6.0` shipped for it are removed. + [#37720](https://github.com/objectstack-ai/objectstack/pull/37720) +- `useObjectTranslation()` and `useI18nContext()` no longer return + `appContentLanguages`; read `useAppContentLanguages()`. + [#37883](https://github.com/objectstack-ai/objectstack/pull/37883) +- The app management page no longer offers "Edit with AI", and its two + released translation keys are removed. + [#38269](https://github.com/objectstack-ai/objectstack/pull/38269) — on + `main` + +#### Knowledge + +- `@objectstack/knowledge-ragflow` is retired, and the Knowledge settings page + no longer offers the RAGFlow adapter. + [#37477](https://github.com/objectstack-ai/objectstack/pull/37477) +- The Knowledge settings page keeps only keys something reads: `adapter`, + `over_fetch` and `enforce_rls` are retired, and a write naming one is + refused whole. + [#37668](https://github.com/objectstack-ai/objectstack/pull/37668) +- The Knowledge page's Turso fields are contributed by the store that reads + them, so a deployment whose store is pgvector shows none and refuses a write + of them. + [#37902](https://github.com/objectstack-ai/objectstack/pull/37902) +- "Test connection" comes with the Turso fields it checks, and + `knowledgeTestActionHandler` moves to `@objectstack/knowledge-turso`. + [#37982](https://github.com/objectstack-ai/objectstack/pull/37982) — on + `main` +- The knowledge field gate stops asking about a field named `title`; a source + whose index could still hold an earlier-rule title is searched only once its + index is proven built under the current recipe. + [#37963](https://github.com/objectstack-ai/objectstack/pull/37963) — on + `main` +- A knowledge source naming a platform object the host does not serve is + refused at publish, for a write naming no package and under a stated + package closure. + [#38038](https://github.com/objectstack-ai/objectstack/pull/38038), + [#38310](https://github.com/objectstack-ai/objectstack/pull/38310) — on + `main` +- `SPLIT_ALGORITHM_VERSION` is retired from `@objectstack/service-knowledge`. + [#38452](https://github.com/objectstack-ai/objectstack/pull/38452) — on + `main` #### The CLI and `verify` @@ -268,19 +359,32 @@ staged edit retirement, - `os db orphans --delete` and `os secret orphans --delete` exit `1` when the confirmation they need is not given. [#36676](https://github.com/objectstack-ai/objectstack/pull/36676) +- `os secret rewrap --apply` without `--yes` in a non-interactive shell exits + `1`. + [#38042](https://github.com/objectstack-ai/objectstack/pull/38042) +- `os i18n extract` and `os i18n check` expect the `_relatedLists` keys + `os validate` accepts under a `.custom` arrangement. + [#38085](https://github.com/objectstack-ai/objectstack/pull/38085) — on + `main` +- `@objectstack/scenarios` deletes the deprecated agent-confirmation grading + names; a `pending_confirmation` operation is graded strictly. + [#38580](https://github.com/objectstack-ai/objectstack/pull/38580) — on + `main` - A managed `mongodb` datasource runs on verify's in-memory stand-in, and a managed datasource on a plugin's driver id refuses the boot. [#36171](https://github.com/objectstack-ai/objectstack/pull/36171) ### 自动迁移 — listed for you by `os migrate meta` [#migrated-for-you] -Each carries a registered ADR-0087 entry. In `19.0.0-next.0` two sit on the -protocol-19 step, `protocol-18-range-refused` and +Each carries a registered ADR-0087 entry. Of the 61 registered changesets, +31 put their entries on the protocol-19 step: `protocol-18-range-refused` +([#37314](https://github.com/objectstack-ai/objectstack/pull/37314)) and +every registered changeset that landed after the first count, from `data-table-staged-edit-retired` -([#37437](https://github.com/objectstack-ai/objectstack/pull/37437)); a later -prerelease may add more, and `os migrate meta` lists them. The other 39 landed -after 18.6.0 on the protocol-18 step, which `os migrate meta --from 18` does -not replay and `--from 17` does. +([#37437](https://github.com/objectstack-ai/objectstack/pull/37437)) on; a +later prerelease may add more, and `os migrate meta` lists them. The entries +of the other 30 landed after 18.6.0 on the protocol-18 step, which +`os migrate meta --from 18` does not replay and `--from 17` does. #### Seeds @@ -323,6 +427,46 @@ not replay and `--from 17` does. - Record create and edit stop loading internal forms; a field gains a Show on create switch. [#36543](https://github.com/objectstack-ai/objectstack/pull/36543) +- `form` is a metadata type of its own, built with `defineForm` in a + `*.form.ts` module and listed under a stack's `forms:`; the Studio helper + that held the name is `defineMetadataForm`, in `*.metadata-form.ts`. + [#37366](https://github.com/objectstack-ai/objectstack/pull/37366) +- A knowledge source is a governed metadata type, `knowledge_source`: a source + written for 18 is refused at parse until it is moved, and + `os migrate meta --from 18 --write` applies the edits it can prove. + [#37676](https://github.com/objectstack-ai/objectstack/pull/37676) +- An agent's `model.provider` is retired; the deployment's AI settings choose + the provider. + [#37783](https://github.com/objectstack-ai/objectstack/pull/37783) +- A book audience names one gate, and a gated book claims its pages by name. + [#37870](https://github.com/objectstack-ai/objectstack/pull/37870) +- The `ask_ai` action type is retired; the shell's 「问 AI」 entry is the one + way into the assistant. + [#37924](https://github.com/objectstack-ai/objectstack/pull/37924) — on + `main` +- An action's `locations` say what it acts on: `list_toolbar`, `list_item`, + `record_header` and `record_more` are retired, and `record` is new. + [#37929](https://github.com/objectstack-ai/objectstack/pull/37929) — on + `main` +- A form view no longer declares `modalSize`. + [#38168](https://github.com/objectstack-ai/objectstack/pull/38168) — on + `main` +- A static chart node's series refuses the renderer-internal `measureFormat` + carrier by name. + [#38145](https://github.com/objectstack-ai/objectstack/pull/38145) — on + `main` +- The build-progress stream frame is retired from `@objectstack/spec/ai`. + [#38398](https://github.com/objectstack-ai/objectstack/pull/38398) — on + `main` +- One pending-confirmation service serves every AI door; the in-app + assistant's pending-action queue leaves `IAIService`. + [#38273](https://github.com/objectstack-ai/objectstack/pull/38273) — on + `main` +- A flow variable key may not use `__proto__`, `constructor` or `prototype` as + its name or any dot-separated part of it, and one run's writes never change + a flow's defaults. + [#38001](https://github.com/objectstack-ai/objectstack/pull/38001) — on + `main` #### Composition and packages @@ -340,6 +484,13 @@ not replay and `--from 17` does. - An `object_extension` amount naming a sibling `currencyField` the served object does not hold is refused at the save. [#35538](https://github.com/objectstack-ai/objectstack/pull/35538) +- A write naming no package is refused over the package-less row of a name + only disabled packages hold. + [#37584](https://github.com/objectstack-ai/objectstack/pull/37584) +- `POST /api/v1/packages/:id/adopt-orphans` is retired; loose items move by an + explicit selection through `POST /api/v1/packages/:id/move-in`. + [#38545](https://github.com/objectstack-ai/objectstack/pull/38545) — on + `main` #### Checks at the build and publish doors @@ -371,6 +522,61 @@ not replay and `--from 17` does. [#37382](https://github.com/objectstack-ai/objectstack/pull/37382) - One refusal names several declared reasons, each in the person's language. [#37395](https://github.com/objectstack-ai/objectstack/pull/37395) +- Four publish-time checks for data-model metadata that saves and does not + work: two refuse, two warn. + [#37513](https://github.com/objectstack-ai/objectstack/pull/37513) +- Three publish-time checks for seeds, flow nodes and actions that save and do + not work. + [#37807](https://github.com/objectstack-ai/objectstack/pull/37807) +- Publish-time checks for views, dashboards and the app shell that save and do + not work. + [#38107](https://github.com/objectstack-ai/objectstack/pull/38107) — on + `main` +- A `_relatedLists` translation key over a list the `.custom` arrangement + hides or re-states without a label is refused. + [#37600](https://github.com/objectstack-ai/objectstack/pull/37600) +- A flow condition that orders a bare date field against text before date + arithmetic on `record.FIELD` or `previous.FIELD` is refused, as its all-bare + and all-root spellings are. + [#37840](https://github.com/objectstack-ai/objectstack/pull/37840) +- A lookup `dependsOn` entry whose filter key names a formula of the + referenced object is refused at authoring. + [#37910](https://github.com/objectstack-ai/objectstack/pull/37910) +- A lookup filter's `$record` path to a structured field is refused where it + is written. + [#38096](https://github.com/objectstack-ai/objectstack/pull/38096) — on + `main` +- Publishing an object draft judges it by the current `ObjectSchema`. + [#38299](https://github.com/objectstack-ai/objectstack/pull/38299) — on + `main` + +#### Knowledge sources + +- A knowledge source is checked for its object, its fields and the search + gates that need no caller, in `os validate` and at publish. + [#37971](https://github.com/objectstack-ai/objectstack/pull/37971) — on + `main` +- A `knowledge_source` save is refused on a deployment that mounts no + knowledge service, and when it names an adapter the deployment does not + mount. + [#38013](https://github.com/objectstack-ai/objectstack/pull/38013), + [#38060](https://github.com/objectstack-ai/objectstack/pull/38060) — on + `main` +- A knowledge service the runtime mounts holds its sources, never building or + searching them, while no embedder or no deployment knowledge store is + mounted. + [#38470](https://github.com/objectstack-ai/objectstack/pull/38470) — on + `main` + +#### Sharing and permissions + +- View All and Modify All stop opening fields; `viewAllFields` is the one + "every field" bit. + [#37371](https://github.com/objectstack-ai/objectstack/pull/37371) +- A manual share or a sharing rule to a user id that names no user is refused + instead of stored as a grant that grants nothing. + [#38216](https://github.com/objectstack-ai/objectstack/pull/38216) — on + `main` #### Sign-in and sync-in @@ -404,8 +610,8 @@ Reach 18.6.0 first, walking each 18.x page's upgrade checklist, through the literal to rewrite, so there the command writes nothing and lists the range; change it by hand in each package manifest. 3. **List the line's registered entries.** `os migrate meta --from 17` also - replays the protocol-18 step, where 39 of the - [41 registered entries](#migrated-for-you) sit. Most are semantic entries: + replays the protocol-18 step, where the entries of 30 of the + [61 registered changesets](#migrated-for-you) sit. Most are semantic entries: for those the command rewrites nothing, and prints each with the surface, the replacement and how to tell it is done. 4. **Run the build, and fix what it refuses.** @@ -429,9 +635,9 @@ Reach 18.6.0 first, walking each 18.x page's upgrade checklist, through the environment you are not a member of, and a reject without a reason. -**Compiled from the changesets, not walked.** No `19.0.0-next.N` was -published when this page was written, so none of these steps has been run -against a published 19.x package. +**Compiled from the changesets, not walked.** This page's steps were +compiled from the changesets; none was run for it against a published +`19.0.0-next.N` package. ## How a breaking change lands on this line diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index 6a26b45af1e..d77ba799d8d 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -25,8 +25,8 @@ The types you'll actually use: Prefer `confirmText`/`params` over the two action properties that are **not wired**: `shortcut` (nothing dispatches keydown events to actions) and -`bulkEnabled` (the multi-select toolbar reads the list view's `bulkActions`, -not this flag). The +`bulkEnabled` (the multi-select toolbar draws the actions placed at +`selection`, not this flag). The [liveness ledger](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/liveness/action.json) carries the per-property status of everything the action schema accepts. @@ -375,6 +375,7 @@ appears on every surface that word covers: | `record_row` | One record, in a list | Per-row menu in list views | | `record_related` | One record, in its parent | Each row of a related list inside a parent record — there only, never on the object's own list views (unlike `record_row`). Declared, not yet placed: the console does not draw it on those rows yet | | `record_section` | One record | Named action bars on record pages | +| `selection` | Many records | The selection bar a grid shows once two or more rows are selected, on every grid view of the object; run once per selected record | `record_related` takes the "One record" cell too. To keep a record page action out of the header's buttons and put it straight into the header's 「More」 (`⋯`) menu, set @@ -404,6 +405,8 @@ ObjectSchema.create({ list: { pinned: ['mass_assign', '$export'], more: ['send_digest'] }, // the record scope: actions placed at record or record_page record: { pinned: ['mark_won', 'mark_lost'], more: ['clone', 'share'] }, + // the selection scope: actions placed at selection, on the selection bar + selection: { pinned: ['mass_assign'], more: ['send_digest'] }, }, }); ``` @@ -426,6 +429,12 @@ ObjectSchema.create({ own Import / Export menu, as without the key (also with `pinned: []`), so `more` names actions only. The record scope has no built-ins: New, Edit and Delete keep their places. +- The `selection` arm orders the selection bar every grid of the object shows once two + or more rows are selected. A view's own `bulkActionDefs` come first; then the arm's + actions, `pinned` as buttons; then the rest, the built-in Delete included, in the + bar's 「More」. `pinned: []` pins none, so every action, Delete included, goes to + 「More」. Without the arm the bar draws its actions by `order` and draws the first + three as buttons, as before. - Leave an arm out (or `actionLayout` out) and that scope draws as before. - The schema refuses more than three pinned, a name given twice, a malformed name, a built-in the scope does not have and a built-in in `more`. `os validate`, `os build` and `os lint` also @@ -443,15 +452,14 @@ ObjectSchema.create({ Surfaces can also reference actions **by name**: ```typescript -// List views — row and bulk menus. These are LIST-VIEW keys, so they nest -// under `list` (or a `listViews` entry) — never at the container top level: -// `ViewSchema` is a strict object and rejects them there. +// List views — the row menu. A LIST-VIEW key, so it nests under `list` (or a +// `listViews` entry) — never at the container top level: `ViewSchema` is a +// strict object and rejects it there. defineView({ // ... list: { // ... rowActions: ['complete_task'], - bulkActions: ['showcase_bulk_reassign'], }, }); @@ -472,23 +480,23 @@ Naming an action in a **widget** does not bypass location filtering — the engine still requires the action to declare the matching location (that's why `MarkDoneAction` above includes `record_section`). -The **selection bar is the exception**, and the only one: an action named in a -list view's `bulkActions` or `bulkActionDefs` is placed by that declaration, -not by `locations`. That is what the retired `action.bulkEnabled` tombstone -prescribes ("the multi-select toolbar is driven by the LIST VIEW's -`bulkActions` / `bulkActionDefs`"), and it is what lets an aggregate bulk -action — one that acts on a whole selection and has no single-record home by -construction — exist at all. +A list view's **aggregate def is the exception**, and the only one: an action +named in a `bulkActionDefs` entry with `execution: 'aggregate'` is placed on +that view's selection bar by the def, not by `locations`. That is what lets an +aggregate bulk action — one that acts on a whole selection and has no +single-record home by construction — exist at all. A per-record bulk action is +placed at `selection` like any other location (protocol 19 retired the view's +`bulkActions` list; `os migrate meta --from 18` moves it). ## Declare the bulk dispatch contract -A list view can wire the same action two ways, and the two hand your body +A selection can run the same action two ways, and the two hand your body **opposite** input: | wiring | dispatches | the body receives | | --- | --- | --- | -| `bulkActions: ['']` | once **per selected row** | that row's `recordId`, no `_selectedIds` | +| `locations: [..., 'selection']` on the action | once **per selected row** | that row's `recordId`, no `_selectedIds` | | `bulkActionDefs: [{ name: '', operation: 'custom', execution: 'aggregate' }]` | **once** for the whole selection | `params._selectedIds: string[]`, no `recordId` | Say which one you wrote the body for, with the same key and the same two values @@ -503,10 +511,12 @@ defineAction({ }); ``` -`os validate` / `os lint` / `os build` then refuse a list view that wires it the -other way (`action-dispatch-contract-mismatch`), naming the action, the view and -both contracts. Without the declaration both mismatches fail **silently, in -opposite directions**: an aggregate body wired bare-string reads `_selectedIds` +`os validate` / `os lint` / `os build` then refuse the other wiring +(`action-dispatch-contract-mismatch`): an action placed at `selection` that +declares `'aggregate'`, or a view's aggregate def naming one that declares +`'perRecord'`, naming the action, where it is wired and both contracts. Without +the declaration both mismatches fail **silently, in opposite directions**: an +aggregate body run per row reads `_selectedIds` as `undefined`, takes its single-record branch and reports success for one row out of ten; a per-record body wired aggregate finds no `recordId` and throws its own "nothing selected", which reads like a selection bug. Nothing else can catch @@ -1015,7 +1025,7 @@ envelope, with `resume_run`'s `{ ok, action, objectName, recordId, result }` as | Symptom | Cause → fix | |:---|:---| -| Button doesn't appear | `locations` doesn't include the surface (empty `locations` is right for a selection-only action that a list view's `bulkActions` places); or the `visible` CEL throws (e.g. a bare, unprefixed field name) and fail-closed hides it; or the user fails `requiredPermissions`, which hides the button at every location with no greyed-out control and no message | +| Button doesn't appear | `locations` doesn't include the surface (a selection-only action declares `locations: ['selection']`); or the `visible` CEL throws (e.g. a bare, unprefixed field name) and fail-closed hides it; or the user fails `requiredPermissions`, which hides the button at every location with no greyed-out control and no message | | Click → `Action 'x' … not found` | `target`-style script with no registered handler — add the `registerAction` call in `onEnable` (Path B above) | | REST → 400 naming the action's `type` | The type has no server dispatch (`url`/`modal`/`form`/`api`) — open its `target` in the client, or call that endpoint directly | | Appears in UI, missing from `list_actions` (MCP) | `ai.exposed` not `true`, `ai.description` under 40 characters, or the type isn't headless-callable | @@ -1024,6 +1034,6 @@ envelope, with `resume_run`'s `{ ok, action, objectName, recordId, result }` as ## Related - [Actions as Tools](/docs/ai/actions-as-tools) — the AI exposure model in depth -- [Views](/docs/ui/views) — `rowActions` / `bulkActions` binding +- [Views](/docs/ui/views) — `rowActions` / `bulkActionDefs` binding - [Action protocol](/docs/protocol/objectui/actions) — the full spec narrative - [Action schema reference](/docs/references/ui/action) — every property, generated from the spec diff --git a/content/docs/ui/components/action.mdx b/content/docs/ui/components/action.mdx index 6c7f4b7ae9d..490cc8b07d0 100644 --- a/content/docs/ui/components/action.mdx +++ b/content/docs/ui/components/action.mdx @@ -59,7 +59,7 @@ Namespace `action`. | `icon` | `string` | | — | | `actions` | `array` of `object` | | The actions in this group, in order. Each member is an action object the group draws and runs itself (`name`, `label`, `icon`, `type`, `target`, `locations`, `visible`, `disabled`, …); a member's executor is its own `type` | | `display` | `enum`: `inline`, `dropdown` | | — | -| `location` | `enum`: `list`, `record`, `record_page`, `record_row`, `record_related`, `record_section` | | Render only the members whose `locations` include this location. Omit to render every member | +| `location` | `enum`: `list`, `record`, `record_page`, `record_row`, `record_related`, `record_section` | | Render only the members whose `locations` include this location — any action location but `selection`, which places a declared action on a grid's selection bar. Omit to render every member | | `variant` | `enum`: `default`, `secondary`, `outline`, `ghost` | | — | | `size` | `enum`: `default`, `sm`, `lg`, `icon` | | Button size for the dropdown trigger and for every inline member that sets none | | `visible` | `boolean` \| `string` \| `object` | | Visibility predicate for the whole group: `true`/`false`, a bare CEL expression, or the `{ dialect: 'cel', source }` envelope, evaluated against the row the host binds. Omit for always-visible | diff --git a/content/docs/ui/components/index.mdx b/content/docs/ui/components/index.mdx index b739e5fce7b..5a574f1ddf3 100644 --- a/content/docs/ui/components/index.mdx +++ b/content/docs/ui/components/index.mdx @@ -87,7 +87,7 @@ regenerates from the renderer registry. Regenerate it with | [`ins`](/docs/ui/components/html#ins) | `ui` | 2 | [HTML Elements](/docs/ui/components/html) | | [`label`](/docs/ui/components/html#label) | `ui` | 2 | [HTML Elements](/docs/ui/components/html) | | [`li`](/docs/ui/components/html#li) | `ui` | 2 | [HTML Elements](/docs/ui/components/html) | -| [`list-view`](/docs/ui/components/plugins#list-view) | `plugin-list` | 42 | [Plugin Blocks](/docs/ui/components/plugins) | +| [`list-view`](/docs/ui/components/plugins#list-view) | `plugin-list` | 41 | [Plugin Blocks](/docs/ui/components/plugins) | | [`main`](/docs/ui/components/html#main) | `ui` | 2 | [HTML Elements](/docs/ui/components/html) | | [`mark`](/docs/ui/components/html#mark) | `ui` | 2 | [HTML Elements](/docs/ui/components/html) | | [`markdown`](/docs/ui/components/plugins#markdown) | `plugin-markdown` | 2 | [Plugin Blocks](/docs/ui/components/plugins) | diff --git a/content/docs/ui/components/plugins.mdx b/content/docs/ui/components/plugins.mdx index 94460edb9bd..3cb72d2f448 100644 --- a/content/docs/ui/components/plugins.mdx +++ b/content/docs/ui/components/plugins.mdx @@ -308,7 +308,6 @@ Namespace `plugin-list`. | `conditionalFormatting` | `array` of `object` | | Row style rules, each `{ condition, style }`: a CEL `condition` over the row's `record.*` and a CSS `style` map. The first rule that matches styles the row. | | `inlineEdit` | `boolean` | | Open the grid in inline-edit mode, for users who may update the object. | | `rowActions` | `array` of `string` | | Names of the actions offered on each row's menu. | -| `bulkActions` | `array` of `string` | | Names of the actions offered once rows are selected. Needs a multi-row `selection`. | | `bulkActionDefs` | `array` of `object` | | Full bulk-action definitions, the spec's `BulkActionDef`: a mass update (`operation: "update"` with a `patch`) or delete, or a named action run once for the whole selection. | | `kanban` | `object` | | The board, the spec's kanban block: `{ groupByField, columns, titleField, summarizeField }`. `groupByField` is the lane field and `columns` the fields on each card. | | `calendar` | `object` | | The calendar, `{ startDateField, endDateField, titleField, colorField, allDayField, initialDate }`; `initialDate` is where it opens: `first_record`, `next_record` or a date-macro token such as `{next_month_start}`, today when omitted. | diff --git a/content/docs/ui/components/record.mdx b/content/docs/ui/components/record.mdx index cb3e240a1d9..2e1106703b7 100644 --- a/content/docs/ui/components/record.mdx +++ b/content/docs/ui/components/record.mdx @@ -142,7 +142,7 @@ Namespace `record`. | :--- | :--- | :--- | :--- | | `actionNames` | `array` of `string` | | Action names to expose, in order — resolved from the actions declared on the object. With no names (and no host-supplied actions) nothing is looked up: the bar renders its empty placeholder on a design / preview surface and nothing at runtime | | `requiredPermissions` | `array` of `string` | | [ADR-0066] Capabilities the user must ALL hold — names that permission sets grant through `systemPermissions`, not object actions: `read` or `update` here is an ordinary capability name, not the object's read or edit permission. When the client has resolved the user's capabilities and any of these is missing, this block does not render its content; wherever it would otherwise render, an insufficient-permissions notice takes its place. Presentation only: it authorises nothing, and the data API still serves the same data to the same user. A client that cannot resolve the user's capabilities (no permission provider, or one that does not report `systemPermissions`) renders this block as if they were held — it fails open. | -| `location` | `enum`: `list`, `record`, `record_page`, `record_row`, `record_related`, `record_section` | | Which declared action location this bar renders | +| `location` | `enum`: `list`, `record_page`, `record_row`, `record_related`, `record_section` | | Which single place this bar draws actions for — any action location but `record` and `selection` | | `align` | `enum`: `start`, `center`, `end` | | — | | `inline` | `boolean` | | Render in the flow instead of folding into the record header | | `variant` | `string` | | Passed to the Button primitive; a per-action variant overrides it | diff --git a/content/docs/ui/pages.mdx b/content/docs/ui/pages.mdx index 39a5436e4d4..2dc5859f33b 100644 --- a/content/docs/ui/pages.mdx +++ b/content/docs/ui/pages.mdx @@ -297,6 +297,61 @@ whose details hold a related table, draws the details across the page. Narrower the drawer and a phone draw one column: the tab row, **Details** first, and the open tab under it. +An object that declares `pinOverview: false` keeps its desktop full page from pinning at any +width: the page draws the tab row with **Details** first and open by default, and lays the +fields out by the page's width in up to three columns, as a page whose details are its only tab +does, also when the details hold a related table. Leaving the key out, or writing `true`, keeps +the layout above. The drawer and a phone draw the same either way, and an object extension +cannot write the key. + +```ts +import { ObjectSchema, Field } from '@objectstack/spec/data'; + +export const Policy = ObjectSchema.create({ + name: 'policy', + label: 'Policy', + pinOverview: false, + fields: { + title: Field.text({ label: 'Title' }), + body: Field.markdown({ label: 'Body' }), + }, +}); +``` + +An object can also move some of its field groups out of the details into tabs of their own with +`fieldTabs`. Each entry names a tab `key` and the `groups` it draws, in order; the tabs sit right +after **Details**, in the order they are declared, before the related lists, and on a pinned page +the first of them is the tab open beside the details. A tab takes its title and icon from its +first group, and a tab with one group draws no second heading under the title. **Details** keeps +the groups no tab names, the fields in no group, the related tables and the approval band. +Each tab counts its own empty fields. A tab whose groups are all hidden (their `visibleWhen`) is +not drawn, and a link to a cited section inside a tab opens that tab first. The reader cannot +move or hide these tabs. Only the standard record page reads the key: the entry form, print pages +and authored pages draw every group as before. + +```ts +export const Policy = ObjectSchema.create({ + name: 'policy', + label: 'Policy', + fieldGroups: [ + { key: 'basic', label: 'Basic' }, + { key: 'content', label: 'Content' }, + { key: 'import', label: 'Original' }, + ], + fieldTabs: [{ key: 'content', groups: ['content', 'import'] }], + fields: { + title: Field.text({ label: 'Title', group: 'basic' }), + body: Field.markdown({ label: 'Body', group: 'content' }), + source_file: Field.text({ label: 'Source file', group: 'import' }), + }, +}); +``` + +The parse refuses a group the object does not declare, a group two tabs name, a group that holds +a related list (body tables stay in **Details**), and a repeated `key`; an object extension cannot +write the key. This is not the form-level `fieldTabs` of a form view, which lists field names. +`os lint` warns when the tabs take every field out of **Details**. + The related lists load in steps, and the details never wait for them. The page asks every list's count in one request set, sent beside the record read, and draws each list's tab before those counts land; a list counted at 0 reads no rows, and its tab is muted, with no diff --git a/content/docs/ui/views.mdx b/content/docs/ui/views.mdx index df36d1b6655..6cebd5d67e5 100644 --- a/content/docs/ui/views.mdx +++ b/content/docs/ui/views.mdx @@ -111,7 +111,6 @@ A List View controls how a collection of records is presented. It supports multi | `selection` | `object` | optional | Row selection mode | | `navigation` | `object` | optional | Row click navigation | | `rowActions` | `array` | optional | Per-row action buttons, by action name — see [Actions](/docs/ui/actions) | -| `bulkActions` | `array` | optional | Bulk selection actions, by action name — see [Actions](/docs/ui/actions) | | `bulkActionDefs` | `array` | optional | Rich bulk action definitions — mass edits, and the aggregate single-call mode (below) | | `inlineEdit` | `boolean` | optional | Enable inline editing | | `exportOptions` | `object` | optional | Export menu configuration: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. `formats` accepts `csv`, `xlsx`, `json` (default `['csv', 'json']`). `'pdf'` is not an export format: to let users print a list as shown, set the view's `allowPrinting`; a printable document (an invoice, a delivery order) is a page that declares `print` — see the [page reference](/docs/references/ui/page). A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse | @@ -239,14 +238,18 @@ columns: [ ### Bulk Actions Over a Selection -Two keys drive the multi-select toolbar. `bulkActions` names actions the object -already declares, and each selected record is dispatched **once** — the action -runs N times for N rows. `bulkActionDefs` carries richer entries: a mass edit -through the data API (`operation: 'update'` + a patch), or the **aggregate** -mode, where the action is called **once for the whole selection**. +Two things drive the multi-select toolbar. An action placed at `selection` +(`locations: [..., 'selection']`) is drawn on the selection bar of **every** grid +view of its object, in the order the object's `actionLayout.selection` gives, +and each selected record is dispatched **once** — the action runs N times for N +rows. A view's own `bulkActionDefs` carry richer entries, first on that view's +bar: a mass edit through the data API (`operation: 'update'` + a patch), or the +**aggregate** mode, where the action is called **once for the whole selection**. +Protocol 19 retired the view's `bulkActions` list; `os migrate meta --from 18` +moves it onto the actions. ```typescript -bulkActions: ['mark_done'], // one dispatch per selected record +// on the action: locations: ['record', 'selection'] — one dispatch per selected record bulkActionDefs: [ // Mass edit — one bulk write, no action involved. { name: 'archive', operation: 'update', patch: { archived: true } }, @@ -290,9 +293,9 @@ A per-record run reports each record on its own: the result dialog lists every failed record with its refusal's `userMessage` when the handler threw one, else the error's message, and the error CSV keeps each failure's whole message. -**Pick the right key for the dispatch you mean.** Per-record is -`bulkActions: ['']` — the bare-string form, which has nowhere to carry a -flag and is promoted with the action's own label, params and `visible`. +**Pick the right form for the dispatch you mean.** Per-record is the action +placed at `selection`, which is promoted with the action's own label, params +and `visible`. Aggregate is the def form, which is where `execution` lives. A def that says `operation: 'custom'` without `execution: 'aggregate'` is rejected at parse time: the renderer has no action attached to such a def, so it used to render a @@ -303,14 +306,14 @@ action declares the contract its body was written for with the same key and the same two values the def uses — `execution: 'perRecord' | 'aggregate'` (see [Actions](/docs/ui/actions#declare-the-bulk-dispatch-contract)). Wiring a declared action the other way is refused by `os validate` / `os lint` / -`os build` with `action-dispatch-contract-mismatch`, naming the action, the -view and both contracts: +`os build` with `action-dispatch-contract-mismatch`, naming the action, where +it is wired and both contracts: ```typescript -// actions: { name: 'export_zip', type: 'api', execution: 'aggregate', … } - -bulkActions: ['export_zip'], // ⛔ refused — the bare string is the per-record - // contract; this body reads `_selectedIds` +// actions: { name: 'export_zip', type: 'api', execution: 'aggregate', +// locations: ['selection'] } // ⛔ refused — `selection` is the +// // per-record contract; this body +// // reads `_selectedIds` bulkActionDefs: [ { name: 'export_zip', operation: 'custom', execution: 'aggregate' }, // ✅ ] @@ -324,7 +327,7 @@ written to serve both. `requiredPermissions: string[]` with `action.requiredPermissions` semantics — absent/empty always passes, several entries AND, unknown caller capabilities fail open (the server stays the authority). A def promoted from -`bulkActions: ['']` (or an aggregate def naming a declared action) +an action placed at `selection` (or an aggregate def naming a declared action) inherits the action's own declaration instead, so this key matters chiefly for the `update`/`delete` data-plane forms, which dispatch no action and have nothing to inherit from. On those defs the gate governs **visibility only** — diff --git a/docs/adr/0037-live-canvas-draft-preview.md b/docs/adr/0037-live-canvas-draft-preview.md index e5cce53178f..9fcb9fd49ec 100644 --- a/docs/adr/0037-live-canvas-draft-preview.md +++ b/docs/adr/0037-live-canvas-draft-preview.md @@ -43,6 +43,8 @@ Everything hard about live preview already exists in the platform; it has simply | SPA usage of `preview=draft` | — | ❌ none (the gap) | | Draft **data** (seed rows before publish) | — | ❌ does not exist (Phase 3) | +> **Note (2026-11-30, [#37753](https://github.com/objectstack-ai/objectstack/issues/37753), carried by [#38438](https://github.com/objectstack-ai/objectstack/issues/38438); built by [#38398](https://github.com/objectstack-ai/objectstack/pull/38398)).** The build-progress stream frame is retired, so two passages no longer describe `main`: TL;DR item 2's "the streaming build tree (`data-build-progress` parts)", and the row of the table above that marks "`data-build-progress` stream parts" ✅ shipped. No decision changes. The frame's one reader, the build chat's progress panel, left with the build chat frontend ([#37720](https://github.com/objectstack-ai/objectstack/pull/37720)), and its producer, the cloud build loop, with objectstack-ai/cloud#5046. #38398 then removed the frame's declaration from `@objectstack/spec/ai` (the module `packages/spec/src/ai/build-progress.zod.ts`, its schemas, types and constants). The upgrade guidance is the ADR-0087 entry `ai-build-progress-frame-retired` (`packages/spec/src/migrations/entries/semantic/19.ai-build-progress-frame-retired.ts`): a host that still streams a progress part of its own passes any `data-` part name to `ctx.onProgress` and owns the payload it sends. Phase 2's first invalidation source, the `buildProgress.items` diffs, was the same signal as the chat held it, and no code under `ui/` holds it any more. The per-edit signal, each authoring tool's `drafted` envelope, is not this note's subject. Both passages are left as written; read them with this note. + ### Why now The 2026-06-10 reliability batch closed the failure modes a live canvas would have amplified: dangling dataset references auto-heal, seed data reliably lands on publish (loudly when it can't), the build streams artifact-level progress, and reloaded conversations render honestly. The canvas is now an additive surface over trustworthy primitives, not a magnifier for bugs. diff --git a/docs/adr/0070-package-first-authoring.md b/docs/adr/0070-package-first-authoring.md index 2c7c8ff30ef..92cbda4ff9f 100644 --- a/docs/adr/0070-package-first-authoring.md +++ b/docs/adr/0070-package-first-authoring.md @@ -1,6 +1,6 @@ # ADR-0070: Package-first authoring — every runtime-authored item lives in a writable package (base); no orphans -**Status**: Accepted (2026-06-24) — P1–P3 implemented, merged & live-verified (see *Implementation status*); D4–D6 remaining · **Superseded in part by [ADR-0146](./0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md)** (2026-10-31) — D3's prompt to create a base, for the paired case only: a customer's first customization of an installed base lands in the auto-created `.custom` package without a prompt (ADR-0146 D3); D5's destination for a package-less overlay row of a packaged item: the base's `.custom`, as a declared override, after which the package-less write closes (ADR-0146 D11). D1, D2, D4 and D6 stand; D3's prompt stands everywhere else. · **Amended** (2026-10-31, [#28117](https://github.com/objectstack-ai/objectstack/issues/28117) — the maintainer's ruling of 2026-10-30, 「大包 + 设置里启用模块」, then 「同意」: a `type: module` sub-package of an installed app may be **disabled**, not authored into, by an admin, on the tie PR [#28308](https://github.com/objectstack-ai/objectstack/pull/28308) shipped; see the amendment note under D2. D2's two kinds and its writability predicate stand.) +**Status**: Accepted (2026-06-24) — P1–P3 implemented, merged & live-verified (see *Implementation status*); D4–D6 remaining · **Superseded in part by [ADR-0146](./0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md)** (2026-10-31) — D3's prompt to create a base, for the paired case only: a customer's first customization of an installed base lands in the auto-created `.custom` package without a prompt (ADR-0146 D3); D5's destination for a package-less overlay row of a packaged item: the base's `.custom`, as a declared override, after which the package-less write closes (ADR-0146 D11). D1, D2, D4 and D6 stand; D3's prompt stands everywhere else. · **Amended** (2026-10-31, [#28117](https://github.com/objectstack-ai/objectstack/issues/28117) — the maintainer's ruling of 2026-10-30, 「大包 + 设置里启用模块」, then 「同意」: a `type: module` sub-package of an installed app may be **disabled**, not authored into, by an admin, on the tie PR [#28308](https://github.com/objectstack-ai/objectstack/pull/28308) shipped; see the amendment note under D2. D2's two kinds and its writability predicate stand.) · **Amended** (2026-11-29, [#38150](https://github.com/objectstack-ai/objectstack/issues/38150) — ruling record [comment 7184753035](https://github.com/objectstack-ai/objectstack/issues/37424#issuecomment-7184753035), question 3, ruled C, as [ADR-0084](./0084-application-builder-information-architecture.md#amendment-2026-11-26-org) records it: D5's "move into a base" is the move-in door, and D5's bulk assignment to a default base is superseded; see the amendment note under D5. D1 and D6 stand.) **Deciders**: ObjectStack Protocol Architects **Builds on**: [ADR-0005](./0005-metadata-customization-overlay.md) (`allowOrgOverride` / runtime overlay model; one Zod source per type), [ADR-0048](./0048-cross-package-metadata-collision.md) (one app per package; package id is the addressing unit), [ADR-0033](./0033-ai-assisted-metadata-authoring.md) (AI authors metadata as drafts), [ADR-0067](./0067-commit-history-and-rollback-for-ai-authoring.md) (commit history & rollback for AI authoring) **Consumers**: `@objectstack/objectql` (`protocol.saveMetaItem` write path), `@objectstack/spec` (metadata-type registry), `../objectui` (Studio create flow, package scope selector, `PackagesPage`), `../cloud` (`service-ai-studio` — `create_metadata` / `resolvePackageId` / `apply_blueprint`) @@ -30,7 +30,7 @@ Built across the three surfaces and verified end-to-end in a real environment vi 2. **[existing->ruled] Two package kinds.** *Code/installed* packages (manifest `source: 'filesystem'` / installed via marketplace) are **read-only** — you may org-overlay an item where `allowOrgOverride` (ADR-0005), but you may **not** author *new* items into them. *Writable* packages (DB-backed, user/AI-created "bases") are the only authoring targets. 3. **[new] Create-flow contract — "pick or create a base first".** Before any create, all three surfaces (Studio UI, the AI authoring tools, the kernel write path) resolve to a writable package or **prompt to create one** — no silent default. This is enforced in code, not just prompt guidance. 4. **[new] The package is the lifecycle unit.** Delete (cascade all its items + data), export, snapshot/version, and duplicate operate on a whole package. This is the answer to "how do I delete the mess." -5. **[ruled] Retire the stopgaps.** #2252's null-coercion evolves into *redirect-to-a-writable-package*; #1946's "Local / Custom" scope becomes a **migration affordance** ("move these loose items into a base") and is then removed. +5. **[ruled] Retire the stopgaps.** #2252's null-coercion evolves into *redirect-to-a-writable-package*; #1946's "Local / Custom" scope becomes a **migration affordance** ("move these loose items into a base") and is then removed. *(Amended 2026-11-29, [#38150](https://github.com/objectstack-ai/objectstack/issues/38150): "move these loose items into a base" is the move-in door — the amendment note under D5.)* --- @@ -87,6 +87,8 @@ Operating on a *base* operates on all of its contents — this is the direct ans - The objectui #1946 *"Local / Custom"* scope is repurposed as a **one-time migration surface**: it lists the legacy package-less items and offers "move into a base" (assign them a writable `package_id`). Once an environment has no orphans, the scope is removed from the selector. - A small migration (or admin action) can bulk-assign legacy orphans to a default base named for the environment. +> **Amended 2026-11-29 ([#38150](https://github.com/objectstack-ai/objectstack/issues/38150), ruling record [comment 7184753035](https://github.com/objectstack-ai/objectstack/issues/37424#issuecomment-7184753035), question 3, ruled C; written into [ADR-0084's amendment of 2026-11-26](./0084-application-builder-information-architecture.md#amendment-2026-11-26-org)) — "move into a base" is the move-in door, and the bulk assignment to a default base is superseded.** TL;DR item 5's "move these loose items into a base" and this decision's `offers "move into a base"` are one door, and it shipped: `POST /api/v1/packages/:id/move-in` moves a selection of loose items — one, several, or all — into a writable package, each through the judges a save runs. The third bullet above, "A small migration (or admin action) can bulk-assign legacy orphans to a default base named for the environment", is superseded by that ruling: nothing is renamed or migrated, and there is no catch-all package. A row that is never moved stays legal: it belongs to the implicit environment package ([ADR-0150](./0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md) D1, the fourth bucket). + ### D6 — Single-tenant framing; no "org" dumping ground [ruled] A metadata-customizable deployment is **single-tenant** (an *environment*; `project -> environment`); there is no per-org overlay dimension here. The relevant axis is **code package vs writable base**, not "org". The earlier instinct to make a package-less "org/local" scope the *default* is explicitly rejected: it reproduces the orphan pile. (Multi-tenant hosting keeps `package_id = null` overlays as a *tenant-overlay* mechanism; that is orthogonal and out of scope for this ADR.) diff --git a/docs/adr/0084-application-builder-information-architecture.md b/docs/adr/0084-application-builder-information-architecture.md index 211569489d0..e7979f5f464 100644 --- a/docs/adr/0084-application-builder-information-architecture.md +++ b/docs/adr/0084-application-builder-information-architecture.md @@ -184,8 +184,9 @@ Every type the spec registers, enumerated at `origin/main` `151e8123` from `pack | **界面 UI** | `ui` | 2 | `page` 页面 | 常用 | | **界面 UI** | `ui` | 3 | `dashboard` 仪表盘 | 常用 | | **界面 UI** | `ui` | 4 | `report` 报表 | 常用 | -| **界面 UI** | `ui` | 5 | `view` 视图 | 高级 | -| **界面 UI** | `ui` | 6 | `action` 操作 | 高级 | +| **界面 UI** | `ui` | 5 | `form` 表单 | 常用 | +| **界面 UI** | `ui` | 6 | `view` 视图 | 高级 | +| **界面 UI** | `ui` | 7 | `action` 操作 | 高级 | | **自动化 Automation** | `automation` | 1 | `flow` 流程 | 常用 | | **自动化 Automation** | `automation` | 2 | `job` | 高级 | | **平台 Platform** | `system` | 1 | `doc` 文档 | 高级 | @@ -215,6 +216,10 @@ Every type the spec registers, enumerated at `origin/main` `151e8123` from `pack *(Amended 2026-11-27, card [#37740](https://github.com/objectstack-ai/objectstack/issues/37740), which catches the notes up with a row the table already holds and decides nothing: `knowledge_source`, the table's last row. The row was written by the change that registered the type (card [#37304](https://github.com/objectstack-ai/objectstack/issues/37304); [ADR-0161](./0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md) K4), under [item 6](#amendment-2026-11-25-silent), and that change left the notes of 2026-11-25 and 2026-11-26 above at their own readings. Read again at `origin/main` `62dd9e1ef5`: 35 entries — the 33 of those readings, each in the domain the 2026-11-26 note leaves it in, and two registered on 2026-11-27: `form`, registered `ui` ([ADR-0159](./0159-forms-are-their-own-metadata-type-public-forms-are-form-items-view-is-lists-only.md) D2; card [#37086](https://github.com/objectstack-ai/objectstack/issues/37086)), and `knowledge_source`, registered `ai`. `form` still has no row: Studio's directory does not list the type yet, and its row is written by the change that lists it ([Amendment (2026-11-26)](#amendment-2026-11-26-moves)). So the table has 34 rows for the 35 entries, and they count 数据 Data 8 · 界面 UI 6 · 自动化 Automation 2 · 平台 Platform 7 · 访问 Access 6 · AI 5. No type changed group since the 2026-11-26 note, and one row has been rewritten since: `datasource`'s, by the note above this one.)* +*(Rewritten 2026-11-29, card [#37087](https://github.com/objectstack-ai/objectstack/issues/37087), which carries out [Amendment (2026-11-26)](#amendment-2026-11-26-moves) for one row and decides nothing: `form`. The same change takes the type off the directory's hidden types and brings its designer, so Studio lists it and its row is written: 界面 UI, fifth, directly after `report` ([item 11](#amendment-2026-11-26-silent)), and its tier is 常用; `view` and `action`, the two types behind it, are each one place later. Read again at `origin/main` `3014176695`: the registry holds the same 35 entries, and the table now has a row for each — 35 rows, counting 数据 Data 8 · 界面 UI 7 · 自动化 Automation 2 · 平台 Platform 7 · 访问 Access 6 · AI 5. The four rows that amendment left to their changes are now each rewritten or written: `dataset`'s, `position`'s, `datasource`'s and `form`'s.)* + +*(Amended 2026-11-30, card [#38438](https://github.com/objectstack-ai/objectstack/issues/38438), from the contract review of the change that wrote the note above ([comment 7258340131](https://github.com/objectstack-ai/objectstack/pull/38619#issuecomment-7258340131), N1), which decides nothing: that note's "The same change takes the type off the directory's hidden types and brings its designer" is true of card #37087 and loose for the change. The card landed in two pull requests. The first ([#38484](https://github.com/objectstack-ai/objectstack/pull/38484)) brought the designer (`ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.tsx`). The second ([#38619](https://github.com/objectstack-ai/objectstack/pull/38619)), the change that wrote the row, lists the type: it takes `form` off the directory's hidden types (`ui/packages/app-shell/src/views/metadata-admin/directoryScope.ts#HIDDEN_DIRECTORY_TYPES`) and gives it its place in the menu (`ui/packages/app-shell/src/views/studio-design/studioMenuPlacement.ts#STUDIO_MENU_PLACEMENT`). The row, its order and its tier stand as that note gives them, and that note is left as written.)* + The rows are in the menu's order: by group, then by **Order**, which counts inside a group. **Tier** is 常用 Common or 高级 Advanced. The Chinese word beside a registered name is the one the ruling or its proposal uses for that type; a type neither names in Chinese has none. `field` carries no order and no tier because it draws no row (the second reading below). The table is the registry read at one commit. **The rule above is what binds**: a type added to the registry, or given another domain there, moves in the menu without this table being edited, and where the two disagree the registry is right. *(Amended 2026-11-25: that sentence is about the Group and `domain` columns. The Order and Tier columns are read from no registry — they are decided in this record, and a type the table has no row for is drawn in 高级 Advanced, at the end of its group: [Amendment (2026-11-25)](#amendment-2026-11-25).)* @@ -231,7 +236,7 @@ The menu also holds four entries that open no type's list. Each sits in the grou | Entry | Group | Source | |---|---|---| -| **The organization's own flows** — the flows that belong to no package (the `~org` scope) | 自动化 Automation | decision 11 | +| ~~**The organization's own flows** — the flows that belong to no package (the `~org` scope)~~ | ~~自动化 Automation~~ | ~~decision 11~~ | | **The organization-wide default sharing overview** — a page with a route of its own, not a metadata item | 访问 Access | decision 11 | | **Diagnostics** | 平台 Platform | decision 11 | | **The cross-package environment directory** (the `~all` leg) | 访问 Access | **drafted here, not ruled** — [item 1](#amendment-silent) below | @@ -240,6 +245,8 @@ The menu also holds four entries that open no type's list. Each sits in the grou *(Amended 2026-11-26, card [#37451](https://github.com/objectstack-ai/objectstack/issues/37451): on a package the menu holds one more entry that opens no type's list — **概览 Overview**, the open package's own page, the menu's first row, above the groups, under no group and in no tier ([Amendment (2026-11-26)](#amendment-2026-11-26-overview)). One row of the table above leaves the menu for Setup: the cross-package environment directory, for a Setup group that holds access pages. Diagnostics stays, and on a package it reads that package. The organization's own flows keep their entry until the door that moves loose items into a package ships, and retire with it. The default sharing overview and 全部类型 All types stay ([Amendment (2026-11-26)](#amendment-2026-11-26-moves)).)* +*(Amended 2026-11-29, card [#38150](https://github.com/objectstack-ai/objectstack/issues/38150), ruling record [comment 7184753035](https://github.com/objectstack-ai/objectstack/issues/37424#issuecomment-7184753035), question 3: the table's first row is struck. The door that moves loose items into a package shipped, and the organization's own flows retired with it, the entry and the scope it opened alike ([Organization-level content](#amendment-2026-11-26-org)). Items that belong to no package are listed under the "Loose" value of the cross-package list's source filter, and a flow among them opens on its own page there.)* + ### What stands, and what the amendment replaces {#amendment-stands} | The 2026-07-01 text | Since the amendment | @@ -295,7 +302,7 @@ A group's label is drawn in a tier only where the group has an entry in that tie The four [entries that are not a type](#entries-not-a-type) are 高级 on a package. Each is drawn after the types of its group, the default sharing overview before the cross-package directory — where the menu adds them today (§3.4). -The tiers belong to a package's menu. The package-less scope (`~org`) and the cross-package leg (`~all`) draw no fold: the same labels and the same order, flat (§3.8). +The tiers belong to a package's menu. ~~The package-less scope (`~org`) and the cross-package leg (`~all`) draw no fold~~ The cross-package leg (`~all`) draws no fold: the same labels and the same order, flat (§3.8). *(Amended 2026-11-29, card [#38150](https://github.com/objectstack-ai/objectstack/issues/38150), ruling record [comment 7184753035](https://github.com/objectstack-ai/objectstack/issues/37424#issuecomment-7184753035), question 3: the sentence named two scopes that draw no fold. The package-less scope retired with its entry ([Organization-level content](#amendment-2026-11-26-org)), so it names one.)* *(Amended 2026-11-26: the two tiers and the rule below stand, and the ten 常用 types keep their places. Three types join them, each placed by name: `dataset` and `position`, and `form`, a type not yet registered, once Studio lists it — thirteen in all. 概览 Overview is drawn above the tiers and belongs to neither. Of the four entries that are not a type, the cross-package directory is to leave the menu. See [Amendment (2026-11-26)](#amendment-2026-11-26-moves).)* @@ -305,7 +312,7 @@ The rule is the proposal's (§3.1), ruled as proposed. A type is **常用** only 1. **It has no parent object.** Its schema does not require one object. A type bound to one object is authored from that object. 2. **A builder makes it directly, as a step of building an app.** It is not reference content, and not developer or operator work. -3. **It stays inside the open package.** An entry that leaves the package's scope — the organization's own flows, the cross-package directory — is 高级 on a package. +3. **It stays inside the open package.** An entry that leaves the package's scope — ~~the organization's own flows,~~ the cross-package directory — is 高级 on a package. *(Amended 2026-11-29, card [#38150](https://github.com/objectstack-ai/objectstack/issues/38150), ruling record [comment 7184753035](https://github.com/objectstack-ai/objectstack/issues/37424#issuecomment-7184753035), question 3: the first of the sentence's two examples is struck. The organization's own flows retired with their scope ([Organization-level content](#amendment-2026-11-26-org)), so the menu draws no such entry. The other example, the cross-package directory, is the entry the 2026-11-26 amendment moved to Setup ([Amendment (2026-11-26)](#amendment-2026-11-26-moves)). The test stands as ruled.)* **A type with no row in the table is drawn in 高级, at the end of its group. It is never invisible.** @@ -329,7 +336,7 @@ Merging accepts them; an objection names the number. 1. **The order of the types the proposal's list does not write out.** Its ordered list (§3.4) is written out for the 数据 Data and 界面 UI types and stops there. The Order column takes the rest from the proposal's drawing of the open fold (§3.2) and, for a type that drawing does not show, from the row order of its per-type table (§2), reading a row that names several types left to right. That places `job` after `flow`; `translation` · `api` · `datasource` · `external_catalog`, in that order, after `email_template`; and `sharing_rule` · `queue` · `capability`, in that order, after `assignment_rule`. 2. **Where `picklist` sits inside 高级.** The maintainer moved it between the tiers and named no place. It keeps the place the proposal's list gave it, second in 数据 Data, which makes it the first 高级 entry of that group. -3. **Where the four entries that are not a type sit.** After the types of their group, as §3.4 leaves them. The proposal's per-type table (§2) lists the organization's own flows between `flow` and `job`; this record follows §3.4, so on a package that holds a `job`, that type's entry is drawn above the organization's flows. +3. **Where the four entries that are not a type sit.** After the types of their group, as §3.4 leaves them. ~~The proposal's per-type table (§2) lists the organization's own flows between `flow` and `job`; this record follows §3.4, so on a package that holds a `job`, that type's entry is drawn above the organization's flows.~~ *(Amended 2026-11-29, card [#38150](https://github.com/objectstack-ai/objectstack/issues/38150), ruling record [comment 7184753035](https://github.com/objectstack-ai/objectstack/issues/37424#issuecomment-7184753035), question 3: the second sentence is struck. It placed the organization's own flows, which retired with their scope ([Organization-level content](#amendment-2026-11-26-org)). Of the four entries this item counts, a package's menu draws two since: the default sharing overview and diagnostics. The cross-package directory is the one the 2026-11-26 amendment moved to Setup ([Amendment (2026-11-26)](#amendment-2026-11-26-moves)). The first sentence stands for those two.)* 4. **The tiers' English names.** The ruling names the tiers in Chinese. This record writes Common and Advanced, after the two values of the proposal's list (§3.4). 5. **The table's shape.** One row per type, so that each type carries its own order and tier. Order counts inside a group, because the order of the groups is the six-group table's. 6. **~~A type registered after the ruling was written: `ai_context`.~~ Types registered after the ruling was written: `ai_context`, and since then `knowledge_source`.** *(Heading reworded 2026-11-27, for the second row that points here; the note that ends this item says what changed.)* The proposal and the ruling were made on a registry of 32 types. `ai_context`, the context pack of [ADR-0160](./0160-record-scoped-ai-inquiry.md) D1, was registered under `ai` the same day, after both. The maintainer's words on AI are 「AI 应该提到第一层分类,放在最下面」, and the ruling record lists the group's 常用 types as 智能体 · 工具 · 技能: three types, and not this one. Three ruled sentences place it, and they agree: its schema requires one root object, so the first test of the rule sorts it 高级; 高级 holds every type the ruling does not list as 常用; and a type with no row is drawn at the end of its group. The table writes that down as a row — last in AI, 高级 — so that the placement list has a row to mirror. If every AI type is meant to be 常用, the tier of this one row is the word to change. *(Amended 2026-11-27, card [#37740](https://github.com/objectstack-ai/objectstack/issues/37740), which decides nothing: a second type has been registered under `ai` since the ruling — `knowledge_source`, on 2026-11-27 ([ADR-0161](./0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md) K4) — and the change that registered it wrote its row under this item: fifth in AI, 高级. So `ai_context`'s row is the fourth, and no longer the last in AI. The ruling record's list of the group's 常用 types, 智能体 · 工具 · 技能, does not name this type either, and the same three sentences place it: its schema requires one object (the `object` key of its `source`, `packages/spec/src/ai/knowledge-source.zod.ts#ObjectKnowledgeSourceSchema`), so the first test of the rule sorts it 高级; 高级 holds every type the ruling does not list as 常用; and a type with no row is drawn at the end of its group. The sentence before this note holds for each of the two rows: if every AI type is meant to be 常用, the tier of that row is the word to change.)* @@ -411,13 +418,15 @@ The top bar is drawn by `ui/packages/app-shell/src/views/studio-design/StudioDes | The way back to the app, with the app's name | The first control of the package row; the name is shown by the switcher beside it | the pick | | The ⋯ package menu (`ui/packages/app-shell/src/views/studio-design/StudioPackageMenu.tsx#STUDIO_PACKAGE_MENU_ITEMS`) | The header of 概览 Overview, moved as it is | the pick | | The pending-changes button with its count, and Publish | The Pending tab of 概览 Overview. The count is a badge on the menu's 概览 row, and one click on it opens that tab | the pick | -| The same button and Publish on the package-less scope (`~org`), which draws no 概览 | A 变更 Changes row with its count, in the left column under the package row (`ui/packages/app-shell/src/views/studio-design/StudioTopLeft.tsx#StudioScopePendingRow`), drawn only while that scope has something pending. It opens the changes sheet that exists, and Publish is in that sheet | not ruled — the note below | +| ~~The same button and Publish on the package-less scope (`~org`), which draws no 概览~~ | ~~A 变更 Changes row with its count, in the left column under the package row (`ui/packages/app-shell/src/views/studio-design/StudioTopLeft.tsx`), drawn only while that scope has something pending. It opens the changes sheet that exists, and Publish is in that sheet~~ | ~~not ruled — the note below~~ | | Save and Cancel, drawn while a page has unsaved edits | The action slot of the item's header (`ui/packages/app-shell/src/views/studio-design/StudioItemHeader.tsx#StudioItemHeader`) | the pick | | The AI assistant button, and the toggle of the right-hand panel | The right end of each page's title row — a list's title row, an item's header — where an app's page carries its own (`ui/packages/app-shell/src/layout/ShellPageActions.tsx#ShellPageActions`) | the pick | | The control that shows and hides the menu | Studio's row | decision 3 | | For a package with no app: the "create app" button, or the label that says its app waits for a publish | None — [item 5](#amendment-2026-11-26-silent) | not ruled | -*(Amended 2026-11-27, card [#37685](https://github.com/objectstack-ai/objectstack/issues/37685): the table gains its fourth row — where Changes and Publish live on the package-less scope. The pick sends them to 概览, and `~org` draws no 概览 ([item 1](#amendment-2026-11-26-silent)), so card [#37456](https://github.com/objectstack-ai/objectstack/issues/37456), which removed the top bar, gave that scope a row of its own. The row is written from the code, read at `origin/main` `73d5e347`: it is drawn on `~org` alone, it counts the drafts of the organization's own flows, the rail keeps it as an icon, and the sheet it opens is `ui/packages/app-shell/src/preview/DraftChangesPanel.tsx#DraftChangesPanel`. No ruling gives this home: it was built first and is recorded after the fact, as that change's contract review asked ([comment 7202356468](https://github.com/objectstack-ai/objectstack/pull/37579#issuecomment-7202356468), finding S3). Merging this note accepts it. The top bar still held seven things: the row is a second home for the third, on a scope where its first is not drawn. No other row changes.)* +~~*(Amended 2026-11-27, card [#37685](https://github.com/objectstack-ai/objectstack/issues/37685): the table gains its fourth row — where Changes and Publish live on the package-less scope. The pick sends them to 概览, and `~org` draws no 概览 ([item 1](#amendment-2026-11-26-silent)), so card [#37456](https://github.com/objectstack-ai/objectstack/issues/37456), which removed the top bar, gave that scope a row of its own. The row is written from the code, read at `origin/main` `73d5e347`: it is drawn on `~org` alone, it counts the drafts of the organization's own flows, the rail keeps it as an icon, and the sheet it opens is `ui/packages/app-shell/src/preview/DraftChangesPanel.tsx#DraftChangesPanel`. No ruling gives this home: it was built first and is recorded after the fact, as that change's contract review asked ([comment 7202356468](https://github.com/objectstack-ai/objectstack/pull/37579#issuecomment-7202356468), finding S3). Merging this note accepts it. The top bar still held seven things: the row is a second home for the third, on a scope where its first is not drawn. No other row changes.)*~~ + +*(Amended 2026-11-29, card [#38150](https://github.com/objectstack-ai/objectstack/issues/38150), ruling record [comment 7184753035](https://github.com/objectstack-ai/objectstack/issues/37424#issuecomment-7184753035), question 3: the fourth row and the note above are struck. The package-less scope retired with its entry ([Organization-level content](#amendment-2026-11-26-org)), and its 变更 Changes row and the batch publish behind that row retired with it. The row's component, `StudioScopePendingRow`, is deleted, so the struck row names its file alone. A draft that belongs to no package is still published from Home's Publish all, and is published or discarded on its own item page. The first three rows stand.)* Decision 3 says the ⋯ menu "is removed". It is read with decision 9 and the pick: the menu leaves the top left, and its rows live on in 概览's header. @@ -442,6 +451,8 @@ Two things about 概览 are not decided here, and neither is yet a question: on *(Amended 2026-11-28, card [#37958](https://github.com/objectstack-ai/objectstack/issues/37958), ruling record [comment 7218879913](https://github.com/objectstack-ai/objectstack/issues/37424#issuecomment-7218879913), the maintainer's 「全部按建议」 on the decision card for the full page's open questions: both are decided, and with them where ADR-0146 D3's line per package stands. **(1) Revert and the publish history**: on a read-only package with a pair they act on the pair, the same target as Pending and Publish. Revert is greyed only where nothing can be published (a read-only package with no pair) or the pair has nothing pending. **(2) Export** (option A): with a pair, 概览's Export downloads the pair, labelled as the base's customizations (「导出 HotCRM 的定制」); with no pair it downloads the package, as before. The cost is accepted: once a pair exists the base is not exported from the UI (it comes from the marketplace or from code). The ground: the uninstall refusal (`packages/objectql/src/registry.ts#PackageUninstallExtendedError`) and ADR-0146 D8 item 3 name the pair's export as the way to keep customizations. **(3) 概览's address** stays `/studio//overview`: a package page, not a metadata address, like the default sharing overview's `owd`. The bare `/studio/` and the Studio entry's return to the last package open 概览 too, so opening a package has one landing; both landed on the object list before. This ruling names those two doors only, and one landing for every door is not ruled: the command palette's (⌘K) package entries, an app's design-in-Studio entry (`ui/packages/app-shell/src/utils/appRoute.ts#appStudioDesignPath`), the "Open in Studio" of an app's empty menu, and Setup's doors, which go with the Setup slimming (decision 10; [#37401](https://github.com/objectstack-ai/objectstack/issues/37401)), still open the object list, and that question is put to the maintainer at the merge of this amendment's pull request ([#38318](https://github.com/objectstack-ai/objectstack/pull/38318)). **(4) The line per package**, ` 已定制 n 项 · 已停用 m 项` (ADR-0146 D3; option B), is not on 概览: it stands under the title of the 全部类型 All types page, which already showed the customized count and gains the switched-off count. The detail panel of Setup → Packages is left as it is and goes with the Setup slimming ([#37401](https://github.com/objectstack-ai/objectstack/issues/37401)). Three costs are accepted: the 全部类型 row sits last in the 高级 Advanced fold; "switched off m" has no list to filter to; and the separate re-order count has no home.)* +*(Amended 2026-11-30, card [#38392](https://github.com/objectstack-ai/objectstack/issues/38392), ruling record [comment 7247357556](https://github.com/objectstack-ai/objectstack/issues/37958#issuecomment-7247357556), the maintainer's 「OK」 to 「⌘K、应用里的「在 Studio 中设计」、空菜单和设置页这几个入口,现在打开的还是对象列表。要不要都改成先进概览页?」: one landing for every door is ruled, so item (3)'s "one landing for every door is not ruled" and its list of doors that "still open the object list" no longer describe `main`. Every door that opens a package's Studio lands on `/studio//overview`, not on the object list (`ui/packages/app-shell/src/views/studio-design/studioOverviewAddress.ts#studioPackageOverviewPath`): the command palette's (⌘K) package entries; an app's design-in-Studio entry (`ui/packages/app-shell/src/utils/appRoute.ts#appStudioDesignPath`, where `#appStudioRoutePath` also falls back for the bare app root, a `system` route and an interface list); the "Open in App Studio" of an app's empty menu; and the three doors of Setup → Packages, which are "Open in App Studio" on an authored package's detail panel, the landing after New Package, and "Customize in App Studio" in the customizations section of a read-only base's detail panel. The pair's bare address `/studio/.custom`, landed by [#38318](https://github.com/objectstack-ai/objectstack/pull/38318), lands on its base's 概览 and is covered by this ruling. `/studio//data` stays a working address for the object list (`ui/packages/app-shell/src/views/studio-design/studioAddress.ts#studioHomePath`). The review-changes deep link (`#studioChangesReviewPath`, `/studio//data?changes=review`) still builds that address: it opens the Changes drawer over the object list, and it is read as no door under this ruling, by a seat reading of 2026-11-29 recorded on the pull request that built this, not by a ruling. Built by [#38501](https://github.com/objectstack-ai/objectstack/pull/38501); the census of the doors is pinned in `ui/packages/app-shell/src/views/studio-design/studioDoorsOverview-38392.test.ts`. The amendment of 2026-11-28 is left as written; read its item (3) with this one.)* + ### Placements, and what moves to Setup {#amendment-2026-11-26-moves} Decision 12 draws the line: **Studio develops one package; Setup runs the organization and holds what is global** (maintainer: 「同意」). Five places are settled by it, by decision 6, and by the rulings of the same day on what the two had left open ([comment 7187264388](https://github.com/objectstack-ai/objectstack/issues/37451#issuecomment-7187264388)). A sixth is written for a type that is about to join the menu. @@ -455,7 +466,7 @@ Decision 12 draws the line: **Studio develops one package; Setup runs the organi **The rule of 2026-11-25 is not reworded.** It says that where the maintainer places a type by name, the name decides, and it carried two such placements: `picklist` in 高级, and the three AI types in 常用. `dataset`, `position` and `form` are three more, each in 常用. The three tests still sort every type that no ruling names. -Of the four entries that are not a type, then, one leaves. Diagnostics stays. The organization's own flows (`~org`) keep their entry in 自动化 Automation until the door that moves loose items into a package ships, and retire with it ([Organization-level content](#amendment-2026-11-26-org)). The organization-wide default sharing overview stays in 访问 Access. +Of the four entries that are not a type, then, one leaves. Diagnostics stays. ~~The organization's own flows (`~org`) keep their entry in 自动化 Automation until the door that moves loose items into a package ships, and retire with it ([Organization-level content](#amendment-2026-11-26-org)).~~ *(Amended 2026-11-29, card [#38150](https://github.com/objectstack-ai/objectstack/issues/38150), ruling record [comment 7184753035](https://github.com/objectstack-ai/objectstack/issues/37424#issuecomment-7184753035), question 3: the door shipped, and the organization's own flows retired with it — [Organization-level content](#amendment-2026-11-26-org).)* The organization-wide default sharing overview stays in 访问 Access. Decision 12 also says how the two surfaces speak of each other: whose sharing rules, queues and assignment rules each side shows; a position defined in Studio and assigned in Setup, linked both ways; one vocabulary for a package's source and state. None of that changes a place in the menu, and it is left to its cards. @@ -478,6 +489,8 @@ Decision 11 of the epic, as ruled on its questions 2 and 3 (maintainer: 「同 - **Loose items stay where they are, and one door moves them** (question 3, ruled C). An item that belongs to no package stays legal: it belongs to the implicit environment package (ADR-0150 D1, the fourth bucket), and nothing is renamed or migrated. One new door moves a selection — one item, several, or all — into a package, and runs each through the judges a save runs, judging the selection as a set for the cross-boundary rule of ADR-0150 D3 (a). It reuses the list page that exists. When that door ships, the bulk adopt and Studio's `~org` entry retire together. This replaces the page that sorts loose items one by one, which decisions 11 and 12 planned. Where the new door is opened from is its card's to say. - **What this changes in the menu.** The organization's own flows keep their entry in 自动化 Automation until the door ships. The ⋯ menu keeps "adopt loose items" until then, and loses it then. +*(Amended 2026-11-29, card [#38150](https://github.com/objectstack-ai/objectstack/issues/38150), ruling record [comment 7184753035](https://github.com/objectstack-ai/objectstack/issues/37424#issuecomment-7184753035), question 3: the door shipped, and the bullets above are left as the ruling wrote them. The door is `POST /api/v1/packages/:id/move-in`. Its card opened it from the cross-package list: the "Loose" value of that list's source filter, `/studio/~all/metadata/TYPE?source=loose`, which a banner on Setup's Packages page links to for each type that holds a loose item. Studio's `~org` entry retired with the door, and the scope with it: the menu row, the scope's list, the scope's flow page (the flow designer, which opened a flow of no package full-screen), its 变更 Changes row and the batch publish behind that row. A flow that belongs to no package opens on its item page on the cross-package leg, `/studio/~all/metadata/flow/NAME`, and is still saved in place there; the flow designer opens on a package's flow. Every `/studio/~org/…` address lands on the Loose list of flows, `/studio/~all/metadata/flow?source=loose`. The bulk adopt is retired by a change of its own under that card ([#38545](https://github.com/objectstack-ai/objectstack/pull/38545)), not by the one that retired this entry. ADR-0070's D5 carries its mark of the same date, as the paragraph below asks.)* + ADR-0070 is not edited by this amendment. Where the ruling restates its D1 and D5, the phase-4 cards that carry the ruling out owe that record its marks. ### What the amendment replaces, and what stands {#amendment-2026-11-26-stands} @@ -504,9 +517,9 @@ ADR-0070 is not edited by this amendment. Where the ruling restates its D1 and D Merging accepts them; an objection names the number. -1. **Where 概览 sits.** Decision 6 says it is the first entry. Written here: above the six groups, under no group and in no tier, drawn on every package and never folded. The package-less scope (`~org`) and the cross-package leg (`~all`) open no package and draw no 概览. +1. **Where 概览 sits.** Decision 6 says it is the first entry. Written here: above the six groups, under no group and in no tier, drawn on every package and never folded. ~~The package-less scope (`~org`) and the cross-package leg (`~all`) open no package and draw no 概览.~~ The cross-package leg (`~all`) opens no package and draws no 概览. *(Amended 2026-11-29, card [#38150](https://github.com/objectstack-ai/objectstack/issues/38150), ruling record [comment 7184753035](https://github.com/objectstack-ai/objectstack/issues/37424#issuecomment-7184753035), question 3: the sentence named two scopes. The package-less scope retired with its entry ([Organization-level content](#amendment-2026-11-26-org)), so it names one.)* 2. **What the package row names.** The 2026-11-24 ruling stands: the open package is named by its app where it publishes one, and by its own name where it does not. The switcher's rows are named the same way. Decision 8 speaks of "the app name in the switcher row", which agrees. -3. **What the switcher lists, and where it lands.** It lists packages and nothing else: a pair is folded under its base, and `~org` and `~all` are not rows of it. Picking a package opens that package's 概览. Weighed and not taken: the list of the type the person was on, which the other package may not hold. +3. **What the switcher lists, and where it lands.** It lists packages and nothing else: a pair is folded under its base, and ~~`~org` and `~all` are not rows of it~~ `~all` is not a row of it. *(Amended 2026-11-29, card [#38150](https://github.com/objectstack-ai/objectstack/issues/38150), ruling record [comment 7184753035](https://github.com/objectstack-ai/objectstack/issues/37424#issuecomment-7184753035), question 3: the package-less scope retired with its entry ([Organization-level content](#amendment-2026-11-26-org)), so one scope is left that is not a row.)* Picking a package opens that package's 概览. Weighed and not taken: the list of the type the person was on, which the other package may not hold. 4. **Below 768 px.** The menu is a drawer there, and something must open it. "No top bar" is read as from 768 px up, the way ADR-0146 D5's note reads the app's shell. Below that width the frame keeps what the app's shell keeps: a strip that holds the control which opens the drawer. 5. **The top bar's seventh tenant.** For a package with no app, the bar draws a "create app" button, or a label that says the app waits for a publish. No ruling gives them a home, and this record gives them none. 应用 `app` is a 常用 row, drawn "whether the package holds one or not, so a package without one still shows where the first is made" (2026-11-25), and an app that waits for a publish is counted on Pending. They go with the bar. 6. **Save and Cancel on a page that saves and is not an item.** The pick puts them in the item's header. A page with unsaved edits and no item header — the default sharing overview is one — carries them at the right end of its own title row. diff --git a/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md b/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md index e41d65a4eaa..b39473fd7cc 100644 --- a/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md +++ b/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md @@ -171,6 +171,24 @@ Keys that merely hide/re-arrange correct information (`hideRelatedTab`, `showRef > object key that only hides or only re-arranges still needs its own ruling, above all per-page > show/hide switches. +> **Note (2026-11-30, [#37792](https://github.com/objectstack-ai/objectstack/issues/37792), carried by +> [#38438](https://github.com/objectstack-ai/objectstack/issues/38438)).** The 2026-11-27 note says +> "Neither key is in the spec yet: `ObjectSchema` is strict and refuses both until #37792 lands +> `pinOverview` and #37802 lands `fieldTabs`." The first half is answered, and no decision changes. +> `pinOverview` is in the spec: `ObjectSchema.pinOverview` is an optional boolean +> (`packages/spec/src/data/object.zod.ts#pinOverview`). Absent or `true`, the pin stays derived, as before. +> `false`: the desktop full standard record page never pins, at any width; the overview is its first +> tab, open by default, and its fields lay out by width in up to three columns, also when the +> overview holds a related table. The side preview and a phone draw as before. The reader is +> `ui/packages/plugin-detail/src/synth/recordPageColumns.ts#recordPagePinsDetails`. An object +> extension does not carry the key: `ObjectExtensionSchema` refuses it with guidance that names +> `ObjectSchema.pinOverview`, so the switch is declared by the package that defines the object, and +> its paired `.custom` package does not write it either. Built by +> [#38679](https://github.com/objectstack-ai/objectstack/pull/38679). The second half stands: +> `fieldTabs` is not in the spec, and `ObjectSchema` refuses it until +> [#37802](https://github.com/objectstack-ai/objectstack/issues/37802) lands it. The 2026-11-27 note +> is left as written; read that sentence with this note. + ### 3. Deletions (all evidenced zero-author) - **`detail` block removed from `ObjectSchema`** — all three typed keys. `renderViaSchema` retires *together with* the legacy monolith renderer path in objectui (separate execution PR; the key is only that path's steering wheel, deleting it alone saves nothing). `hideReferenceRail`/`hideRelatedTab` are removed outright (the former is a proven no-op for spec authors; the latter's raison d'être — overriding rail/tab dedup — died with the rail). diff --git a/docs/adr/0087-metadata-protocol-upgrade-contract.md b/docs/adr/0087-metadata-protocol-upgrade-contract.md index 63c598647e4..d71ca788aca 100644 --- a/docs/adr/0087-metadata-protocol-upgrade-contract.md +++ b/docs/adr/0087-metadata-protocol-upgrade-contract.md @@ -1,6 +1,6 @@ # ADR-0087: Metadata protocol upgrades for AI consumers — conversion over notification, executable migrations, machine-verifiable upgrades -**Status**: Accepted (2026-07-04, #2582) · trued up to as-built 2026-07-15 (see Addendum) · **Amended** (2026-09-30, #20390 ruling A — the artifact-ingestion window decides per entry by each retired conversion's `retiredAfter`; see the amendment note under the 2026-09-13 addendum's window bullet) · **Amended** (2026-10-09, #22449 ruling B′ — the two D4 projections, the per-major section of `spec-changes.json` and the protocol upgrade guide, are generated at publish rather than committed; see the amendment note under D4, which says what is generated where and where each part landed, and the struck clauses in the P2 phase-status bullet) · **Amended** (2026-10-13, #23038 — the artifact-ingestion window's third disjunct, landed as `58f5c90999`: a floor that is the first release of a major replays that major's conversion step, verdict `'converted-major-step'`; see the 2026-10-13 amendment note under the 2026-09-13 addendum's window bullet) · **Amended** (2026-10-27, #26220, the maintainer's decision A: D8's predicate 4 gains an index-signature limb, and D9's predicate 1 maps a `src/index.tsx` source entry; see the 2026-10-27 amendment notes under D8's predicate 4 and under D9's unmappable-entry paragraph) · **Amended** (2026-10-27, #26220, ruling A on PR #26365, comment `6439038287` — D9 gains a whole-package operand, `#*`, for a published package deleted at HEAD; see the second 2026-10-27 amendment note under D9's unmappable-entry paragraph) · **Amended** (2026-11-14, #30598, the maintainer's decision A narrowed, record `6885400963` — D9's three operands take a literal subpath key of the `exports` map, `/#…`, and a wildcard key is refused by name; see the 2026-11-14 amendment note under D9's unmappable-entry paragraph) · **Amended** (2026-10-26, #25767 ruling D2 = A, scoped by ruling 6434038284 of 2026-10-27 — a retirement kit (the `retiredKey()` tombstone and its D2 conversion with fixtures) lives one protocol major after the one it retired in and is then removed; a removed key is refused as a strict unknown key whose refusal names the protocol upgrade guide; the kit ages out, the chain's step stays, and the support floor stays 16; see the 2026-10-26 addendum, which also amends the "never deleted" wording in D2 and the conversion "forever" in the 2026-07-31 and 2026-09-13 addenda) +**Status**: Accepted (2026-07-04, #2582) · trued up to as-built 2026-07-15 (see Addendum) · **Amended** (2026-09-30, #20390 ruling A — the artifact-ingestion window decides per entry by each retired conversion's `retiredAfter`; see the amendment note under the 2026-09-13 addendum's window bullet) · **Amended** (2026-10-09, #22449 ruling B′ — the two D4 projections, the per-major section of `spec-changes.json` and the protocol upgrade guide, are generated at publish rather than committed; see the amendment note under D4, which says what is generated where and where each part landed, and the struck clauses in the P2 phase-status bullet) · **Amended** (2026-10-13, #23038 — the artifact-ingestion window's third disjunct, landed as `58f5c90999`: a floor that is the first release of a major replays that major's conversion step, verdict `'converted-major-step'`; see the 2026-10-13 amendment note under the 2026-09-13 addendum's window bullet) · **Amended** (2026-10-27, #26220, the maintainer's decision A: D8's predicate 4 gains an index-signature limb, and D9's predicate 1 maps a `src/index.tsx` source entry; see the 2026-10-27 amendment notes under D8's predicate 4 and under D9's unmappable-entry paragraph) · **Amended** (2026-10-27, #26220, ruling A on PR #26365, comment `6439038287` — D9 gains a whole-package operand, `#*`, for a published package deleted at HEAD; see the second 2026-10-27 amendment note under D9's unmappable-entry paragraph) · **Amended** (2026-11-14, #30598, the maintainer's decision A narrowed, record `6885400963` — D9's three operands take a literal subpath key of the `exports` map, `/#…`, and a wildcard key is refused by name; see the 2026-11-14 amendment note under D9's unmappable-entry paragraph) · **Amended** (2026-10-26, #25767 ruling D2 = A, scoped by ruling 6434038284 of 2026-10-27 — a retirement kit (the `retiredKey()` tombstone and its D2 conversion with fixtures) lives one protocol major after the one it retired in and is then removed; a removed key is refused as a strict unknown key whose refusal names the protocol upgrade guide; the kit ages out, the chain's step stays, and the support floor stays 16; see the 2026-10-26 addendum, which also amends the "never deleted" wording in D2 and the conversion "forever" in the 2026-07-31 and 2026-09-13 addenda) · **Amended** (2026-11-28, #37447 and its ADR half #38328, the maintainer's decision 「新增第八类」 of 2026-11-26, recorded on PR #37433 as comment `7183687803` — the changeset disposition vocabulary gains an eighth category, `runtime-member-retyped`, for a member that stays on a published type while its declared type changes; it is D9's sibling, proven by the compiler at both revisions, and D8's predicate 4 gains no limb for it; see the 2026-11-28 addendum, D10, and the 2026-11-28 note under D8's predicate 4) **Deciders**: ObjectStack Protocol Architects **Builds on**: [ADR-0059](./0059-third-party-backward-compatibility-gates.md) (layered backward-compat gates — this ADR is its consumer-facing sequel), [ADR-0078](./0078-no-silently-inert-metadata.md) (no declarable-but-unenforced metadata — the un-checked `engines.protocol` is exactly this class), [ADR-0025](./0025-plugin-package-distribution.md) (§3.2 `engines.protocol` / `engines.platform` compatibility ranges, §3.10 #3 protocol-first check order), [ADR-0033](./0033-ai-assisted-metadata-authoring.md) (the authoring population this ADR designs for), [ADR-0049](./0049-no-unenforced-security-properties.md) (enforce-or-remove), [ADR-0054](./0054-runtime-proof-for-authorable-surface.md) (prove-it-runs), AGENTS.md Prime Directive #12 (contract-first, no consumer-side dialect fallbacks — §"Why the conversion layer does not violate PD #12" draws the line) **Consumers**: `@objectstack/spec` (protocol version constant, conversion layer, deprecation/change registries), `@objectstack/cli` (`validate`, `doctor`, `migrate meta`), the runtime metadata loader (handshake + conversion), `@objectstack/mcp` (the AI-native change/migration surface), `@objectstack/create-objectstack`, the Release workflow, and every third-party consumer — whose maintainer is assumed to be an **AI agent** @@ -754,6 +754,7 @@ gate's log and its `--list` output. + ``` **The vocabulary is closed, and every exemption is re-verified on every run** — an @@ -772,14 +773,17 @@ refuses it; whether the fix is written as an arrow, a table or a sentence does n change that. The fix is a `registered` semantic entry, one file under `packages/spec/src/migrations/entries/semantic/`, or a category resting on a checked fact when one is true: `already-registered`, `unpublished`, `runtime-interface-only`, -`type-surface-only`, `runtime-export-retired`. If the change refuses nothing an author +`type-surface-only`, `runtime-export-retired` and, since 2026-11-28, +`runtime-member-retyped`. If the change refuses nothing an author could write, the `Metadata-protocol:` line is what is wrong, not the disposition. `added`, `semantic` and `none` keep the exemption, and a changeset already breaking at the branch point is inherited and never re-judged); `runtime-interface-only` is the subject of the rest of this addendum; `type-surface-only` — the sixth, added -2026-08-30 — is the subject of the addendum after it; and `runtime-export-retired` — +2026-08-30 — is the subject of the addendum after it; `runtime-export-retired` — the seventh, added 2026-10-12, whose whole-package operand `#*` was added -2026-10-27 (#26220) — is the subject of the addendum after that. The checks live in +2026-10-27 (#26220) — is the subject of the addendum after that; and +`runtime-member-retyped` — the eighth, added 2026-11-28 (#37447) — is the subject of +the addendum after that one. The checks live in [`scripts/check-adr-0087-registration.mjs`](../../scripts/check-adr-0087-registration.mjs), which is also where each one's measured history is written down. @@ -1025,6 +1029,12 @@ at all. A regression pin in the gate's `--self-test` asserts that the #6048 shap refused by predicate 4 specifically, so the founding case can never become claimable. +> **2026-11-28 note** (#37447) — a member of a published type retyped from one concrete +> type to another (PR #37433: `AuthClient.updateUser` in `@object-ui/auth`, +> `Promise` to `Promise`) is refused by predicate 4, and the maintainer's +> decision 「新增第八类」 gave that class a category of its own, `runtime-member-retyped` +> (the eighth; see D10), instead of a limb here. Predicate 4 reads exactly as it did. + #### What this does not decide **Whether the HEAD type is the *right* type.** Whether the bound contract is what @@ -1314,6 +1324,191 @@ refused rather than assumed. are unchanged; the arrowless line stays outside the detector's reach, stated as such in the gate's residual-blind-spot paragraph, and is read only by this category. +## Addendum (2026-11-28) — the eighth category: a published runtime MEMBER retyped (#37447) + +The vocabulary above gained an eighth answer: + +```text + +``` + +Provenance: the maintainer's decision 「新增第八类」 on a decision card (2026-11-26T05:38Z) +that asked 「已发布 TS 类型从具体类型收窄,ADR-0087 用哪个处置类别?」. The card's text for that +option is 「ADR-0087 增补 runtime-member-retyped,另开受管卡教门禁;#37433 保持 draft,等门禁卡合并后带新标记落地」. +It is recorded on PR #37433 as comment `7183687803` and in the body of #37447. + +### The dead end it closes + +The worked example is PR #37433. `AuthClient.updateUser` in `@object-ui/auth` declared +`Promise` while the server answers a receipt, and the member now declares +`Promise`. The member stays on a published type and its declared type moves from +one concrete type to another, so the changeset declares `**BREAKING**` truthfully and +owes the FROM → TO line a breaking changeset carries. Measured at `4cb162bfb9`, with +that PR's diff (head `ac218b2489`) applied to it and driven through the shipping gate +under each disposition: + +| disposition | outcome | +|---|---| +| `registered` | refused — no id is new in the diff, and none could honestly be written: `objectstack migrate meta` has nothing to rewrite in a caller's code. | +| `not-required (already-registered )` | admitted on any id that pre-dates the merge base, the door D8's table records: the gate checks that the id resolves and is old, never that the entry covers this change. No entry does. | +| `not-required (unpublished)` | refused — `@object-ui/auth` publishes. | +| `not-required (type-surface-only …)` | refused by predicate 4, under the bare and the dotted spelling alike — the return annotation was already concrete at the merge base (`Promise`). | +| `not-required (runtime-export-retired …)` | refused by predicate 1 — `AuthClient` still has the member at HEAD, so nothing retired. | +| `not-required (no-migration-prescription)` | refused when the fix is written as a labelled `FROM → TO` arrow line, which the detector reads. Admitted on the PR's own body, which writes the pair as `FROM:` and `TO:` on two lines, and on an arrowless `FROM … TO …` line: the detector reads neither. | +| `not-required (runtime-interface-only …)` | the same two outcomes — it inherits that refusal, and its four predicates read the symbol at HEAD and say nothing about what changed. | + +So a changeset that writes its fix where the detector reads it has no category that is +true of it, and one that does not is held by a detector **miss**: the shape D7 retires, +and the one D9 closed for a retirement. D8's exit stays shut as well, because the refusal +by predicate 4 is the one D8 says is never weakened. + +### D10 — a published runtime member that is kept and retyped is compiler-carried, and the gate proves the retyping with the compiler + +The channel argument is D7's, D8's and D9's: the affected party is a TypeScript +consumer, and the compiler reports the break at their own site. Measured on the worked +example's shape, that is `TS2339` at a caller that reads the result and `TS2322` at a +host that passes in its own implementation. The ledger has no metadata to rewrite. + +**The category is D9's sibling.** What D9 proves about a member that left, this category +proves about a member that stayed. It takes D9's member operand, D9's compiler reading of +the package's published entry at both revs, and D9's predicates 2 and 3. Only predicate 1 +is its own. + +**Operands.** `#.` names a member of a type the package's +published entry exports, in the canonical spelling D9 fixed (a member of an exported +value is read too, on that value's type, as D9's reader reads it), and +`/#.` names one behind a literal subpath key of the +`exports` map, read as D9's 2026-11-14 amendment reads that key. A member is the only +operand. `#` and `#*` are refused by name: the decision is +about a member that is kept, and an export or a package that left the entry is +`runtime-export-retired`. + +An author may claim the category when, for every operand, all three of these hold — +re-verified on every run and checked by name (`present-at-both-type-differs`, +`no-metadata-surface`, `from-operands-named`): + +1. **present-at-both-type-differs** — the type is exported by the package's published + entry at the merge base and at HEAD, the member is on it at both + (`getPropertiesOfType`), and the member's declared type differs between the two. The + reading is D9's predicate 1 reading: the TypeScript compiler, a Program over the + package's source entry at each rev, with the entry located as D9 locates it and an + unmappable one refused as D9 refuses it. The declared type is the type the checker + prints for the member, with whether the member is optional, and the two printings are + compared as text. The Program is compiled with `strictNullChecks`, so `| null` and + `| undefined` are part of what is compared. Refused, never guessed: a member that is + gone at HEAD (it was retired, and the refusal names `runtime-export-retired`), a + member the diff adds (nothing published was retyped), and a member whose type rests, + at either rev, on what the reader cannot resolve **where that leaves a trace**. Two + traces are read, on the member's own declaration and on the type printed for it: a + name that does not resolve, and more `any` in the printing than the member's own + declarations write. A bare reference to an unresolved type prints as the name written + and an unresolved value prints as `any`, which is how either shows in an inferred + type, behind a local alias or on a member with no declaration of its own; SAME and + DIFFERS would both be guesses there. An `any` the declaration writes itself is + compared as written. A type that rests on something unresolved and leaves neither + trace is compared, not refused; "What this does not decide" names the roads. +2. **no-metadata-surface** — D9's predicate 2, asked at **both** revs because the + operand exists at both: neither the type nor the member is declared in a `*.zod.ts`, + under `packages/spec/src/contracts/` or in an object definition, the type is not a + Zod projection, and no metadata surface references it in code. +3. **from-operands-named** — D9's predicate 3, unchanged: the FROM → TO block names + **exactly** the named operands, each spelled `Type.member` as in the marker. Every + FROM operand is a named one, and every named one has a FROM side. + +**It inherits the `no-migration-prescription` refusal, as D9 does.** Predicate 3 reads +the FROM side of every rewrite the body writes, sets exactly those lines aside and runs +the same prescription detector over what is left, and anything it still finds is +refused. Nothing the detector refuses today becomes claimable unless every operand it +rests on was proven retyped by predicate 1 and clear of metadata by predicate 2. +`type-surface-only` stays the only category exempt from that refusal. + +**It does not go through D8's text walker.** `type-surface-only` finds a member by a +structural walk over a masked projection of one file, which is why its reference is +`#..`. This category names the package and asks the compiler for the +member on the exported type, so no file is named and no source text is walked. + +⛔ **D8's predicate 4 is not weakened.** The decision adds a category instead of a limb. +A concrete base is still refused under `type-surface-only`, by predicate 4 and with the +founding-case refusal, and the gate's `--self-test` keeps asserting that on the worked +example's own shape: a concretely typed arrow property retyped is not narrowed-from-erased. +The maintainer's ruling of 2026-08-30 (#13080), 「豁免的安全性由谓词④承载,保持豁免是收窄而非洞」, +stands as written. This category needs no such payment, because it is not exempt from the +prescription refusal. + +**D9's deviation carries over with its machinery.** A merge base has no build output, +so the member is read on the **source** entry that generates the public `.d.ts`, not on +the `.d.ts` itself. For D9's question, which names the entry exports, the two agree. For +a member's type they can part: a `private` class member is on the source type, and its +type is absent from the published declaration. The gate reads the source and does not +tell such a member from a public one. + +### The worked example under this category + +By the decision, PR #37433 lands carrying this category's marker: one marker, +`runtime-member-retyped @object-ui/auth#AuthClient.updateUser`, and its fix written in a +shape predicate 3 reads, with `AuthClient.updateUser` on the FROM side. Its body at head +`ac218b2489` writes the pair as `FROM:` and `TO:` on two lines, which predicate 3 names +and refuses rather than reads, so that pair becomes one `FROM … TO …` line. On that line +every code span between `FROM` and `TO` is read as a FROM operand, so the old type cannot +stand there in backticks: only `AuthClient.updateUser` does, and both types are written +after `TO`. + +### What this does not decide + +**The direction of the change.** The predicate is "differs". Whether the new type is +narrower, and whether a given consumer stops compiling, is the compiler's to deliver at +the consumer's own site. The changeset declared the break; the gate proves that the named +member's declared type is not what it was. + +**A change inside a type the member names.** The comparison is of the member's own +printed type. A member that still declares `Promise` was not retyped when +`AuthUser` changed shape; the member of `AuthUser` that changed is the operand to name. + +**Whether the HEAD type is the right type.** As under D8, that is a question about a +producer, settled by driving it. + +**A member whose type reaches outside the package.** The reader resolves the package's +own files and `lib.es2022`, and of another workspace package only a root entry the +package re-exports, as D9 reads it. A member whose declaration names a type imported from +another package, a DOM type or a React type is refused as unprovable, and so is one whose +type is inferred through a value from outside where that shows in the printed type (the +next item names where it does not). On the worked example's own interface, +`AuthClient.describeDelegableScope` names `DelegableScope` from +`@objectstack/spec/contracts` and could not be claimed. Resolving such an import at both +revs waits for its own case. + +**A type that rests on something unresolved without a trace.** Predicate 1 reads traces: +an unresolved name in the member's own declaration or in the printed type, and a surplus +`any` in the printed type. A type can rest on something unresolved and leave neither. It +is then compared, and SAME or DIFFERS is a reading of the reader's blindness. Predicates 2 +and 3 hold on all of it, so no metadata prescription gets through; what can be wrong is a +"same type" refusal or an admitted retyping. Three roads, each measured through the gate: + +- **(a) The `any` reading is a count, not a position.** A written `any` that never + prints (`keyof any`, a conditional over `any`, the implementation signature under an + overload, a setter beside its getter) leaves room for one the reader produced. That one + arrives through a local alias or by inference: a method that takes `k: keyof any` and + returns an unresolved call writes one `any`, prints one, and is compared. +- **(b) An operator consumes the unresolved type behind a local alias.** `keyof` of an + unresolved type is `string | number | symbol`, so no name and no `any` prints, and no + written `any` is needed. A conditional type that checks an unresolved name prints its + branches the same way. Written on the member itself, the same `keyof` is refused, + because the declaration then names the unresolved type. +- **(c) Inference consumes it.** An unresolved value passed to a local overloaded + function matches the first overload, and the member prints that overload's return type. + No reader of traces sees this one. + +The three are carried by #38379. Until it lands this item is the contract: on these roads +the gate compares, and its SAME or DIFFERS proves nothing. + +**An export itself, a wildcard subpath key or a static member.** An exported function or +constant whose own declared type changed is not a member of an exported type and is not +read; that waits for its own case. The bounds on a subpath key and on a class's static +side are D9's. + +**The completeness of the claim.** Like every category above, the gate judges the +operands named, not every member the diff retyped. + ## Addendum (2026-09-13) — the artifact-ingestion door opens a versioned window (#12772) The addenda above reach authored source and metadata at rest in `sys_metadata`. diff --git a/docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md b/docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md index e5ffd816376..d93b82248c7 100644 --- a/docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md +++ b/docs/adr/0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md @@ -910,6 +910,34 @@ name suffixed, the base untouched (N-23c). > write a key, the App's pair is served ([D3](#d3)). The 2026-11-22 note is left as written; read "the base's > arrangement stays the base's" with this note. +> **Note (2026-11-30, [#36548](https://github.com/objectstack-ai/objectstack/issues/36548), built by +> [#38706](https://github.com/objectstack-ai/objectstack/pull/38706); carried by +> [#38438](https://github.com/objectstack-ai/objectstack/issues/38438)).** One sentence of the note above no longer +> describes every door: "A `.custom` package that is not the object's pair is not applied, and the boot log names it." +> Maintainer ruling (record +> [`7268226134`](https://github.com/objectstack-ai/objectstack/issues/36548#issuecomment-7268226134); this note is its +> item 5, arm (c)), on the question 「非配对的定制包写页面排布,保存和安装时要不要当场拒绝?」, verbatim: +> 「保存和安装都拒绝」. So at every door that can read the installed packages, a `.custom` package that is not the +> object's pair is refused when its object extension writes `fieldGroups`, `relatedLists` or `actionLayout`: at the +> save, the restore and the draft promotion of the item (`VALIDATION_ERROR` / 400), and at marketplace install +> (`VALIDATION_ERROR` / 422, with nothing installed). A package duplicate saves each copied row through the save door, +> so it meets the same refusal row by row, and it answers in its own shape: the refused row is listed in the +> duplicate's `failed[]` with the save door's sentence as its `error` and no code, and nothing is stored for that row +> (`packages/metadata-protocol/src/protocol-package-commits.ts#duplicatePackage`; pinned in +> `packages/objectql/src/protocol-custom-arrangement.test.ts`). The refusal names the object's pair in its +> first sentence, or says that the object has none, and no error code is minted. The judge is the one the note above +> names, now asked with the lookup the registry fold serves by +> (`packages/metadata-core/src/customization-pair-lookup.ts#pairsOf`, of the object's owner). A per-package pair an +> earlier version created stays admitted on its own package's objects. A target whose owner the door does not know +> (at install, neither the delivered artifact nor the registry names it) is not judged by role, by item 3 of the same +> ruling; there the registry fold's skip is the backstop, as in the paragraph below. +> +> Where no door can read the installed packages, the sentence stands as written: `os validate` and `os build`, which +> keep the suffix rule alone, a code-defined stack booted without them, and a stack that names no package id. There +> the writer is still not applied and the boot log names it, because boot never refuses. With this note, the note +> above agrees with the note below ("Any other package is refused"). The upgrade guidance is the migration entry +> `non-pair-custom-arrangement-refused`. The note above is left as written; read that sentence with this note. + > **Note (2026-11-24, [#36366](https://github.com/objectstack-ai/objectstack/issues/36366), built by > [#36629](https://github.com/objectstack-ai/objectstack/pull/36629)).** `actionLayout` is the third key of that exception > (`packages/spec/src/data/field-customization.ts#CUSTOM_ARRANGEMENT_KEYS`). It arranges an object's actions for one diff --git a/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md b/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md index e75a9675a09..ae3f83a818a 100644 --- a/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md +++ b/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md @@ -266,6 +266,14 @@ A caller with no package (an environment item, a context-free door, an MCP clien > > Pins: `packages/objectql/src/disabled-holder-packageless-row-doors.test.ts` ("[ADR-0150 D3, the 2026-11-26 note] the per-item publish and the rollback naming no package, while every holder is disabled"). The upgrade guidance is the migration entry `disabled-holder-package-less-row-bare-write-refused`. +> **Amendment note (2026-11-30, #34261 — PR #38633; carried by #38438).** One more sentence of the 2026-11-26 note above no longer describes `main`, the last of its bullet "Reads stay the missing name": "Three reads at `_env` still answer `409` at this head (`?state=draft`, `?preview=draft`, `?layers=true`), and card #34261 carries their move to `404`." The move has landed. No decision changes: the three reads now answer what that bullet gives the other reads. +> +> While every package that holds the name is disabled, `_env` answers each of the three its own `404`, naming no package: an admitted `?state=draft` (a caller who may read pending drafts) answers `404 NO_DRAFT`, as the by-name draft read does, and an admitted `?preview=draft`, and `?layers=true`, answer `404 RESOURCE_NOT_FOUND`. A caller the draft switches do not admit is answered the plain read's `404`, as before. `RestServer` and the runtime dispatcher answer alike (`packages/rest/src/meta-qualified-item-route.ts#admitEnvironmentAddress`, `packages/runtime/src/domains/meta.ts#admitEnvironmentAddress`). The door judges the read the caller is answered: a draft read reaches its own `404` only when the plain read and that draft read both withhold the name, and the layered view is judged by the plain read. A package-less draft stored under such a name is the disabled holder's customization and is withheld with it. Once the holder is enabled again, each of the three refuses `409` and names it, as before. +> +> One `409` stays, as a leak guard. Where an enabled package holds a stored draft of the name that the plain read does not see, the bare draft reads serve that draft to an admitted builder, so `_env` keeps the `409` for `?state=draft` and `?preview=draft` and never serves the draft. The layered view withholds it and answers its `404`. +> +> Pins, per type, in `packages/rest/src/meta-qualified-item-route.test.ts` and `packages/runtime/src/domains/meta-qualified-item-read.test.ts`: "only a disabled holder — `_env` with an admitted draft switch or the layered view answers its own 404, naming no package; re-enabled, each refuses naming it", and its control, "only a disabled holder in the registry, and an enabled package's stored draft — the bare draft reads serve it, `_env` draft reads refuse 409 and the layered view answers 404, never that draft". + **Two consequences of the rule, as R (#31637) implements it.** - **(a) A package caller never resolves to an environment-authored item by bare name.** A package cannot declare a dependency on the environment, so an environment item is in no package's closure. A name that only an environment item holds is refused for a package caller (`outside-closure`), and the refusal names the environment as the holder. **This is a declared narrowing**, added by this record within the letter of the ruled rule. Today `getItem` serves the bare slot first to every caller (D4's overlay row), so a package flow's `template: welcome` filled by an environment-authored template is served today and refused once its reader is wired. It is carried by the E rows that wire a package caller (E1–E6, E8) and by U only through G1's door: Studio's held id travels as `?package=` (`client.meta.getItem`), so at the door it is the exact qualifier (D5), never a caller. G1 declares what that refuses. It cannot be measured on a package tree (HotCRM holds no environment), so the D10 upgrade report names each such reference as the migration finds it. @@ -306,6 +314,8 @@ Every runtime index that keys a bucket 2 or 3 item by bare name gains the packag > **Amendment note (2026-11-10, #32060 item 6 — PR #32067; it closes when B #31696 lands).** Between G1 and B #31696 the engine arms one flow per bare name: a flow name two packages hold is refused at registration, naming both, and nothing is armed (`packages/services/service-automation/src/engine.ts#registerFlow`, #31677 Q1). So the flow row above ("all same-named flows arm") and the covered-types sentence that a package-qualified address reaches the intended holder do not hold for flows yet: the address of such a name answers the same `409` as its bare path (`packages/runtime/src/domains/automation-address.ts#admitAutomationAddress`). D5's two-holder text stays the end state, and B #31696 owns the engine re-key (epic seat reading E3, answered in record [`6755708575`](https://github.com/objectstack-ai/objectstack/pull/32001#issuecomment-6755708575) on PR #32001). +> **Amendment note (2026-11-30, #34891 — PR #38652; carried by #38438).** The table keys the engine's flow map by `(package, name)` and says nothing of the status rows read from it. No decision changes; this note records what those rows carry. Each row of `getFlowRuntimeStates()`, and so each row of `GET /automation/_status`, carries the `packageId` of the engine slot it reads (`packages/spec/src/contracts/automation-service.ts#FlowRuntimeState`; the key is absent for a flow no package holds). So `(packageId, name)` names one row, and a reader that means one package's flow of a name two packages hold picks its row by both, never by `name` alone. The toggle door (`POST /automation/:name/toggle` and its namespaced address, `/automation/:ns/:name/toggle`) reads back that row for the slot it switched, so on such a name it answers the switched flow's stored state. It echoes the request only where the reading cannot name the switched flow: a service that does not implement the read, a read that holds no row of the flow, or, on a door serving no package's slot, two or more rows of the name. Code: `packages/services/service-automation/src/flow-definitions.ts#getFlowRuntimeStates` and `packages/runtime/src/domains/automation.ts`. Pins: `packages/services/service-automation/src/flow-slots-per-package.test.ts` ("[ADR-0150 D4] the status rows carry their slot's package") and `packages/runtime/src/domains/automation-addressed-route.test.ts` ("[ADR-0126 §7.2] the toggle door answers the switched slot, on a name two packages hold"). + Hooks bind by event and object and already carry `packageId`. Only `isArtifactShippedHook` (name-only) gains the package. **An owner-less engine function registration is the platform's holder, not the environment's item** (the epic seat's review of R2, record [`6729484996`](https://github.com/objectstack-ai/objectstack/pull/31733#issuecomment-6729484996) item 2, refined by its re-review [`6730444942`](https://github.com/objectstack-ai/objectstack/pull/31733#issuecomment-6730444942) item 1). An `engine.registerFunction` with no owning package is code a plugin or host registers, never an item authored in the environment (bucket 4 is authored metadata). It resolves like `sys`, reachable from every caller's closure: diff --git a/docs/adr/0159-forms-are-their-own-metadata-type-public-forms-are-form-items-view-is-lists-only.md b/docs/adr/0159-forms-are-their-own-metadata-type-public-forms-are-form-items-view-is-lists-only.md index 8e335e5d959..4a8863c68ee 100644 --- a/docs/adr/0159-forms-are-their-own-metadata-type-public-forms-are-form-items-view-is-lists-only.md +++ b/docs/adr/0159-forms-are-their-own-metadata-type-public-forms-are-form-items-view-is-lists-only.md @@ -1,6 +1,6 @@ # ADR-0159: Forms are their own metadata type — a `form` item is a named form with a consumer, public forms are `form` items, and `view` is lists only -**Status**: Proposed — 2026-11-24, written for objectstack#36868 on the maintainer's ruling of that day (ruling records [`7123091354`](https://github.com/objectstack-ai/objectstack/issues/36444#issuecomment-7123091354) on #36444 and [`7123091586`](https://github.com/objectstack-ai/objectstack/issues/36505#issuecomment-7123091586) on #36505). **The five merge questions are ruled, all option A** (ruling record [`7131569242`](https://github.com/objectstack-ai/objectstack/issues/36868#issuecomment-7131569242) on #36868, 2026-11-24; [the questions](#the-five-merge-questions-as-ruled)): the record now carries no open default. `docs/adr/**` is Tier H (Prime Directive #14): this record becomes **Accepted** by an authorized approval or the maintainer's merge of the PR that carries it, and is in force from that merge. **This record declares; it implements nothing** — no schema, no code, no changeset; every mechanism below is cut as a card after the merge ([Execution plan](#execution-plan-after-acceptance)). It **amends** [ADR-0017](./0017-object-has-many-view.md) (`viewKind` becomes list-only; the form arm is tombstoned on [D7](#d7)'s schedule) and [ADR-0146](./0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md) D2 (`form` joins the overridable types) — each record's Status line carries the dated pointer. **Revised 2026-11-25** to record five maintainer rulings and two seat decisions made after PR #36957 merged (ruling record [`7142585849`](https://github.com/objectstack-ai/objectstack/issues/36868#issuecomment-7142585849) on #36868, 2026-11-24T19:46Z, and its addendum [`7142658348`](https://github.com/objectstack-ai/objectstack/issues/36868#issuecomment-7142658348), 19:49Z; the words are under "Decided by"): the type is added in major 19 and no release carries the dual-read; the major's upgrade command runs the stored-row ceremony and then switches, all or nothing; that upgrade removes stored internal record forms; the major's release notes lead with #36425's effect; HotCRM moves its sources with its own bump to the major. Each revised sentence carries the record's id and the ruling's number, and nothing else in this record is re-opened. +**Status**: Proposed — 2026-11-24, written for objectstack#36868 on the maintainer's ruling of that day (ruling records [`7123091354`](https://github.com/objectstack-ai/objectstack/issues/36444#issuecomment-7123091354) on #36444 and [`7123091586`](https://github.com/objectstack-ai/objectstack/issues/36505#issuecomment-7123091586) on #36505). **The five merge questions are ruled, all option A** (ruling record [`7131569242`](https://github.com/objectstack-ai/objectstack/issues/36868#issuecomment-7131569242) on #36868, 2026-11-24; [the questions](#the-five-merge-questions-as-ruled)): the record now carries no open default. `docs/adr/**` is Tier H (Prime Directive #14): this record becomes **Accepted** by an authorized approval or the maintainer's merge of the PR that carries it, and is in force from that merge. **This record declares; it implements nothing** — no schema, no code, no changeset; every mechanism below is cut as a card after the merge ([Execution plan](#execution-plan-after-acceptance)). It **amends** [ADR-0017](./0017-object-has-many-view.md) (`viewKind` becomes list-only; the form arm is tombstoned on [D7](#d7)'s schedule) and [ADR-0146](./0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md) D2 (`form` joins the overridable types) — each record's Status line carries the dated pointer. **Revised 2026-11-25** to record five maintainer rulings and two seat decisions made after PR #36957 merged (ruling record [`7142585849`](https://github.com/objectstack-ai/objectstack/issues/36868#issuecomment-7142585849) on #36868, 2026-11-24T19:46Z, and its addendum [`7142658348`](https://github.com/objectstack-ai/objectstack/issues/36868#issuecomment-7142658348), 19:49Z; the words are under "Decided by"): the type is added in major 19 and no release carries the dual-read; the major's upgrade command runs the stored-row ceremony and then switches, all or nothing; that upgrade removes stored internal record forms; the major's release notes lead with #36425's effect; HotCRM moves its sources with its own bump to the major. Each revised sentence carries the record's id and the ruling's number, and nothing else in this record is re-opened. **Revised 2026-11-29** by card ⑤a, to record five maintainer rulings on #37111, each in [D7](#d7) where it applies: an internal record form served ahead of a package-less row that carries a public link (ruling record [`7249158572`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7249158572), D7-d); the destination of a form row bound to a package that ships no form of its name (ruling record [`7250977204`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250977204)); stored drafts, and the per-package pair of an earlier version that holds the namespace (ruling record [`7250982640`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250982640), D7-c); the reach of the second ruling, a row the read serves at another address than the package it is bound to (ruling record [`7254350842`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7254350842), D7). One reading of this record stands beside them, marked where it stands and named in TL;DR 10: the first ruling's answer for any other linked row behind such a form (D7-d). **Revised 2026-11-30** by card ⑤a, to record one maintainer ruling on #38661 and the seat steps under it, in [D7](#d7): a stored form row the read serves at two addresses of one App is moved at neither and holds the upgrade, and the same hold covers every slot of a pair that more than one plan claims (ruling record [`7265816895`](https://github.com/objectstack-ai/objectstack/issues/38661#issuecomment-7265816895)); the class of the hold's cause, and the same hold for a row more than one address serves where those addresses would not all move it or all remove it, are the owning seat's steps, not the maintainer's words. So is one reading of the ruling of 2026-11-29 (`7249158572`) together with the ruling of 2026-11-30: a form row kept behind an internal record form that an address leaves in place holds the upgrade, at that address too, where another address serves it and would move it or remove it; and, by the same reading, the row a further address serves holds the upgrade where its plan would fold, move or remove a row so kept or that internal form, or write a folded row's withdrawal into either. Each is an exception to that ruling record's "The upgrade is not blocked", and each is the owning seat's step, for the approver to accept with the record or strike ([D7](#d7), D7-d). - **Date**: 2026-11-24 - **Decided by**: the maintainer, 2026-11-24, verbatim and untranslated, as the card and the two ruling records carry them: @@ -16,6 +16,12 @@ 4. 「要在发版说明里重点提示」 5. On HotCRM: 「HotCRM 的迁移跟着它升级到大版本那次一起做」「卡⑤ 不再等 HotCRM 卡,否则两边会互相等待。」 - Two seat decisions stand under those rulings. They are the owning seat's, not the maintainer's words, and are in his veto window: the upgrade's move is all-or-nothing with the switch (`7142585849`); the ceremony's `--apply` is reached only from the upgrade command, and the standalone command is read-only (`7142658348`). + - 2026-11-29, on card ⑤a (#37111), each by decision tap after an independent analysis; entered here by the revision of 2026-11-29: + 1. An internal record form served ahead of a same-named package-less row that carries a public link: 「两行都不动,写进报告」 (ruling record [`7249158572`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7249158572); [D7](#d7), D7-d). + 2. A stored form row bound to a read-only package that ships no form of the name: 「B 搬进定制包(推荐)」 (ruling record [`7250977204`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250977204); [D7](#d7)). + 3. Draft rows with form content: 「A 留下并提醒(推荐)」; and the per-package pair of an earlier version that holds the namespace: 「B 只改文字,不开卡」 (ruling record [`7250982640`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250982640); [D7](#d7), D7-c). + 4. The reach of the second ruling, a row the read serves at another address than the package it is bound to: option A of four (ruling record [`7254350842`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7254350842); [D7](#d7)). + - 2026-11-30, on decision card #38661, put for card ⑤a (#37111), by decision tap after an independent analysis; entered here by the revision of 2026-11-30. What the upgrade does with a stored form row the read serves at two package addresses of one App, and the reach of the answer: 「A 拦住升级·同类全覆盖」 (ruling record [`7265816895`](https://github.com/objectstack-ai/objectstack/issues/38661#issuecomment-7265816895) on #38661, recorded 2026-11-30T01:03Z; [D7](#d7)). The option as the card worded it: 「升级前检查点名该行,升级不切换、两个地址照常应答;同一定制位置被多份表单争用的情形也一律这样拦住,不必再开决策卡。」 Not taken: A for the two-address row alone; B, leave the row as stored, report it and do not count it; C, decide by what the row does today. The steps that carry it out are the owning seat's, not the maintainer's words: the cause class of the hold is one of them, and the same hold for a row more than one address serves, where those addresses would not all move it or all remove it, is another ([D7](#d7)). A third reads this ruling together with the ruling of 2026-11-29 (`7249158572`, item 1 above): 「两行都不动」 keeps the form rows behind the internal record form at that address, so a row kept there holds the upgrade, at that address too, where another address serves it and would move it or remove it, and the row a further address serves holds the upgrade where its plan would fold, move or remove a row kept there or the internal form itself, or write a folded row's withdrawal into either. That ruling's record says "The upgrade is not blocked"; each is an exception to it, the owning seat's reading and not the maintainer's words, for the approver to accept with the record or strike ([D7](#d7), D7-d). - **The ruling, as the card records it** (this record executes it; ⛔ none of it is re-opened here): 1. A new metadata type **`form`**, addressed by name, bound to one object (it carries `object` itself), body = today's form view schema. Its content is named forms that have a consumer: **public forms** (the main content, `sharing` included) and forms an action of `type: 'form'` opens. 2. **Public forms are not a separate feature**: they are `form` items. Their list, detail and edit come from the `form` type, not from a separate Studio page. @@ -37,12 +43,13 @@ 7. **Translations get a `forms` family**; the form tails under `objects.OBJECT._views` are read as a fallback until the major ([D8](#d8)). 8. **Shipped work is kept and re-pointed**: Setup's page reads `form`, the paused designer becomes the `form` editor, the Studio Developer page and the Form-tab switch retire ([D9](#d9)). 9. **Five cards, in order**; ② adds the type and narrows one write, ③ and ④ are additive, ⑤ is the major ([Execution plan](#execution-plan-after-acceptance)). -10. **Five points the first ruling is silent on were put to the maintainer and are ruled, all option A**: `defineForm` is the type's factory, the name stays `OBJECT.KEY`, a taken public address is refused, the reader of old withdrawals is exempt from the age-out, and the body is at the top level ([The five merge questions, as ruled](#the-five-merge-questions-as-ruled)). **Five points go past the ruling's words. Each is marked where it stands, outside every ruled block, for the approver to accept with the record or strike**: +10. **Five points the first ruling is silent on were put to the maintainer and are ruled, all option A**: `defineForm` is the type's factory, the name stays `OBJECT.KEY`, a taken public address is refused, the reader of old withdrawals is exempt from the age-out, and the body is at the top level ([The five merge questions, as ruled](#the-five-merge-questions-as-ruled)). **Six points go past the ruling's words. Each is marked where it stands, outside every ruled block, for the approver to accept with the record or strike**: - the `*.form.ts` file suffix follows the factory name, by the owning seat's routing on question 1 ([D2](#d2)); - a switched-off form that keeps its link still holds its address ([question 3](#q3), this record's reading of "holds"); - this record keeps the withdrawal reader through major 19, although the ruling would let it leave there ([question 4](#q4)); - the source conversion moves an item that declares `overrides` to `forms[]` whatever its body, which for a time puts a record form's override among the `form` items, past ruling item 3; `os validate` refuses the one whose base ships no form of that name ([D7](#d7), D7-b); - rule 11's replacement check is kept after major 19 on the withdrawal reader's lifetime, past the "this one reader" that question 4 exempts ([D7](#d7), "After the major"; [question 4](#q4)). Striking this returns the later ruling on the two kinds of row, named below, to the maintainer. + - the ruling of 2026-11-29 answers an internal record form served ahead of a package-less row that carries a public link; this record gives the same answer wherever the row behind declares a link, whatever it is bound to ([D7](#d7), D7-d). Striking it sends those shapes back to the maintainer before card ⑤b's `--apply`. Four more things are named here so they are read with them. The first three touch no ruled word; the fourth is a later ruling: - the fold of several stored rows closes a form that is open today, where a row no layer reads withdraws it ([D7](#d7), D7-d); @@ -278,25 +285,34 @@ Each pin asserts the refusal's status and `code` and that no record was written, - A stored `view` item with `viewKind: 'form'` becomes a `form` row at the same `(package, name)`; a stored container is split — its lists stay a `view` row, each form becomes a `form` row. - A **`.custom` override** of a form keeps its package, its name and its `overrides` declaration, `basedOn` unchanged: it is the same override in the type its base now has. This covers every switch Setup has written, and every override that differs from its base in any other way, a cleared link included: an override is never set aside as an internal record form on its own body (D7-b). - A **package-less overlay row** over a packaged form (ADR-0146 D11's unmigrated class) is moved to the destination D11 gives it: a declared `form` override in the base's pair, with its body as written — its switch when it has one, and no link when it has none (D7-b). +- A **form no door serves today is left in place by the upgrade**, whatever row holds it and whatever package that row is bound to; the upgrade never moves one into service. "No door serves" has one meaning here: the effective `form` read, the read both public doors take their candidates from, lists no form of the name at the address the plan is made at. At the environment's own address, which a name has only while no package ships its form and no stored row of it is bound to a package, that address is every slot the read seats the name's package-less row in, a package's slot included. A withdrawn form is not such a form: its switch is off, so both doors answer `404` for it today, but the read lists it, and it moves with its switch (D7-a, D7-d). Nor is an internal record form: no public door is meant to serve it, and it takes ruling 3's deletion. Left in place, the plan at that address moves and writes nothing, the form is not counted, and its served row and the rows behind it stay as stored there, unless the read also serves one of them at another address: that row takes what D7 gives it at that address, so it goes with a move made there, or folds into the form served there (D7-d). A plan of the form that holds at a slot, or for a row more than one address serves, still holds (ruling record `7265816895`). No other hold stands for it: where its move would hold at the pair door (D7-c) or at a destination the store seals, it is left in place instead. Ruled by the maintainer on 2026-11-30: 「本 PR 修,原地不动」 (ruling record [`7277149723`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7277149723) on #37111). +- A **form row bound to a read-only package that ships no form of its name**, and a pair's declared override of a base that ships none, is served today at the package it is bound to, unless no door serves it (the rule above). A row that is served today moves into that package's pair as the pair's own `form` item, declaring no `overrides`, with its body as written, so its public address answers byte-equal before the ceremony and after it (the precedent is ADR-0146's ceremony, which stores a member the base does not ship as the pair's own member). When that pair cannot be ensured, D7-c's hold applies. A package-less row of the same name behind it folds into it (D7-d), and the name has no environment address while such a row stands. An internal record form among these rows still takes ruling 3's deletion and needs no destination. Ruled by the maintainer on 2026-11-29: 「B 搬进定制包(推荐)」 (ruling record [`7250977204`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250977204) on #37111). Where a row bound to the base stands beside a pair's declared override of that base, D7-d decides, and the ruling's words do not reach it: the read serves the override at the base's address and the bound row nowhere, so the override's body is the one kept, as the own `form` item of the pair it stands in, the bound row folds into it, and the ensure door is not asked. An override a second pair of the same base holds is not the one served there, and keeps its own pair's address, where it is served today: D7-d keeps the body the read serves today, so this follows from D7-d and goes past no ruling's words. The ruling holds on its stated premise, that the row is served today at the package it is bound to: a row the read serves at another address is classed by the base it stands over there (D7-b) and takes the destination D7 gives a row bound to a read-only base, with D7-c's hold where that pair cannot be ensured, D7-e is unchanged, and the ruling stands for every row its premise holds for (ruled by the maintainer on 2026-11-29, option A of four: ruling record [`7254350842`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7254350842) on #37111). Where the read serves one row at two addresses, that destination cannot be given at both: a pair holds one row of a type and name, and a row declares one base (ADR-0146 D2). Ruled by the maintainer on 2026-11-30: 「A 拦住升级·同类全覆盖」 (ruling record [`7265816895`](https://github.com/objectstack-ai/objectstack/issues/38661#issuecomment-7265816895) on #38661). Such a row is moved at neither address and holds the upgrade, and both addresses answer as they do today. The same hold covers every slot of a pair that more than one plan claims, and no further decision is owed for that class. A plan is what D7 gives one form name at one address; a slot is the one row of a type and name a pair holds. No new hold cause, no new kind of plan, no new "not counted" kind and no protocol key come with the ruling. The ruling, against the rules it touches: + - **What is held.** A plan claims a slot where it keeps or moves a row in a pair under the name, as the pair's declared override or as the pair's own `form` item; a `form` row already stored there claims the slot as a row that would move there does. The pair's own row of the name is such a claimant: a row the pair holds as its own item, declaring no `overrides`, is read at the pair's own address, where the plan keeps it if it is a `form` row and moves it into the pair's own `form` row if it is an old-shape `view` row, and either way it claims the pair's slot; beside a row another address plans into that pair, both are held. Two cases are held. The first is the slot: where more than one plan claims one slot, every claimant is held, be it one row the read serves at two addresses of one App, whose two plans claim the App's one pair, or two rows, each read at its own address, that would both land in one pair. The second is the row more than one address serves, and it is decided per stored row, over every address that serves it, whatever App each address is of. A move or a removal takes the row from every address that serves it, so the row is moved only where every one of them would move it, each into its own destination, and removed only where every one of them would remove it (ruling 3). Where one would move or remove it and another keeps it, or one would move it and another remove it, every plan of the row holds the upgrade and the row is moved or removed at none of them. An address keeps the row where it leaves it in place (D7-d: an internal record form ahead of a row that declares a link), where the row already stands at its destination, and where the row holds there; a base whose App cannot be read has no pair, so the row holds there (D7-c), and that address keeps it. An address also keeps a form row that stands behind an internal record form it leaves in place, though it does not serve that row: this is the seat's reading of the ruling of 2026-11-29 (`7249158572`), stated under "Against D7-d". No plan need claim a slot in the second case. It is the owning seat's step under the ruling, not the maintainer's words: the ruling leaves both addresses of its row answering as they do today, and the seat reads the same for every address that serves a row. A held row is folded into no other row, be it held at the pair door (D7-c) or under this ruling: D7-c has the ceremony write nothing for it. Where a row that holds the upgrade where it is served stands behind the row another address keeps or moves, that address's plan lists it apart from the rows that fold into its served row, and the fold there is read without it: its withdrawal is not carried, and no form is named newly closed on its account. The report says the row is not folded because it holds the upgrade where it is served. Where every address that serves a row would move it and the moves land in different pairs, no slot is claimed twice, and D7 gives each its destination as before. + - **Against D7-b.** Each address still classes the row by the base it stands over there, and only a row this classing gives a destination in a pair claims a slot. The classing can differ between two addresses that serve one row, of one App or of two: one would move it, and the other gives it no destination or would remove it. The row is then held as above, and is moved or removed at neither. A row that every address that serves it would treat alike is not held for that: an internal record form takes ruling 3's removal where every one of them would remove it, and a row every one of them would move takes its destination at each, unless two of those moves claim one slot. + - **Against D7-c.** The hold is the one D7-c gives a row whose pair cannot be ensured: the ceremony writes nothing for the row, it stays as stored on the pre-upgrade release, which reads it as it does today, the precheck counts it, and the upgrade does not switch. The precheck names each held row once, and a row more than one address serves with every one of them; a row one of whose plans already holds, under D7-c or at a slot, is named by that hold and not a second time. Where the second case holds such a row, its plans that would not hold by themselves wait on that hold only where every other address would move the row: each then takes its cause and its action, an administrator's where the hold is one an administrator removes, and its refusal names the address the hold stands at and repeats that hold's own refusal. Where some other address would not move the row, those plans do not wait: they hold as every other row of the second case does, with an action that names no exit, and neither their refusal nor their action says what clearing that hold alone would bring, which was not measured. Every other hold under the ruling takes the class of a cause only the App's author can remove. Neither the class nor the waiting is the maintainer's words: each is the seat's step under the ruling, and the class is read from the rule, because no exit of the administrator's own that leaves every address's answer as it is was measured. The action of a hold that does not wait says only what was measured. D7-c's sentence for the class, that the deployment stays on its release until the App ships a version without the cause, is therefore not said of these holds as a class; the precedent for an action that names no exit is D7-c's own, for the pair an earlier version created (ruling record `7250982640`). One exit was measured: for one row read at two or more addresses of one App and at no address besides, where every one of its plans claims the App's one pair and no other row claims that slot, or where one address would move the row and another would not, no address keeps it behind an internal record form and no plan of it already holds, the action names the App, says only its author can remove the cause, and says the deployment stays on the release it is running until the App ships the form from one of those packages only; the row is then read at that address alone and takes what D7 gives it there. For every other hold that does not wait, no exit was measured, and the action promises none: it says that no action on this release clears the hold, that no exit from it was measured, and that the deployment stays on the release it is running while every address answers as it does today. At a slot, and for a row of one App, it also says the cause is in the App and its author's to remove, and names the App. For a row more than one address serves, the App is named, in either way, only where every address that serves the row, or keeps it behind an internal record form, is of one App that can be read, as a base of that App or as the App's pair. Otherwise the action says where the row is served, naming each App that can be read, each base whose App cannot be read and each package this environment writes, and says that no one App's author can remove the cause alone. + - **Against D7-d.** The fold comes first, and is unchanged for every row that does not hold: the rows of a form at one address reduce to the body the read serves there, and an address has one plan at most. A row that holds the upgrade where it is served is folded into no other row, as above. D7-d gives no order between the plans of two addresses, and ⛔ the ceremony never decides by the order it moves rows in or by which row reached the destination first. So no claimant is chosen for the slot, and nothing is written. D7-d's "left in place" is asked per address and is unchanged, with two exceptions under the ruling. The first: where another address that serves the same row, of the same App or of another, would move it or remove it, the row is held at each of those addresses and the precheck counts it, so that it is neither moved nor removed from under the address that leaves it. The second is the owning seat's reading of the ruling of 2026-11-29 (`7249158572`) together with this one, not the maintainer's words. 「两行都不动」 keeps the form rows behind the internal record form at that address as it keeps the form, so the address that leaves the form in place keeps each of them, though it does not serve them. Where another address serves such a row and would move it or remove it, the row holds the upgrade at every address that serves it or keeps it, the address that leaves the form in place among them: it is moved or removed at none of them, both rows stay as stored, the precheck names the row once, and the action names no exit. The seat reads that keeping row-wide: the internal record form an address leaves in place under the ruling of 2026-11-29, and each form row behind it there, stay as stored at every address under that name, so a plan at another address that would fold one of them into the row it serves, remove it with that row, or write a folded row's withdrawal into it holds the upgrade instead (the precheck names the row that plan serves; its action names no exit, and says the cause is one App's author's to remove only where that address and each address that keeps the row are of one App that can be read), a kept row behind the served row of any plan that holds is listed apart there and not among the rows that fold into it, and the address that keeps the row stays left in place unless a row it keeps would also be moved or removed at an address that serves it. That ruling's record says "The upgrade is not blocked", written for one address; this is an exception to it, for the approver to accept with the record or strike. + - **Against D7-e.** D7-e is unchanged: the hold's action offers no deletion and no reset, and names no act of the administrator's that changes what an address answers. - A **row bound to a read-only base** — a customization saved under the base's own id before that door closed, the class ADR-0146 D11's ceremony carries beside the package-less one (`packages/metadata-protocol/src/protocol-packageless-overlay-migration.ts`) — has the same destination: a declared `form` override in the base's pair, with its body as written (D7-b). - **(D7-d) Several stored rows of one form fold into one: the body kept is the one served today, and the fold only narrows.** More than one stored row of a form can head for one destination. Over a read-only base there are three, all bound for the pair's declared override: the pair's own override, a row bound to the base, and a package-less row. For a writable package there are two, bound for the package's own row: that row and a package-less row (the ensure door refuses a writable base with "customize it directly"). - **The body kept is the one the served-row order serves today** (`servedOverlayRowCandidates`: the pair's override, then the row bound to the package, then the package-less row), whichever binding and whichever type it is stored in. It lands on the destination as written: a body with no link stays without one. ⛔ The ceremony never decides this by the order it moves rows in, and never by which row reached the destination first. - **The served row is found among every stored row at the address, whether it carries a form or not, in either type.** Where the row the order picks carries no form at the name (D7-b's row with nothing to move), nothing is served for the name today ([D5](#d5)), and the ceremony moves **no** row of that name. A form row behind it, bound to the base or package-less, stays where it is, and every stored row of the name stays as stored with the no-form row. The no-form row is one of the two kinds the ruling recorded beside [question 4](#q4) names; by this record's reading of that answer, a form row left behind a no-form row is not held either. None of them holds the upgrade; the report names each as left in place. Moved alone, the form row would become the pair's override, first in the served-row order and ahead of the row that keeps the address closed. The same holds where the row picked is a declared `view` override that carries no form, if card ② finds a door for one: no form row behind it is moved into the pair, where a stored `form` row would win over it ([D5](#d5)). - **A writable package's own list ahead of a package-less form row.** The same rule decides it, and the record says it by name because the list is not D7-b's row. The served row at the address is the package's own `view` row, which carries a list; the package-less row behind it carries a form no layer reads ([D5](#d5), "served rows only"). The ceremony moves **no** row of the name: moved to the package's own `form` row, the package-less body would be a `form` item of that package and would be served. The list is the package's own item: it is not an old-shape form row, it holds nothing, and neither the report nor the precheck names an action for it. The package-less form row stays as stored: by the ruling recorded beside [question 4](#q4) it gets no disposition of its own and does not hold the upgrade. The report names it as left in place, with the list that is served ahead of it, and offers no deletion for it (D7-e) and no save that would serve it. No layer reads it before the major or after it. **This is the rule at the writable package's address, and only there.** A package-less row that is also the served row at a read-only base's address, standing over that base's form, keeps at that address what [D7](#d7) gives it: its destination in the base's pair, or D7-c's hold where the pair cannot be ensured. - - **Every other row of the form is folded into it and carries over one thing only**: if it explicitly withdraws the form, the destination keeps its link and takes that switch off. Nothing else of a folded row is kept — not its link, not a switch that is on — so a body the read does not serve today is never served by the ceremony. The report names every row of the form, the one whose body was kept, and which one closes the form. + - **An internal record form served ahead of a row that declares a link.** The served row is an internal record form (the three-part set above), and another stored row of the same name at the same address declares a `sharing.publicLink`, switched on or off: a writable package's own row ahead of a package-less row, say. The ceremony moves **no** row of the name and deletes none, and the internal form is not removed in this shape: removed, it would leave the linked row behind it, which no layer reads today, as the row the order serves next. Both rows stay as stored, and the report names both as left in place, saying the internal form was not removed because a row with a public link stands behind it. The precheck does not hold the upgrade for them: this is a "not counted" kind beside the two the ruling recorded beside [question 4](#q4) names and the one this record adds. The maintainer ruled the package-less case on 2026-11-29: an internal record form served ahead of a same-named package-less row that carries a public link gets 「两行都不动,写进报告」 (ruling record [`7249158572`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7249158572) on #37111); the ruling record's reading carries the same answer to the twin, where that link's switch is off. By this record's reading of that answer, the same answer holds wherever the row behind the internal served row declares a link, whatever it is bound to: an internal pair override ahead of a linked row bound to the base, say, where removing the internal row would likewise serve a linked row the read does not serve today. Only that reading is still open to correction. Both doors answer `404` at the address before the ceremony and after it, and on major 19. One exception to "does not hold the upgrade" stands beside this bullet, and it is the owning seat's step, not the maintainer's words: where another address serves a form row that stands behind the internal form here, and would move it or remove it, the row holds the upgrade at every address that serves it or keeps it, this one among them, so that both rows stay as stored (the seat's reading of this ruling with the ruling of 2026-11-30, `7265816895`; it and the exception for the internal form itself are stated under "Against D7-d" in [D7](#d7)), and a further exception, the same seat's step and not the maintainer's words, is stated there too: where a plan at a further address would fold, move or remove a row kept here, the internal form or a form row behind it, or write a folded row's withdrawal into it, the row that address serves holds the upgrade. + - **Every other row of the form is folded into it and carries over one thing only**: if it explicitly withdraws the form, the destination keeps its link and takes that switch off. Nothing else of a folded row is kept — not its link, not a switch that is on — so a body the read does not serve today is never served by the ceremony. The report names every row of the form, the one whose body was kept, and which one closes the form. A row that holds the upgrade where it is served is not one of them: it is folded into no other row, it carries nothing over, and the report names it apart ([D7](#d7), under the ruling of 2026-11-30, `7265816895`). - **Why the served order decides: a row bound to the base beside a package-less row.** The read serves the bound row today, in the effective list and in the base's per-package layer alike; the package-less row behind it is read by neither. Where the bound row has no link over a linked base, it closes the address by replacing the base's body (rule 11 of [D6](#d6)), and the package-less row may hold an open body. Both rows have the pair as destination, and the pair's override is first in the served-row order. Kept by the served order, the bound row's body is the pair's override and the address stays closed after `--apply`; the package-less body is folded and its open switch is not carried. - **A folded row's withdrawal that a layer reads today must keep closing.** The base's per-package layer reads the first of the bound row and the package-less row, under an open override of the pair. A withdrawal there closes the form today, and the fold carries it. - **A folded row's withdrawal that no layer reads today closes the form newly.** A package-less row behind a row bound to the base, or behind a writable package's own row, is read by no layer, so its withdrawal closes nothing today. The fold carries it all the same: the form is open before the ceremony and answers `404` after it. That is the direction a layer may take. The report names the form as newly closed, and the administrator switches it on again in Setup. - Every statement about today in this bullet is read from the served-row order and the per-package layer's contract (`servedOverlayRowCandidates`, `getMetaItemsPerPackage`) and was not run for this record; card ⑤'s fold pin runs each "before" half before the ceremony relies on it. - **(D7-c) Where the pair cannot be ensured, the row is not moved, and it holds the upgrade to major 19 until it is.** The ceremony writes nothing for it. It stays a `view` row on the pre-upgrade release, which reads it as it does today — that release has no [D6](#d6) (`7142585849`, ruling 2, and the seat's all-or-nothing decision below) — so a withdrawal it holds keeps closing and a base form it replaces stays replaced. ⛔ It is not moved to a package-less `form` row: `form` takes no environment-overlay tier ([D2](#d2)), and the read path honours an unmigrated package-less row only for a type that has one (ADR-0146 D11). The ceremony's report and the upgrade precheck both name the row (type, name, base) and repeat the ensure door's own refusal (`packages/metadata-protocol/src/protocol-customization-package.ts#customizationPairEnsureRefusal`), with the administrator's action for its cause: - - **A cause the administrator can remove in the deployment**: a package installed under the pair's id is not the pair; another package owns the pair's namespace; the App that carries the base is not installed; a per-package pair an earlier version created holds the namespace (ADR-0146 D11's own ceremony re-identifies it, so that ceremony runs first). The door's text names the fix for each. The administrator makes it on the pre-upgrade release and runs the upgrade command again (`7142585849`, ruling 2); the row moves to the pair with its body as written. - - **A cause only the App's author can remove**: the App declares no namespace, or one too long or not valid for a pair namespace; the App's version is not SemVer; the base declares several Apps and its namespace picks none. An administrator who authors the App fixes it as above. One who does not cannot: the deployment stays on major 18 until the App ships a version without the cause, or is uninstalled, which takes the base's form and its address with it. "Stays on major 18" stands: it is the state of a deployment whose upgrade does not switch (`7142585849`, ruling 2). The row keeps closing meanwhile, as the `view` row it is. The precheck names the App and the cause, says the fix is its author's, and offers no other action. + - **A cause the administrator can remove in the deployment**: a package installed under the pair's id is not the pair; another package owns the pair's namespace; the App that carries the base is not installed. The door's text names the fix for each. The administrator makes it on the pre-upgrade release and runs the upgrade command again (`7142585849`, ruling 2); the row moves to the pair with its body as written. A per-package pair an earlier version created that holds the namespace is classed here too, and is not removable on this release: the row holds the upgrade until that pair is re-identified as the App's pair (ADR-0146 D3, merge question 12), and no command on this release does that; the precheck's action says so and offers no other. Ruled by the maintainer on 2026-11-29: 「B 只改文字,不开卡」 (ruling record [`7250982640`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250982640) on #37111): the text changes, the class does not, and no card is filed. + - **A cause only the App's author can remove**: the App declares no namespace, or one too long or not valid for a pair namespace; the App's version is not SemVer; the base declares several Apps and its namespace picks none. An administrator who authors the App fixes it as above. One who does not cannot: the deployment stays on major 18 until the App ships a version without the cause, or is uninstalled, which takes the base's form and its address with it. "Stays on major 18" stands: it is the state of a deployment whose upgrade does not switch (`7142585849`, ruling 2). The row keeps closing meanwhile, as the `view` row it is. The precheck names the App and the cause, says the fix is its author's, and offers no other action. A hold under the ruling of 2026-11-30 (`7265816895`, [D7](#d7)) that waits on another hold of its row takes that hold's class and its action. Every other one is of this class, and its action is the one stated there: it names the App where the cause is in one App that can be read, and otherwise says where the row is served, naming each App that can be read, each base whose App cannot be read and each package this environment writes, and that no one App's author can remove the cause alone. It names the exit of this class, a version of the App without the cause, only where that was measured, for one row read at two or more addresses of one App; elsewhere it says that no action on this release clears the hold. - **A base that has no pair in this version**: a kernel package, until the kernel whitelist of ADR-0146 D3 admits it. Measured at `689e5695b98`, this case is empty: no package that ships metadata to a deployment authors a form in any of the three shapes (`git grep -lE "formViews|viewKind: 'form'|viewKind === 'form'" -- packages/platform-objects packages/plugins packages/services packages/triggers packages/drivers packages/connectors packages/apps` finds one `CHANGELOG.md` and no source), so no package-less row overlays a kernel package's form. Card ⑤ takes the reading again before it is cut. If a kernel package ships a named form by then, this record has no way out for the row without a new mechanism, and the case goes to the maintainer as a decision before major 19 opens. - **A body the projection cannot read** (rule 7 of [D6](#d6)) is in the same class: the ceremony cannot move it, it holds the upgrade, and on the pre-upgrade release both doors answer for it as they do today: rule 7 runs on `main` and on the major, not there. It leaves the class by an old-shape save that repairs the body, made on the pre-upgrade release; the upgrade command, run again, then moves it (`7142585849`, ruling 2). - **(D7-e)** ⛔ In none of these cases does the precheck or the ceremony's report offer deletion or a reset for a row that declares a `sharing.publicLink`, or for a row that stands over a base form that declares one (D7-b), and card ⑤ does not let such a row through. Deleting a switched-off form's row switches the form back on; deleting a link-less row over a linked base serves the base's form again. - History rows stay verbatim under the type they were written as (ADR-0087: the version layer is not converted); the new row's history starts with the move. -- Internal record forms in stored rows are removed by the upgrade, in the run that switches (`7142585849`, ruling 3): an item-shaped row is deleted, a container that also holds lists is re-saved without that member, its lists byte-equal. The report names each removed form, writes out its body, and says per object that New and Edit now follow the object's field groups and whether it has any. History rows stay verbatim. A deployment that does not switch keeps every one. The set is the one defined above, all three parts: no `sharing.publicLink`, no action target, and not standing over a base form that declares a link. Ruling 3 widens nothing: a row that declares a `sharing.publicLink`, or stands over a linked base, is never removed, and D7-e and the three-part test are unchanged. Removing a row of that set changes no door's answer: it steers nothing, it holds no switch because it has no link, and it replaces no linked body because its base has none. ⛔ That holds for this set only. A row with no link of its own that stands over a linked base is not in it (D7-b), and the report never lists one for removal. The precheck does not count the internal ones as holding the upgrade; the read-only run lists them as "will be removed" (`7142585849`, ruling 3). -- The major's upgrade command runs the ceremony and then the precheck (`7142585849`, ruling 2). It switches when the precheck counts no row. It refuses to switch when the precheck counts one, naming each row and its action, and the deployment stays on the release it is running. What refuses is a row that holds the upgrade (D7-c: its pair cannot be ensured, or its body cannot be read). A row the ceremony can move does not refuse, and neither does an internal record form: the upgrade moves the one and removes the other (ruling 3). Not counted are the two kinds of row the ruling recorded beside [question 4](#q4) names — a row that carries no form over a linked base, and a package-less form row no layer reads behind a writable package's own list — and, by this record's reading of that answer, a form row left behind a no-form row. They stay as stored and the upgrade proceeds with them. "Not counted" is asked per package address, as [D5](#d5) asks "served": a package-less row passed over at a writable package's address still holds the upgrade at a read-only base's address whose pair cannot be ensured. +- **Draft rows are neither moved nor deleted**, and no door's answer changes: no read serves a draft. The report lists each draft `view` row that carries form content in an old shape, and says that after the upgrade such a draft cannot be published, so an administrator who wants one kept publishes it first; it also names a draft left behind by a published row that moves. A `form` draft is in the new shape and is not listed. Ruled by the maintainer on 2026-11-29: 「A 留下并提醒(推荐)」 (ruling record [`7250982640`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7250982640) on #37111). +- Internal record forms in stored rows are removed by the upgrade, in the run that switches (`7142585849`, ruling 3): an item-shaped row is deleted, a container that also holds lists is re-saved without that member, its lists byte-equal. The report names each removed form, writes out its body, and says per object that New and Edit now follow the object's field groups and whether it has any. History rows stay verbatim. A deployment that does not switch keeps every one. The set is the one defined above, all three parts: no `sharing.publicLink`, no action target, and not standing over a base form that declares a link. Ruling 3 widens nothing: a row that declares a `sharing.publicLink`, or stands over a linked base, is never removed, and D7-e and the three-part test are unchanged. Removing a row of that set changes no door's answer: it steers nothing, it holds no switch because it has no link, and it replaces no linked body because its base has none. ⛔ That holds for this set only. A row with no link of its own that stands over a linked base is not in it (D7-b), and the report never lists one for removal. The precheck does not count the internal ones as holding the upgrade; the read-only run lists them as "will be removed" (`7142585849`, ruling 3). A deletion is per row, and so is a move: each asks every address that serves the row, whatever App the address is of. A package-less row is read at every address of its name, so it is in the set only when it is internal at each of them, and a row over a linked base at any one of them moves at each instead, into each address's own destination; where two of those moves claim one slot of a pair, it holds the upgrade and is moved at neither (the ruling of 2026-11-30, `7265816895`). A row is moved only where every address that serves it would move it, and removed only where every address that serves it would remove it. Where one would move or remove it and another keeps it, as D7-d does where it leaves an internal record form in place ahead of a row that declares a link, or one would move it and another remove it, the row is moved or removed at none of them and holds the upgrade at each; the precheck names it once, with every address, or by the hold one of its plans already has. That is the owning seat's step under the same ruling, not the maintainer's words: a move or a removal takes the row from every address that serves it, and the ruling leaves both addresses of its row answering as they do today. A list row behind a removed form is not part of it, and stays byte-equal. +- The major's upgrade command runs the ceremony and then the precheck (`7142585849`, ruling 2). It switches when the precheck counts no row. It refuses to switch when the precheck counts one, naming each row and its action, and the deployment stays on the release it is running. What refuses is a row that holds the upgrade (D7-c: its pair cannot be ensured, or its body cannot be read; or, by the ruling of 2026-11-30, `7265816895`, it claims a slot of a pair and another plan claims that slot too, or more than one address serves it, one of them would move or remove it, and another would not do the same). A row the ceremony can move does not refuse, and neither does an internal record form: the upgrade moves the one and removes the other (ruling 3). Not counted are the two kinds of row the ruling recorded beside [question 4](#q4) names — a row that carries no form over a linked base, and a package-less form row no layer reads behind a writable package's own list — and, by this record's reading of that answer, a form row left behind a no-form row, and, by the ruling of 2026-11-29 (D7-d, `7249158572`), an internal record form served ahead of a package-less row that declares a link, with that row, and, by this record's reading of that ruling, an internal record form served ahead of any other row that declares a link, with that row. They stay as stored and the upgrade proceeds with them, with the three exceptions the ruling of 2026-11-30 brings ("Against D7-d" under [D7](#d7)), each the owning seat's step: an internal record form left in place at one address holds the upgrade where another address that serves it would move it or remove it; a form row kept behind such a form holds the upgrade, at that address too, where another address serves that row and would move it or remove it; and the row a further address serves holds the upgrade, and is the row the precheck names, where its plan would fold, move or remove such a form or a row kept behind it, or write a folded row's withdrawal into either. "Not counted" is asked per package address, as [D5](#d5) asks "served": a package-less row passed over at a writable package's address still holds the upgrade at a read-only base's address whose pair cannot be ensured. - **A seat decision, not the maintainer's words (`7142585849`; in his veto window): the upgrade's move is all-or-nothing with the switch.** A deployment that does not switch holds every stored row as it was. The pre-upgrade release has no `form` type and reads `view` rows only, so a switch-off moved to a `form` row there is read by nothing and the base's form answers. The decision rests on [ruled question 4](#q4). **What keeps a public address closed today, and the rule that carries it.** The break was tried once more for this record across the four stages, for every way a stored row can be the thing that keeps an address closed. Each cell names the rule that holds; "D6-n" is rule n of [D6](#d6). @@ -319,14 +335,16 @@ One path the table does not close, by design: an administrator who resets an ove - **the switched-off form in a record-form slot**: a public form in the container's default `form` slot, link kept and `enabled: false`, whose name is open in another layer. After the source conversion, and after the ceremony on the stored twin (Setup's switch-off override of that form), it is a `form` item with its switch, the internal-forms report does not list it, and both doors still answer `404` (ablate: the `publicLink` test of the internal set — judge "public" by `sharing.enabled === true` — and the form is deleted or left behind with its withdrawal); - **its twin, the link-less row over an open base**: a `.custom` override in the default `form` slot whose body has no `publicLink`, over a base whose default-slot form is open; and the same body as a package-less row. After the source conversion of the pair's own source, and after the ceremony, it is a `form` override with no link, the internal-forms report does not list it, the precheck names no removal for it, and both doors still answer `404` at the base's address (ablate: the base half of the internal test — class the row by its own body alone — and the pin turns red: the report lists the row for removal, and removing it as the report says serves the base's form); - **the ceremony keeps a withdrawal closed**: a form withdrawn before the ceremony — by a `.custom` switch-only override, and by a member of a stored container — answers `404` after it (ablate: the carry of the `sharing` block in the move); -- **the fold keeps the served body and only narrows** (D7-d), five fixtures: +- **the fold keeps the served body and only narrows** (D7-d), six fixtures: - an open override in the pair beside a package-less row that withdraws the form answers `404` before the ceremony and after it, and the destination row keeps its link with the switch off (ablate: the fold's carry of the folded row's switch); - **the row bound to a read-only base**: a row bound to the base whose body has no `publicLink`, over the base's open form, beside a package-less row whose body is open. Both doors answer `404` at the base's address before the ceremony and after it, and the pair's override has no link (ablate: the choice of the kept body — take the package-less row first, as the row that reaches the pair first — and the address answers); - **the writable-base twin**: a writable package's own open row beside a package-less row that withdraws the form. The form is open before the ceremony and answers `404` after it, and the report names it as newly closed (ablate: the report's line for a newly closed form); - **the writable package's list ahead of a form row**: a writable package's own `view` row that carries a list, beside a package-less `view` row of the same name that carries an open form. Both doors answer `404` at the form's address before `--apply` and after it, the package holds no `form` row of the name, the list row is byte-equal, the report names the package-less row as left in place, and the precheck does not hold the upgrade for it (ablate: fold the package-less form row into the package's own `form` row, as a row of that form, and the address answers); - **the no-form row ahead of a form row**: a row bound to the base that carries no form at the name, over the base's open form, beside a package-less row that holds an open form of that name. Both doors answer `404` at the base's address before `--apply` and after it, the pair holds no row of the name, the report names both rows as left in place, and the precheck does not hold the upgrade for them (ablate: leave the no-form row out of the fold — find the served row among form rows only — and the address answers); + - **the internal form ahead of a linked row** (the ruling of 2026-11-29, `7249158572`, D7-d): a writable package's own internal record form (a record-form slot, no link, no action target), beside a package-less row of the same name with a public link, and its twin with that link switched off. Both doors answer `404` at the address before `--apply` and after it, and on major 19; neither row is moved or deleted, the report names both as left in place, and the precheck does not hold the upgrade for them (ablate: the case's predicate, so the internal row is removed and the linked row behind it is served); - each "before" half proves one of this record's readings of today's layers. If one is not as stated here, the card stops and reports; -- **the precheck refuses**: a deployment that holds a stored old-shape form row of each stopping class (pair not ensurable, body not readable) does not reach major 19, and the refusal names the row and its action (`7142585849`, rulings 2 and 3: a movable row is moved and an internal one is removed, so neither is a stopping class); for a row that declares a link or stands over a linked base, the action it names is never a deletion or a reset (ablate: the precheck's read of each class in turn). A list in a package at a form's name is not named by the precheck (ablate: [D5](#d5)'s bound); +- **the row bound to a package that ships no form of its name** (ruling `7250977204`): a row bound to a read-only package that ships no form of the name, with an open link, and a pair's declared override of a base that ships none. Each, alone at its name, moves into the pair as the pair's own `form` item with no `overrides`, and both doors answer byte-equal at its address before `--apply` and after it; together at one name, the override's body is the one kept, the bound row folds into it, and the bound row's body is served neither before nor after (ablate, for the half alone at its name: the destination, as the declared override the other moves take; for the half together at one name: the read of the override at the base's address, so that each row is planned at its own address). The byte-equal claim holds within the ruling's premise; a row the read serves at one other address answers there byte-equal before `--apply` and after it, as the declared override in that base's pair (ruling record [`7254350842`](https://github.com/objectstack-ai/objectstack/issues/37111#issuecomment-7254350842); ablate: the read of the row at the address that serves it, so that it is planned at the package it is bound to). A row the read serves at two addresses is outside this pin's move: it has no destination and holds the upgrade, and so does every row that claims a slot of a pair more than one plan claims, the pair's own row of the name among them: read at the pair's own address, as an old-shape `view` row and as a stored `form` row, it holds beside a row another address plans into that pair, and alone it is planned there and nothing holds (D7; ruling record [`7265816895`](https://github.com/objectstack-ai/objectstack/issues/38661#issuecomment-7265816895) on #38661). What holds instead, for each held row: the precheck counts the row and names it once, and a row read at two addresses with both addresses; `--apply` writes nothing while it is stored, every stored row is byte-equal, and both doors answer the same at each address that serves it before the refused run and after it (ablate: the hold's predicate, so that each claimant is planned as a move again). The same is pinned for a row more than one address serves where those addresses would not all move it or all remove it, whatever App each is of: moved at one and left in place at the other, an internal record form ahead of a row that declares a link, at two packages of one App and at packages of two Apps; removed at one and left in place at the other, at two packages of one App and at an App's base beside a package this environment writes; moved at one and held at the other at the pair door, for a cause an administrator removes and for a base whose App cannot be read, where the plan that would move waits on that hold and takes its cause and its action. The precheck counts the row and names it once, nothing is moved or removed, and the action names the App or says where the row is served, and names an exit only where one was measured: a slot two rows claim is told of none (ablate: the predicate that asks every address that serves the row, so that each address is planned by itself again). A held row that stands behind the row a third address moves is listed apart there, and that fold is read without it: its withdrawal is not carried. The control: a row every address would move, each into its own pair, moves at each. Where the package that ships the name ships only a list of it, the plan stops short of that package and keeps the row at the package it is bound to, with no outcome differing; +- **the precheck refuses**: a deployment that holds a stored old-shape form row of each stopping class (pair not ensurable, body not readable), or one held under the ruling of 2026-11-30 (`7265816895`: a slot of a pair more than one plan claims, or a row more than one address serves where those addresses would not all move it or all remove it), or one held under the owning seat's reading of the ruling of 2026-11-29 (`7249158572`) with that one, an exception to that ruling record's "The upgrade is not blocked" (the row an address serves where its plan would fold, move or remove a row another address keeps as stored under that ruling, or write a folded row's withdrawal into it), does not reach major 19, and the refusal names the row and its action (`7142585849`, rulings 2 and 3: a movable row is moved and an internal one is removed, so neither is a stopping class); for a row that declares a link or stands over a linked base, the action it names is never a deletion or a reset (ablate: the precheck's read of each class in turn). A list in a package at a form's name is not named by the precheck (ablate: [D5](#d5)'s bound); - **internal record forms are removed, and only those** (`7142585849`, ruling 3): after the run that switches, a stored internal record form is gone and the report names it with its body; a row with a link, or over a linked base, in the same slot is not removed, and both doors answer at its address as before (ablate: the link test of the internal set, then its base half, and the row is removed); - **the precheck does not hold the two ruled kinds, and their addresses stay closed**: a deployment whose only such rows are a row that carries no form over a linked base, in a binding [D5](#d5) bounds, and a package-less form row behind a writable package's list reaches major 19 with every one of those rows byte-equal, and both doors answer `404` at each address before the upgrade and on the major-19 build (ablate: the kept replacement check's read of a row that carries no form, and the base's address answers on the major-19 build); - **the kept reader still closes after the tombstone**: on a major-19 build, a stored old-shape body that withdraws a form still closes it, a stored old-shape row with no link over a package's open form still keeps that address closed, and so does a stored row that carries no form over it, in a binding [D5](#d5) bounds (ablate: the exempt reader, then its replacement half); @@ -526,8 +544,8 @@ Ruling-ref: [`7131569242`](https://github.com/objectstack-ai/objectstack/issues/ - **The reading, as the first record carries it and the second confirms it.** These rows need no disposition of their own. The ceremony does not move them, the upgrade precheck does not hold major 19 for them, and they stay as stored. - **No form that is closed today opens by it.** The first kind keeps its base's address closed through rule 11's replacement check, which this record keeps after the major ([D7](#d7), "After the major"). The second kind is read by no layer, before the major or after it ([D5](#d5), "served rows only"). -- **What follows in this record, and is this record's own.** [D5](#d5)'s bounded reading and card ②'s refusal last as long as the replacement check, past major 19. The ruling record names two kinds of row; by this record's reading of that answer, a form row left behind a no-form row over a read-only base stays as stored with it and is not held either ([D7](#d7), D7-d). And the answer rests on the replacement check being kept, which is the fifth point of TL;DR 10: striking that point puts this question back. Only this bullet is still open to correction. -- **What a later release owes.** The ruling narrows which rows major 19's precheck counts, and two of the uncounted kinds are old-shape form rows. So the release that one day removes the withdrawal reader, or the replacement check, owes its own answer for these rows: major 19's precheck no longer refuses a deployment that holds them. Nothing opens meanwhile: this record keeps the reader through major 19, and the uncounted form rows are read by no layer or stand behind a row the check keeps closed. +- **What follows in this record, and is this record's own.** [D5](#d5)'s bounded reading and card ②'s refusal last as long as the replacement check, past major 19. The ruling record names two kinds of row; by this record's reading of that answer, a form row left behind a no-form row over a read-only base stays as stored with it and is not held either ([D7](#d7), D7-d). A later ruling (2026-11-29, `7249158572`) adds an uncounted kind beside the two ruled ones and this record's own: an internal record form served ahead of a package-less row that declares a link, with that row; where the linked row behind is any other row, the same answer is this record's reading of that ruling ([D7](#d7), D7-d). And the answer rests on the replacement check being kept, which is the fifth point of TL;DR 10: striking that point puts this question back. Only this bullet is still open to correction. +- **What a later release owes.** The ruling narrows which rows major 19's precheck counts, and two of the uncounted kinds are old-shape form rows. So the release that one day removes the withdrawal reader, or the replacement check, owes its own answer for these rows: major 19's precheck no longer refuses a deployment that holds them. Nothing opens meanwhile: this record keeps the reader through major 19, and the uncounted form rows are read by no layer, stand behind a row the check keeps closed, or (the kind the ruling of 2026-11-29 adds for a package-less row, and this record's reading of it for any other row that declares a link, [D7](#d7), D7-d) stand behind a served internal record form that is not removed. ### 5. The document shape: body at the top level, or under `config` {#q5} @@ -561,7 +579,7 @@ Ruling-ref: [`7131569242`](https://github.com/objectstack-ai/objectstack/issues/ - **A stored row that keeps a public address closed is never set aside as an internal record form**, whether it closes by a switch or by replacing its base's form. The migration moves it, or by the later ruling leaves it as stored, and no report or precheck offers its removal ([D6](#d6) rule 11, [D7](#d7)). Where a form row stands behind a no-form row, removing the row in front before the major serves the row behind it and not the base's form; the report names both. The price is one more read rule for the dual-read period, and a `.custom` source's overrides being moved by the conversion without a look at the base. `os validate` then refuses the one whose base ships no form of that name, so a record form's override does not stay among the `form` items (this record's reading of ruling item 3, [D7](#d7)). - **The ceremony can switch off a public form that is open today.** Where a stored row no layer reads today withdraws a form — a package-less row behind a writable package's own row, or behind a row bound to the base — the fold carries the withdrawal, and the form answers `404` after `--apply`. The report names it as newly closed, and the administrator switches it on again in Setup ([D7](#d7), D7-d). Where several stored rows of one form exist, the one whose body the read serves today is the one kept. - **From card ②, and for as long as rule 11's replacement check is kept, a package-less list is not saved at a name a read-only package authors as a form**, as an item or through a container's expansion. It is a refusal card ② adds and an exception to [D3](#d3) that outlasts major 19. **Some of these saves are admitted today**: where several packages ship the name, where the base has no pair, a re-save of a row its pair already holds, and a container that overlays the package's own container. An administrator who holds such a list can no longer edit it in place once the package authors the form. The door that remains: another key, or the list saved into an app of the environment's own. Card ② is `narrowed` for it. -- **Two kinds of stored row get no disposition of their own** (ruled; [question 4](#q4), the last paragraph after it). A package-less form that no layer reads today, behind a writable package's own list of the same name, stays unread: it is not served from card ②'s release and the ceremony does not move it. A row that carries no form over a linked base — a package-less list that held the name before the package shipped a form under it, say — keeps that form unserved in that deployment for as long as rule 11's replacement check is kept. Both stay as stored, and major 19 is not held for them. Serving the base's form in such a deployment is the administrator's own act on the row; no report prescribes it ([D5](#d5), [D7](#d7)). +- **Two kinds of stored row get no disposition of their own** (ruled; [question 4](#q4), the last paragraph after it; beside them and this record's own kind, an internal record form served ahead of a package-less row that declares a link, with that row, by the ruling of 2026-11-29, and ahead of any other row that declares one, by this record's reading of that ruling; [D7](#d7), D7-d). A package-less form that no layer reads today, behind a writable package's own list of the same name, stays unread: it is not served from card ②'s release and the ceremony does not move it. A row that carries no form over a linked base — a package-less list that held the name before the package shipped a form under it, say — keeps that form unserved in that deployment for as long as rule 11's replacement check is kept. Both stay as stored, and major 19 is not held for them. Serving the base's form in such a deployment is the administrator's own act on the row; no report prescribes it ([D5](#d5), [D7](#d7)). - **One arrangement served today is refused once it is in the new type**: a retired form that keeps its link beside its successor on the same address. The author clears the retired form's link ([question 3](#q3), this record's reading of "holds"). - **`defineForm` changes meaning** in card ② ([ruled question 1](#q1)): a declared, compiler-carried export break, on the premise that its outside use is platform-internal. The 17 Studio form modules change file suffix in the same card ([D2](#d2), the seat's routing). - **First-party work**: about 100 non-test source files and about 160 test files name the old shapes; they move in ②, ③ and ④ and the remainder falls to ⑤. diff --git a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md index 4af7eecfbe5..9dd5e0fe74e 100644 --- a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md +++ b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md @@ -18,6 +18,10 @@ - **Inputs**: every code and docs text quoted below was read on `objectstack-ai/objectstack` `main` at `254e396a29`, the commit this record's branch starts from. Positions are in [Readings](#readings-taken-at-254e396a29). PR #36823 and PR #36850 are merged and are in that tree; PR #37075 is open and edits §6 of `content/docs/protocol/knowledge.mdx`, so the §6 quotations may move when it lands. - **Amended** (2026-11-25, [#37097](https://github.com/objectstack-ai/objectstack/issues/37097)): a dated note under the table of [K8](#k8--the-contract-additions-decided-item-by-item) records that the document hash of item 2 covers `organizationId` when the document has one (item 9), with no version bump. The status line above is left as it is. - **Amended** (2026-11-25, [#37324](https://github.com/objectstack-ai/objectstack/issues/37324)): a second dated note under the table of [K8](#k8--the-contract-additions-decided-item-by-item) gives item 17 its final shape, `AdapterSearchOptions.scope?`: the typed scope the service builds from `scope: [{ object, ids }]`, on the maintainer's ruling of that day, 「也能指定上级对象(制度)」 (record `7168192820` on #37308). The status line above is left as it is. +- **Amended** (2026-11-28, [#38368](https://github.com/objectstack-ai/objectstack/issues/38368)): a third dated note under the table of [K8](#k8--the-contract-additions-decided-item-by-item), read with item 12, records that a knowledge service the runtime mounts is enabled by configuration: a boot enables it when it finds an embedder and the deployment's store, and until then its sources are held and not served. It is written on the maintainer's words of that day, 「平台没有知识服务时,知识源不应该启用啊。」 and 「私有部署判断的是相关参数有没有配置」, as the filing gate of #38368 records them, and on four points he ruled on 2026-11-29 by choosing the decision card's option 「全按推荐(1A 2A 3A 4A)」 (record [`7248214179`](https://github.com/objectstack-ai/objectstack/issues/38368#issuecomment-7248214179) on #38368). It adds no contract member and no settings key. A cross-reference stands under [K4](#k4--knowledge_source-is-admitted-as-a-metadata-type). The status line above is left as it is. +- **Amended** (2026-11-29, [#38502](https://github.com/objectstack-ai/objectstack/issues/38502)): a fourth dated note, under "What follows from the two lists" in [K1](#k1--the-boundary), amends that list's sentence "The service does not choose a model, compute a vector, score a candidate, rerank or parse a file": the service may re-order the hits it is about to answer by an ordering their source declares against a fact about the caller, by position and never by score, and a source may declare what a hit brings with it (`source.affinity`, `source.expand`). It is written on the maintainer's ruling of that day, his choice of the decision card's option 「A 精简:排序加带出」 (record [`7251603512`](https://github.com/objectstack-ai/objectstack/issues/38412#issuecomment-7251603512) on #38412). It adds no contract member. A cross-reference stands under [K4](#k4--knowledge_source-is-admitted-as-a-metadata-type). The status line above is left as it is. +- **Amended** (2026-11-30, [#38692](https://github.com/objectstack-ai/objectstack/issues/38692)): a fifth dated note, under "Rules for every member" in [K8](#k8--the-contract-additions-decided-item-by-item), amends rule 4 of that list and the reading of the "Hybrid retrieval" row of [K1](#k1--the-boundary), and with it of "hybrid retrieval" in the title, in the D1 key-words line above and in TL;DR item 1: a knowledge source declares which retrieval legs run and the vector leg's share (`source.retrieval`), the adapter reports the modes it supports and still decides how candidates are found and how the legs are fused, and a parameter of one search request is not configuration. Decided by the maintainer on 2026-11-30: ruling record [`7270218011`](https://github.com/objectstack-ai/objectstack/issues/38692#issuecomment-7270218011) on #38692, given on his words 「同意,更新决策卡」 (2026-11-30T06:00Z) and revised after an independent review on his words 「全部采纳,修正裁决」 (2026-11-30T06:16Z); the note records the revised text. It registers two contract members, `AdapterCapabilities.retrieval` and `AdapterSearchOptions.retrieval`; that the second is optional, like the first, is his choice of the decision card's option 「可选(推荐)」 at 2026-11-30T07:57Z (record [`7272337479`](https://github.com/objectstack-ai/objectstack/issues/38692#issuecomment-7272337479) on #38692). It is in force from the maintainer's merge of the PR that carries it, which the record keeps for him: 「单独 PR,Tier H,由维护者亲手合并」. Cross-references stand under [K1](#k1--the-boundary) and [K4](#k4--knowledge_source-is-admitted-as-a-metadata-type). The status line above is left as it is. +- **Amended** (2026-11-30, [#38760](https://github.com/objectstack-ai/objectstack/issues/38760)): a sixth dated note, under "What follows from the two lists" in [K1](#k1--the-boundary), amends the reading of the "Rerank" row of that section, and with it of "rerank" in the title, in the D1 key-words line above and in TL;DR item 1. It amends again the sentence of that list which the fourth note amended, and rule 4 of [K8](#k8--the-contract-additions-decided-item-by-item) as the fifth note left it: a knowledge source may declare that its searches are reranked (`source.retrieval.rerank`), the reranker is the deployment's configuration and no source names a model, and the knowledge service reranks, after the permission re-check and before the cut to `topK`. The adapter contract does not change. Decided by the maintainer on 2026-11-30, after the rulings the fifth note records: on his words 「有就用」 (10:13Z) and 「所以还是应该按照主流系统的做法,开了开关,一律重排」 (10:37Z), as the body of [#38750](https://github.com/objectstack-ai/objectstack/issues/38750), the epic for knowledge retrieval rerank, records them, and on his 「全部同意」 (10:47Z) to the six decisions of that card (ruling record [`7276086125`](https://github.com/objectstack-ai/objectstack/issues/38750#issuecomment-7276086125) on #38750). The first of the six, which is not ruling D1 of the key-words line above, says of this note: "Accepting row 1's ADR-0161 note records it; no separate decision card." It adds no contract member, no tool argument and no settings key. Cross-references stand under [K2](#k2--the-texts-this-record-revises), [K4](#k4--knowledge_source-is-admitted-as-a-metadata-type) and [K8](#k8--the-contract-additions-decided-item-by-item). The status line above is left as it is. --- @@ -111,6 +115,51 @@ Ruling D1, as two lists. The left one is the knowledge service's work, done once - The split strategies and their rules belong to the splitter's card, #37098 (`whole`, `recursive`, `markdown`, aware of Chinese text). This record fixes who owns the split and where its key lives (K8, item 10). - **Why the purge and the grouping run in the service, not in SQL** (Prime Directive #5). The index sits behind the adapter contract and may live in another store than the records, so the anti-join that finds stale documents and the grouping of hits by record cannot be pushed down in general. An adapter that shares a database with the records may do either in SQL later; that is K8's item 13, and it comes back with its reader. +> **Note (2026-11-29, [#38502](https://github.com/objectstack-ai/objectstack/issues/38502)) — the second sentence of the list above: the service may re-order what it answers by an ordering the source declares against a fact about the caller, by position and never by score; and a source may declare what a hit brings with it.** The maintainer's words of 2026-11-29, verbatim and untranslated, as the filing gate of #38412 records them: 「检索按提问人单位加权,每种知识的要求不同吧,你的评估不能只考虑当前的规章制度,要考虑客户可能开发的各种元数据应用」. He ruled that day by choosing the decision card's option 「A 精简:排序加带出」, whose line on the card reads 「平台按提问人排序(加权、本单位就近优先),命中带出相邻或关联内容;不做硬筛选,按时间衰减等有应用要再加。一份架构记录加约三个 PR。」 (ruling record [`7251603512`](https://github.com/objectstack-ai/objectstack/issues/38412#issuecomment-7251603512) on #38412; the analysis is comment `7251063339` there). That record leaves three things to this note: the key names and shapes, how a boost combines with the stores' scores, and how neighbouring passages are read. A ◆ marks what this note decides past the ruling's words, for the approver to accept with it or strike. The conditions the ruling record carries are written below as given and are not marked. +> +> - **The sentence, amended.** The list above says: "The service does not choose a model, compute a vector, score a candidate, rerank or parse a file." From the merge of this note it reads: "The service does not choose a model, compute a vector, compute a score for a candidate, rerank or parse a file. It may re-order the hits it is about to answer by the ordering their source declares against a fact about the caller that the platform resolves, by position alone, and it changes the order the adapters answered in no other way." This is not rerank, which stays the adapter's in the table above: the service reads no passage text and calls no model to do it. It falls on the platform's side by K1's own test ("facts only the platform has"): who the caller is and where they sit in the organization is such a fact. The two tables, "Why the line is here" and the other sentences of the list are unchanged. +> - **◆ The keys, on the object arm.** `source.affinity?` and `source.expand?`, beside `metadataFields` and `split`, for item 10's reason: both name fields of the indexed object, so a later arm brings its own. A source that declares neither is answered exactly as before this note. No wrapper key holds the two: it would be a level kept for a third member this note does not admit, and no key is reserved (K4). +> - **`affinity`.** A list of entries `{ field, caller, mode, places? }`. `field` is a member of the source's `metadataFields`. `caller` names one fact from the closed list below. `mode` is `boost` or `nearest`, and nothing else: there is no `filter` mode, because narrowing is the search scope (item 17) and visibility is sharing. `boost` takes `places`, a positive integer; this note fixes no upper bound, and #38503 sets one and states it on the key. `nearest` takes none, reads a hierarchy, and a source declares at most one. Several entries add. +> - **◆ The caller facts are a closed list of two.** `user`: the caller's user id; `field` is then a field whose reference target (`packages/spec/src/data/field-value.zod.ts#referenceTargetOf`) is `sys_user`, and an entry matches a hit whose value is that id. `business_unit`: the caller's primary business unit, then each parent up to the root; `field` is then a field whose target is `sys_business_unit`, a `boost` entry matches a hit whose value is any unit of that chain, and `nearest` reads the chain in order. A list value (a lookup declared `multiple: true`) matches when an element does, and `nearest` takes its nearest element. Values are compared as a scope term compares them. Both are facts the resolver of [#38363](https://github.com/objectstack-ai/objectstack/issues/38363) answers, and the ordering reads that one resolver's answer, as the caller may read it about themselves, so a unit the caller may not read ends the chain below it. The resolver's third fact, the active organization, is left out: the organization filter of item 9 already decides which organizations' documents are ranked, and no application asks to order by it. The platform resolves a fact from the execution context the search already carries, at most once per search and only when a searched source declares an entry that reads it. It is never an argument of the tool, an option of `search`, or a value a client or a model supplies. The system identity is no caller in this sense, and a caller with no primary unit has no chain: an entry that finds no fact matches nothing. The active organization, positions, teams and non-primary memberships are not in the list; each joins it by a dated note here, with its resolver and its first reader. +> - **What is re-ordered.** The search runs as it does today up to its answer: the rounds, the scope check, the permission re-check, the per-hit record check, and the grouping under record granularity. What that leaves is the units that could be answered, best first by the adapters' scores: passages, or records, or `groupBy` groups, each standing as one hit. Today the first `topK` of them are answered. The re-order works on that list, before the cut to `topK`, and on nothing else. It asks no adapter again and changes neither the size of a round nor the condition of the refill, so a search still reads at most `topK × SEARCH_REFILL_FACTOR` passages per source (`packages/services/service-knowledge/src/knowledge-service.ts#SEARCH_REFILL_FACTOR`). A caller the re-check applies to is already asked `topK × SEARCH_FIRST_ROUND_FACTOR` per source in the first round, so there are units below `topK` to bring up. Under record granularity the freshness check then checks the hits about to be answered, as today. Nothing in the answer says that a hit moved or how far, and no count is returned (K9 rule 6, K10 rule 4); the moves go to the `debug` log. +> - **◆ By position, never by score.** (1) Per source: the units of one source are re-ordered among the places that source's units hold in the list, and a unit of another source is never moved. A declaration is one source's, and `nearest` means nothing for another source's hit. How units of different sources stand against each other stays what it is today. (2) A unit is judged on the hit that stands for it: that hit's source, and that hit's `metadata[field]`. (3) `nearest` parts the source's units into tiers: the caller's own unit first, then each parent in order, then every other unit together, a hit with no value among them. (4) Inside a tier, with its units numbered from 1 in their order, a unit's key is its number minus the sum of `places` of the `boost` entries it matches. The tier is ordered by key; a tie goes to the larger sum, then to the earlier number. So a unit that matches one entry with `places: 3` passes at most three units of its tier that match nothing, and a source without `nearest` is one tier. (5) A hit keeps the `score` its adapter answered. The service writes no score of its own, so an answer may no longer be in descending `score`. +> - **◆ Why position.** Read at `545a4fa278`: `knowledge-pgvector` and `knowledge-turso` answer a reciprocal rank fusion of two legs (`packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts#RRF_K`, `packages/plugins/knowledge-turso/src/turso-adapter.ts#RRF_K`, both 60), divided by the score of a passage first in both legs. The passages ranked first to tenth in both legs score from 1 down to about 0.87, and a passage only one leg ranks scores at most 0.5. `knowledge-memory` answers the cosine similarity itself, and the hit's schema says the meaning of `score` is each adapter's (`packages/spec/src/ai/knowledge-document.zod.ts#KnowledgeHitSchema`). So a number added to a score, or multiplied into it, orders one source differently on each store: `+0.1` lifts a hit ranked ninth in both legs to second on the two SQL stores, and on the memory store past however many hits lie within 0.1 of it. A source is written once and builds on every store (K4), and a search over several sources may read several stores. Every adapter answers its hits best first, whatever its numbers mean, so position is the one thing the service can read alike from all of them. It also keeps what the amended sentence still forbids: the service computes no score. The other answers: adding to or multiplying the score, for the reason above. A rank fusion with the declaration as one more leg, which reads positions too: with the stores' constant, a weight near 1 puts every match above every non-match in a first round of 25 passages (the tool's default `topK` of 5), and a smaller weight has no unit an author can check. Matches first with no number, which is what `nearest` is: for a `boost` it would put a weak match above the best passage every time, and the ruling names both. +> - **Judged on the index copy; never an access decision.** An entry is judged on the values assembly stored with the document, as a scope term is, fresh as of the last sync. A document indexed before its source listed the field carries no value and matches nothing until a rebuild writes it again. The order tells a caller nothing they could not work out themselves: source admission already requires every `metadataFields` member to be queryable by the caller before the source is searched for them, and the facts are the caller's own. The re-order moves hits that passed the re-check; it removes none and admits none. +> - **◆ `expand.window`.** A positive integer: the passages on each side of the hit's passage, in the same document, that the hit brings with it, counted across headings. The heading-bounded mode of the decision card (`siblingsBy`) is not taken: it returns by a dated note here with a consumer. They are not hits: they are not counted in `topK`, they are not ordered, and no passage is answered twice in one answer, so a neighbour that is itself answered as a hit, or that an earlier hit already brought, is left out. Under record granularity the neighbours are those of the passage that stands for the record or the group. #38504 bounds the key and states the bound on it; this note fixes no number. +> - **◆ Neighbouring passages are cut again from the record; no adapter member is added.** Read at `545a4fa278`. A passage carries `id`, `documentId`, `index`, `content` and `headingPath?` (`packages/spec/src/ai/knowledge-document.zod.ts#KnowledgeChunkSchema`) and no position in the document's text. Its text is not a slice of that text either: under `markdown` a passage begins with its heading path, and a table cut between rows repeats its header row in each piece. So a neighbour is a passage, not a range, and there are two ways to have it. No method of the adapter contract reads a passage by document and index (`packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`); adding one reopens the list rule 5 of K8 closes. The other way needs no member. The splitter is pure (`packages/services/service-knowledge/src/split/splitter.ts#splitDocument`), the fingerprint covers the applied split and its algorithm version, and a search is served only under the fingerprint the service expects (K7 rule 5), so a document whose hash is the hit's `docHash` cuts again into the passages the index holds, index for index. The service already reads a hit's record, assembles it and compares that hash in two places: the freshness check of a record-level search, and the per-hit record check (`checkFreshness` and `dropUnverifiedHits` of `packages/services/service-knowledge/src/knowledge-service.ts#KnowledgeService`). **So the service does that for the hits it is about to answer, at most `topK`, cuts each matching document again, and takes the passages around the one whose `id` is the hit's `chunkId`.** ◆ One more check stands on that passage, because the fingerprint is an optional member (rule 2 of K8; K7 has a row for an adapter with no `indexStatus`) and `docHash` does not cover the split: an adapter that does not hold a search to the fingerprint may still answer passages cut under an earlier split. So neighbours are attached only when the `content` of the passage cut at that `id` is the hit's `snippet`, character for character, which is what a passage's `content` is defined as. The service judges the text it holds and nothing an adapter reports, so the rule is the same for an adapter with `indexStatus` and one without. It costs one read per source, of those records only, projected to the fields assembly reads, and a split in memory; no adapter is called and nothing is embedded. Why this one: every adapter that takes chunks gets it with no change, where an optional member would bring nothing on an adapter that lacks it (rule 2); and a neighbour is text of the record as it reads now, where a member would answer the index copy, which K10 rule 3 keeps for ranking and snippets. The price: a long document is read whole to bring a few passages. A member that reads passages by position returns by a dated note here, with a store as its reader, when that cost is measured on a real source. +> - **When a hit brings no neighbours.** Its adapter does not declare `capabilities.chunks`, so its passages are its own (the service says so once in its log, naming the adapter; rule 2). The hit carries no `docHash` or no record id. The record's hash is not the hit's, so the index is behind the record: the hit is answered as it is today, and its document is repaired as the freshness check repairs one. The cut holds no passage with the hit's `chunkId`, or that passage's `content` is not the hit's `snippet`: the store's passages were cut under another split, or its snippet is not the passage. The read fails. In each case the hit is answered without neighbours and nothing in the answer says why. A neighbour is attached only for a row that passed the caller's re-check in this search, and it is cut from fields the source admission already requires that caller to be able to query. +> - **◆ `expand.follow`.** A list of field names: `lookup` or `master_detail` fields of the indexed object that the source lists in `metadataFields`, one hop each. A hit brings, for each, the record the field points at: its object, its id and its title, the title being that object's display field as a hit's title is (K5). The id is read from the hit's record as it reads now, and the related record is read as the caller, under every gate a read of that object through the record tools passes. Nothing of it is stored in an index. A related record the caller may not read, one that no longer exists and an empty lookup all bring nothing, with no marker and no count; the answer then says no more than the row itself says to a caller who may query the field. The hop brings the name, not the content: an answer reads content as the asking user through the record tools (K10 rule 3), and a model that wants the related record's own passages searches with `scope` (item 17). So #38505's "declared fields" are this hop's three. A list of fields to bring, a second hop, and a `user` field as a hop each return by a dated note here with a consumer. A `multiple` lookup brings each record it names up to a bound #38505 states. +> - **◆ How an expansion rides.** On the hit of the one `search_knowledge` definition (K9 rule 1): `neighbours`, a list in document order of `{ offset, snippet, headingPath? }`, where `offset` is the signed distance from the hit's passage; and `related`, a list of `{ field, object, id, title? }`. An expansion is a result of the service, not a member ("What counts as a member" in K8): no adapter stores, reads or returns it, so the `KnowledgeHit` an adapter answers gains no key and the list stays closed. `IKnowledgeService.search` keeps its signature and its return type, and its hits come back in the declared order. The expansions ride beside the hits on the report the tool already reads for refused sources, and the slice that builds each writes that carrier. The tool gains no argument (K9 rule 2): there is no opt-out until a consumer asks. +> - **Refused when it is written**, by the schema or by the lint and `os validate` checks of row 4, each with a sentence that names the fix: a `field` or a `follow` member that is not in `metadataFields`; a `field` whose target is not the one its `caller` names; a `mode` outside the two, and a `filter` there is answered that narrowing is the search scope and visibility is sharing; a second `nearest`; `nearest` with a `caller` other than `business_unit`; `places` missing on a `boost`, present on a `nearest`, or not a positive integer; `expand.window` on a source whose split is `whole`, where a document is one passage and the key could do nothing (ADR-0078); a `follow` member that is not a `lookup` or `master_detail` field, or whose target is an object the record tools serve to no caller (a system object without `enable.aiReadable`), where the hop could bring nothing (ADR-0078). A source registered in code parses the same schema (point 3). +> - **No index is rebuilt for either key.** Neither enters the fingerprint or the recipe hash (K7): both are read when a search is answered and change nothing a store holds. Listing a field in `metadataFields` so that an entry can read it changes the recipe hash, as it always did. +> - **Not in this note.** A `filter` mode. A decay by date (`recency`): it returns by a dated note here with its first consumer. An opt-out argument on the tool. Any change to how hits of different sources are merged. +> - **The slices that build it**, each after this note merges, each key with its reader and its refusals in one PR (K10 rule 1). [#38504](https://github.com/objectstack-ai/objectstack/issues/38504): `expand.window`, which needs no identity. [#38503](https://github.com/objectstack-ai/objectstack/issues/38503): `affinity`, after #38363; it also settles with #38363 where the resolver lives so that the knowledge service can call it. Its acceptance is the ruling record's: on one question set, three arms (no identity, the model told who asks, the model told plus a declared `nearest`), at least three runs each, and if the third does not beat the second beyond the run-to-run range that result returns to the maintainer before `expand.follow` is built. [#38505](https://github.com/objectstack-ai/objectstack/issues/38505): `expand.follow`, after that. Each slice rewrites the docs sentences its code makes untrue, never ahead of it (K2). +> +> This note adds no contract member, no tool argument and no settings key: the list stays closed (rules 3 and 5 of K8). It declares, and the three slices build it. Until they land, `main` orders hits by the adapters' scores alone and a hit brings nothing with it. The code this note cites was read on `main` at `545a4fa278`; #38363 is a draft on its branch at `0cea24a56c`, not merged, and this note names the two facts its resolver answers, not its code. The tables of K1, the K8 table and every earlier note are left as written; read the list's second sentence with this note. + +> **Cross-reference (2026-11-30, [#38692](https://github.com/objectstack-ai/objectstack/issues/38692)).** The "Hybrid retrieval" row of the adapter's table above is read with the dated note of 2026-11-30 under "Rules for every member" in [K8](#k8--the-contract-additions-decided-item-by-item), and so is "hybrid retrieval" in the title, in the D1 key-words line and in TL;DR item 1: a knowledge source declares which retrieval legs run and the vector leg's share, and the adapter still decides how candidates are found and how the legs are fused. That note also answers two sentences of "◆ Why position" in the note of 2026-11-29 above: "a smaller weight has no unit an author can check", and "a passage only one leg ranks scores at most 0.5", which stops being true of every search. No sentence of K1 or of the note of 2026-11-29 is changed. + +> **Note (2026-11-30, [#38760](https://github.com/objectstack-ai/objectstack/issues/38760)) — the "Rerank" row of the adapter's table above, and the second sentence of the list: a knowledge source may declare that its searches are reranked; the deployment configures the reranker, and no source names a model; the knowledge service reranks, after the permission re-check and before the cut to `topK`.** The maintainer's words of 2026-11-30, verbatim and untranslated, as the body of [#38750](https://github.com/objectstack-ai/objectstack/issues/38750), the epic for knowledge retrieval rerank, records them. At 10:13Z: 「有就用」, in answer to the question that body gives as 「是否重排以及模型为什么不是知识源上的开关?」. At 10:37Z: 「所以还是应该按照主流系统的做法,开了开关,一律重排」. In English, the question is why whether to rerank, and the model, are not switches on the knowledge source. The first answer: if there is one, use it. The second: so it should still be done as mainstream systems do it, and with the switch on a search is always reranked. That body states what the two decide under "Rulings", items 1 to 3, and the bullets below quote them. At 10:47Z he answered the six decisions of #38750 with 「全部同意」, all agreed (ruling record [`7276086125`](https://github.com/objectstack-ai/objectstack/issues/38750#issuecomment-7276086125) on #38750). That card numbers its six D1 to D6. Below they are written #38750 D1 to #38750 D6, and none of them is ruling D1, D2 or D5 of this record. #38750 D1, in the ruling record: "The knowledge service reranks, after the permission re-check. Accepting row 1's ADR-0161 note records it; no separate decision card." Row 1 of #38750 is this note. At 11:02:50Z, asked what becomes of #38750, he chose 「照常做,作为平台能力」, carry on as planned, as a platform capability (record [`7276461244`](https://github.com/objectstack-ai/objectstack/issues/38750#issuecomment-7276461244) on #38750). All of these are later than the rulings that the note of 2026-11-30 under [K8](#k8--the-contract-additions-decided-item-by-item) records, which are of 06:00Z to 07:57Z that day. Where the two differ, the later words are the ones this note records. This note marks no ◆. What it states is in those rulings, or in what that body's design says of the placement #38750 D1 confirms: who reranks, and why there. Where it reads an earlier sentence of this record anew, it quotes the sentence. What the rulings leave open, it leaves to the rows of #38750 by name, under "Not in this note". The wording of the amended sentences is this note's. +> +> - **The "Rerank" row.** The adapter's table gives it "Whether a second model reorders candidates, and which." From this note neither is the adapter's. Whether: a knowledge source declares it. Which: the deployment configures the reranker, and no source names a model. And it is the knowledge service that reranks, after the permission re-check and before the cut to `topK`. The adapter contract does not change: `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter` and `AdapterSearchOptions` in the same file gain nothing. What the row keeps is the adapter's own search, which this record gives it in two places this note does not touch: "how candidates are found" (the "Hybrid retrieval" row) and "Changing the adapter changes how candidates are found and ranked" ([Consequences](#consequences)). The table is left as written. +> - **Why the service, and why after the re-check.** K1's test for the platform's side is "facts only the platform has". Which passages the caller may read is such a fact, and no adapter has it: an adapter "does not check permissions" (the list above). So a rerank that stands after the re-check can only be the service's, and because it stands there, only text the caller may read is handed to the reranker. "Why the line is here" is read with this: its "The four on the right need none of those" no longer holds of rerank, and the reranker itself is still an engine the deployment brings and this repository does not write. The record of #38692 had already said whose a platform-wide rerank would be, in words the note of 2026-11-30 under K8 quotes: 「平台以后如果统一做重排,那是知识服务的配置。」 This note records that case. +> - **The sentence of the list, amended again.** As the note of 2026-11-29 left it, the second sentence of the list reads: "The service does not choose a model, compute a vector, compute a score for a candidate, rerank or parse a file. It may re-order the hits it is about to answer by the ordering their source declares against a fact about the caller that the platform resolves, by position alone, and it changes the order the adapters answered in no other way." From the merge of this note it reads: "The service does not choose a model, compute a vector, compute a score for a candidate or parse a file. It may re-order the hits it is about to answer in two ways, and it changes the order the adapters answered in no other way: by the ordering their source declares against a fact about the caller that the platform resolves, by position alone; and by reranking them, where their source declares it and the deployment has configured a reranker, after the permission re-check and before the cut to `topK`." The service still chooses no model and computes no score: the deployment's configuration names the reranker, and the reranker judges the passages. +> - **One sentence of the note of 2026-11-29.** It says of its own re-order: "This is not rerank, which stays the adapter's in the table above: the service reads no passage text and calls no model to do it." The re-order by a declared ordering is still not rerank, and the service still reads no passage text and calls no model to do it. What changes is the clause between: rerank no longer "stays the adapter's". And of the rerank the second half is not true: to rerank, the service hands the question and passage text to a model. Nothing of `source.affinity` or `source.expand` changes, and the other sentences of that note are left as written. +> - **The title, the D1 key-words line and TL;DR item 1.** Each says that adapters own rerank. From this note the word is read in those three places as the row is read above: it no longer covers whether the hits of a search are reranked, by which model, or by whom, and it covers only what an adapter does inside its own search. TL;DR item 1 keeps its "Adapters own four", two of them now read as narrowed: hybrid retrieval by the note of 2026-11-30 under K8, rerank by this one. The three texts are left as written; the D1 line is a quotation of the filing gate's record. +> - **The source key.** The body of #38750, under "Rulings", item 1: "A knowledge source may declare `retrieval.rerank` (boolean). The model is never chosen by the source; it comes from the deployment". The key is `source.retrieval.rerank?`, a third optional key of the `source.retrieval` group that the note of 2026-11-30 under K8 declares; `mode` and `vectorWeight` stand as that note states them. A source that does not declare it is searched as before this note. How a deployment states its reranker is under "Not in this note". +> - **No reranker is configured.** Item 2 of that list: "No reranker configured: the search runs normally, the report marks the source not reranked, and saving/publishing the source shows a notice. Never a refusal, never fewer hits." The mark is the reason `no_reranker` in the report's `notReranked`, the two names the ruling record uses (#38750 D2 and #38750 D4). This is not what the note of 2026-11-30 under K8 does with a `mode` the store cannot run, which is refused at four points: a declared rerank is accepted and its search is answered, on 「有就用」. The declaration is not silent (ADR-0078): each such search says that its source was not reranked, and the author is told when the source is saved or published. +> - **A reranker is configured and the source declares it.** Item 3 of that list: "Switch on + reranker configured ⇒ every search is reranked. No skip by candidate count or score gap. Only 0 or 1 candidate makes no call (nothing to order) and sets no marker. At most 50 passages are sent per search; the number of searches is not capped." That is the maintainer's 「开了开关,一律重排」. +> - **A configured reranker fails or times out (#38750 D2).** The ruling record: "adapter order kept, the source marked `failed` in `notReranked`, one attempt (`maxRetries: 0`), 3 s; a configuration failure (4xx: wrong key or model) logged at `error`. Not a coded refusal." So the search is still answered, and its report says that the rerank failed. The reranker is asked once, with no retry, under a limit of 3 s. +> - **One model and one wire format (#38750 D3).** The ruling record: "One reranker model and one wire format for v1, the one the first deployment can reach; no vendor preset list." Which model that is, and the one development tests use, are in ruling records `7276135635` and `7276183954` on #38750. This record names neither. +> - **A hosted deployment (#38750 D4).** The ruling record: "Hosted reranking after row 6 shows a gain (or a hosted customer asks). Until then a hosted source that declares rerank is searched normally and marked `no_reranker`." Row 6 of #38750 measures rerank on against rerank off. #38750 D5, the hosted recipient and its charging, is not decided. #38750 D6 is a rule for one application and is not this record's. +> - **What the reranker is sent.** To rerank, the service hands a model the question and at most 50 passages per search, each one a passage that passed the permission re-check for this caller. A deployment that configures no reranker sends nothing. Configuring one is the deployment's decision to send that text to it, as configuring an embedder is (K5, and the note of 2026-11-28 under K8). +> - **Rule 4 of K8, amended again.** As the note of 2026-11-30 under K8 left it, rule 4 reads: "Which provider, which key, how to batch, rerank toggles and parser options stay in the adapter's own plugin options. Hybrid weights are declared by the knowledge source. A parameter of one search request is not configuration." From the merge of this note it reads: "Which provider, which key, how to batch and parser options stay in the adapter's own plugin options. Hybrid weights are declared by the knowledge source, and so is whether its searches are reranked. The reranker is the deployment's configuration, and no source names a model. A parameter of one search request is not configuration." The rule's headline is unchanged: the contract carries what an adapter reports, never how it is configured, and it still carries no rerank. An adapter's plugin options stay its own ("What counts as a member"); this note takes none from it and gives it none. +> - **Three sentences of the note of 2026-11-30 under K8.** Under "Rule 4, amended" it quotes the record of #38692: 「K8 第 4 条:「hybrid weights」改划给知识源声明;rerank toggles、parser options 照旧留在驱动。」 It quotes that record's section 六 there too, 「永远不进知识源协议」: 「融合算法及其常数、重排、分数阈值、分词器。平台以后如果统一做重排,那是知识服务的配置。」 And under "Not in this note" it says: "Rerank, a score threshold, a tokenizer and the fusion algorithm with its constant never enter the source (section 六, above)." From this note the three are read so. Of rerank, a switch enters the source and nothing else does: no source names a reranker or a model. That switch is not an adapter's option. The fusion algorithm with its constant, a score threshold and a tokenizer still never enter the source, and parser options stay the adapter's. The last sentence of section 六 stands for the reranker itself: which one a deployment uses is configuration the knowledge service reads, and no source's. That note states the record of #38692 as it was ruled and is left as written. +> - **Three rows of K2.** Each names rerank in its "What it becomes" column. The opening of `content/docs/protocol/knowledge.mdx`: "Engines are integrated for embedding, hybrid retrieval, rerank and file parsing." It stays true as a sentence, because a reranker is an engine the deployment brings. What it no longer means is that an adapter integrates it: the knowledge service calls it. The §3.4 row keeps its "no rerank": the adapter contract carries none, before this note and after it. The class note of `KnowledgeService`: "Embedding calls, vector storage, hybrid retrieval and rerank stay the adapter's." From this note the first three stay the adapter's, and reranking the hits of a source that declares it is the service's. This note rewrites none of those texts: each is rewritten by the PR whose code makes the new sentence true (K2). The table is left as written. +> - **Not in this note.** #38750 D5. How a deployment states its reranker, and what the knowledge service calls it through: the contract, the client and the settings are rows 2 and 3 of #38750, each landing with its reader. By "What counts as a member" none of them is a member: a member is what an adapter author must read, and no adapter reads these. How many candidates are reranked under the ceiling of 50; how a rerank and a declared `affinity` follow one another; how the hits of several sources stand against each other; what `notReranked` looks like on the report and in the answer of `search_knowledge`; how the notice is shown: each belongs to the row that builds it. A per-search argument on the tool (K9 rule 2). +> +> This note adds no contract member, no tool argument and no settings key: the list stays closed (rules 3 and 5 of K8). It declares, and the rows of #38750 build it. Its row 2 brings the key with its reader in one PR (K10 rule 1), and each row rewrites the docs sentences its code makes untrue, never ahead of it (K2). Until then `main` has no such key and reranks nothing. Read on `main` at `acf3b33e31`: `packages/services/service-knowledge/src/knowledge-service-search.ts#searchByKey` re-checks the hits as the caller (`applyPermissionFilter`), orders them by a declared `affinity` (`affinityOrderFor`) and cuts them to `topK`, with no rerank between; and, tests aside, in `packages/services/service-knowledge/src` and the `src` of `knowledge-memory`, `knowledge-pgvector` and `knowledge-turso` the word `rerank` is on one line, the class note that K2 lists (the control `embed` is on 412). The title, the two tables of K1, the tables of K2 and K8, the rules of K8 and every earlier note are left as written; read the "Rerank" row, the second sentence of the list and rule 4 with this note. + **The push door.** `indexDocument(sourceId, doc)` and `deleteDocument(sourceId, documentId)` hand a caller-built document to the adapter. On an object source that contradicts the first row above and K5: a pushed document is not built by assembly, so neither the content list nor the egress rule binds it, and the purge of #37096 removes it at the next complete rebuild, because no record answers for it. So **both calls are refused on an object source**, with a coded refusal (ADR-0112), from row 3 at the latest; an earlier card that touches the door may land the refusal sooner. They remain the write door of a source that is not an object source. Whether v1 has such a source is point 1 (K4): if that point stands, the two methods leave `IKnowledgeService` with the `file` and `http` arms. ### K2 — The texts this record revises @@ -123,7 +172,7 @@ Each text below states the old position. The left column quotes it as it reads a | Same file, §1: "We have nothing distinctive to add to those layers." and "The protocol scopes the framework's responsibility to (1)–(4) and delegates the rest to plugins." | The framework's list grows by the four of K1; what is delegated is the adapter's four. | #37096 | | Same file, §3.1: a source "is stored as metadata (versioned, environment-scoped) just like a view or a flow", against the schema note on `packages/spec/src/ai/knowledge-source.zod.ts#KnowledgeSourceSchema`: "the shape of a **runtime registration**, ⛔ not a governed metadata type". | The two agree: a source is a `knowledge_source` item (K4). Until row 3 lands, the schema note is the true one. | row 3 | | Same file, §3.2: "The framework does **not** chunk; adapters do." | The framework splits; adapters index the passages. | #37098 (row 6) | -| Same file, §3.4, and the note on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`: "The surface is **deliberately minimal**: no chunk strategy, no embedding configuration, no rerank toggles." | The contract grows by K8's list. It carries what an adapter reports about its embedder and still no configuration, no rerank and no hybrid toggle. | #37096, then each card that adds a member | +| Same file, §3.4, and the note on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`: "The surface is **deliberately minimal**: no chunk strategy, no embedding configuration, no rerank toggles." | The contract grows by K8's list. It carries what an adapter reports about its embedder and the retrieval modes it runs (`capabilities.retrieval`), and the mode a search runs in (`AdapterSearchOptions.retrieval`): the source's declaration, else the adapter's default; still no configuration and no rerank. | #37096, then each card that adds a member (#38692 phase 1a: the retrieval mode) | | Same file, §6: "that surface stays unbuilt until a real `object` source calls for it." | The enumeration surface is built (K8, item 1); reconcile covers application-level predicate writes. | #37096 and row 15 | | Same file, §7 and §8: `knowledge-pgvector` as "Phase 3", and "a `KnowledgeSource.embedding` field". | `knowledge-pgvector` is an open adapter of this repository (cloud ADR-0119 D5); `embedding` is removed (K6). | #37100, row 3 | | `packages/spec/src/ai/embedding.zod.ts`, file note: "NOT in scope (these belong to application code, not the platform): Chunking strategies (fixed/semantic/recursive/markdown)." and "These were removed in v1 because they describe one specific way to build a RAG application". | Structural splitting is a platform capability of the knowledge service. It does not return as the pipeline vocabulary that was removed. Retrieval pipelines, document loaders and end-to-end orchestration stay out of scope. | #37098 | @@ -134,6 +183,8 @@ The same position is restated in `content/docs/ai/knowledge-rag.mdx` ("Why we di **The rule for all of them (Prime Directive #10).** A text is rewritten in the PR whose code makes the new sentence true, and not before. This record changes no file outside `docs/adr/`. A reader who meets an old sentence in the meantime finds this record through the ADR index. +> **Cross-reference (2026-11-30, [#38760](https://github.com/objectstack-ai/objectstack/issues/38760)).** Three rows of the table above name rerank in "What it becomes": the opening of `content/docs/protocol/knowledge.mdx`, §3.4 of that file, and the class note of `KnowledgeService`. Each is read with the dated note of 2026-11-30 on #38760 under "What follows from the two lists" in [K1](#k1--the-boundary): a knowledge source may declare that its searches are reranked, the deployment configures the reranker, and the knowledge service reranks. So rerank is no longer among what "stay the adapter's", a reranker is an engine the knowledge service calls and no adapter integrates, and the adapter contract still carries no rerank. The rule above holds for these texts as for every other: each is rewritten by the PR whose code makes the new sentence true, and not before. That note changes no row of the table. + ### K3 — What this record supersedes **1. The three judgements of #4606, and its restart condition.** #4606 (2026-08-02, closed 2026-09-24) recorded the maintainer's positioning in its body: @@ -220,6 +271,14 @@ The package whose README and tests carry the `http` shape, `knowledge-ragflow`, > **Cross-reference (2026-11-25, [#37325](https://github.com/objectstack-ai/objectstack/issues/37325)).** Which package's source a name means is ADR-0150's question, and this record does not ask it. Its [addendum of 2026-11-25](./0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md#addendum-2026-11-25-knowledge_source-joins-bucket-3) puts `knowledge_source` in bucket 3 beside `skill` and `ai_context`, on the maintainer's ruling 「按应用+名字区分,都保留」 (record [`7168239918`](https://github.com/objectstack-ai/objectstack/issues/37304#issuecomment-7168239918) on #37304): a source is identified by `(package, name)`, two packages that ship one source name each keep their source, and the keys of a source's index carry the package. Point 3 above is read with it: "A name is one source" holds between two packages by keeping both, and which holder a registration in code is stays open there, for row 3. So is [K6](#k6--adr-0087-dispositions): item 4 stays true of the rename, and the re-keying is what moves a document id and rebuilds an index; item 5 keeps its spellings, and the value each carries for a package's source is that addendum's and row 3's to state. Row 3 ([#37304](https://github.com/objectstack-ai/objectstack/issues/37304)) follows the addendum. No sentence of this record is changed. > > **Cross-reference (2026-11-26, [#37545](https://github.com/objectstack-ai/objectstack/issues/37545)).** Which holder a registration in code is was ruled on 2026-11-26: **A**, by the maintainer's word 「两处都选 A」 (record [`7192063608`](https://github.com/objectstack-ai/objectstack/issues/37304#issuecomment-7192063608) on #37304). ADR-0150's addendum carries the ruling as the dated note under [point 6 of "Past the ruling's words"](./0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md#addendum-2026-11-25-knowledge_source-joins-bucket-3). The record states it as: "A knowledge source registered in code belongs to no package. It is read as the environment's own source and takes the one package-less slot of its name, keeping its bare key, bare face and existing index. The duplicate refusal compares `(package, name)`. A code registration and an environment-authored source of one name are the same slot, so the second arrival is refused, naming both doors. A code registration and a package's source of one name are two sources, and both are kept." Point 3 above is read with it. No sentence of this record is changed. +> +> **Cross-reference (2026-11-28, [#38368](https://github.com/objectstack-ai/objectstack/issues/38368)).** Whether a mounted knowledge service is enabled is the question of the dated note of 2026-11-28 under the table of [K8](#k8--the-contract-additions-decided-item-by-item), read with item 12. Two texts above are read with it. Clause 3 ("A real consumer"): where the runtime mounted the service and it is not enabled, a source is loaded and listed to administrators, whichever store it names, and it is not built, synced or searched until a boot finds an embedder and the deployment's store. "Source admission at save": an author's save is also refused while the service is not enabled, at the save doors that note names, the package move-in among them, and the package duplicate door is not refused for that reason. No sentence of this record is changed. +> +> **Cross-reference (2026-11-29, [#38502](https://github.com/objectstack-ai/objectstack/issues/38502)).** Two source keys are declared by the dated note of 2026-11-29 under "What follows from the two lists" in [K1](#k1--the-boundary): `source.affinity` and `source.expand`, on the object arm. The table above lists the v1 keys as they stood and is left as written. Each of the two lands with its first reader (#38503 for `affinity`; #38504 and #38505 for `expand`), as "A key added later lands with its first reader" asks, and neither is reserved before that. No sentence of K4 is changed. +> +> **Cross-reference (2026-11-30, [#38692](https://github.com/objectstack-ai/objectstack/issues/38692)).** One group of source keys is declared by the dated note of 2026-11-30 under "Rules for every member" in [K8](#k8--the-contract-additions-decided-item-by-item): `source.retrieval`, with `mode` and `vectorWeight`, beside `source.affinity`. The table above lists the v1 keys as they stood and is left as written. Each key lands with its first reader, as "A key added later lands with its first reader" asks: `mode` in phase 1a of ruling record `7270218011` on #38692, and `vectorWeight` in its phase 1b, after #38671. One text above is read with that note. The reason given for "`adapter` becomes optional" is that "one source written as metadata must build on `os dev`, on a hosted environment and on PostgreSQL". The note records one intended exception: a source that explicitly declares a retrieval mode its store does not support is refused, at the four points the note lists, and its index is still built. A source that omits `mode` is not in the exception. No sentence of K4 is changed. +> +> **Cross-reference (2026-11-30, [#38760](https://github.com/objectstack-ai/objectstack/issues/38760)).** One more source key is declared, by the dated note of 2026-11-30 on #38760 under "What follows from the two lists" in [K1](#k1--the-boundary): `source.retrieval.rerank`, a boolean, in the group the cross-reference above names. The table above lists the v1 keys as they stood and is left as written. The key lands with its first reader, as "A key added later lands with its first reader" asks: row 2 of #38750. It is not reserved before that. One text above is read with that note. "The v1 keys are the keys something enforces": the knowledge service reads this key, and what follows depends on the deployment. Where a reranker is configured, every search of the source is reranked. Where none is, the source is searched normally and is not refused, each such search is marked, and saving or publishing the source shows a notice. That is the opposite of the exception the cross-reference above records for a `mode` the store does not support, and it is the maintainer's ruling: 「有就用」. No sentence of K4 is changed. ### K5 — A source lists its content fields; embedding is egress @@ -347,6 +406,25 @@ The epic holds the contract shut until this record merges ("No new adapter-contr > > This note adds exactly one member, `AdapterSearchOptions.scope` with its term type, and no other: the list stays closed beyond it (rules 3 and 5). #37308 builds it after this note merges, in one PR: the member, its first reader in `knowledge-memory`, and the suite cases. The code this note cites was read on `main` at `829a45e96c`. The table is left as written; read item 17 with this note. +> **Note (2026-11-28, [#38368](https://github.com/objectstack-ai/objectstack/issues/38368)) — item 12: a knowledge service the runtime mounts is enabled by configuration; until it is, its sources are held and not served.** Item 12 is unchanged: the `knowledge` token, or a `knowledge_source` the stack ships, mounts the knowledge service and the deployment's store. Mounted is not enabled. The maintainer's words of 2026-11-28, verbatim and untranslated, in the order the filing gate of #38368 records them: 「如果我还是想把知识库放到 统一的 app-starter,但是根据平台的实际运行情况,决定是否有知识搜索的能力呢?」「也就是同一套元数据,企业版和社区版运行结果不一样」「平台没有知识服务时,知识源不应该启用啊。」「知识服务本身应该也可以有一个开关」「云端不需要管,企业版其实看的也是有没有配置相关的参数」「私有部署判断的是相关参数有没有配置」. So one set of metadata ships to every deployment, and what a self-hosted deployment has configured decides whether it searches. A ◆ marks a choice past those words. Three were put to the maintainer with their recommendations and ruled that day by 「以上都同意」; each is recorded below in the card's words. Four more were put to him on 2026-11-29 and ruled by his choice of the decision card's option 「全按推荐(1A 2A 3A 4A)」 (record [`7248214179`](https://github.com/objectstack-ai/objectstack/issues/38368#issuecomment-7248214179) on #38368); each is recorded below with that date, under the number the record gives it. +> +> - **Enabled.** A knowledge service the runtime composes for item 12 (`packages/core/src/capability-composition.ts#resolveServedCapabilities`, read by `os serve` and by `@objectstack/verify`) is enabled when, at `kernel:bootstrapped`, an embedder is available and the deployment's store is mounted. An embedder is available when another plugin registered one, or when the saved `ai.embedder_*` settings build one (`packages/services/service-knowledge/src/knowledge-service-plugin.ts#provideEmbedder`). The store is mounted when its adapter is registered; whether a registered store can open its database is outside this note, which declares no boot probe of it. That event follows every plugin's `start()` and every `kernel:ready` handler, so an embedder or a store that is absent then is absent for that boot. The state is read once per boot: a changed setting takes effect at the next restart, which the settings page already says (the description of `embedder_provider` in `packages/services/service-settings/src/manifests/ai.manifest.ts#aiEmbedderSettingsSpecifiers`). +> - **◆ Ruled 2026-11-29 (point 2): the state is the whole service's.** Every source of a service the runtime mounted is held while the service is not enabled, whichever store it names, a store the application registered included. An application whose store embeds on its own mounts the knowledge service itself in `plugins[]`, which the third ◆ below leaves outside this note. On `main` a source on an application's store that reads no embedder is built and searched under a runtime-mounted service with none saved, so holding it is a narrowing, and a named part of the one #38369 declares. +> - **Not enabled: held, not served.** The sources are loaded and listed to administrators. They are not built, synced, reconciled or searched. The service hands out no tool definition, so no transport registers `search_knowledge`: every transport registers the one definition the service hands out (K9 rule 1), so the tool is absent on all of them alike. A direct `search` is refused with a coded refusal (ADR-0112) that names the remedy, and it is never answered empty, which is K7 rule 5's rule for a source that cannot be searched. The state is said once, in the boot's log (K8 rule 2: nothing is skipped silently). +> - **◆ Ruled 2026-11-29 (point 3): no reap guard and no store call.** While it is not enabled the service registers no lifecycle reap guard and calls no store, so a retention sweep deletes its rows on time. A row deleted or reaped then can leave an entry in a store that holds an earlier index. Nothing searches that entry while the service is not enabled, and the reconcile after enabling, or an operator's rebuild, removes it: this joins the known gap below. K3 item 3 ("an index entry never outlives its row") is read with this note as the promise of an enabled service. No earlier sentence of the record is changed. +> - **Enabling is an egress decision.** Embedding is egress (K5), so configuring an embedder is the deployment's decision to send the listed fields of its sources to that provider. The boot that first finds both, an embedder and the deployment's store, runs K7's boot pass ("What starts a rebuild") over every held source and names each one it builds. A source held since it was first loaded has nothing in the store, so it is built whole. +> - **The switch.** The switch the maintainer asked for is a setting that exists: `ai.embedder_provider`, whose default is `none`. No settings key is added. +> - **◆ Ruled: an author's save.** "An author's save is refused while the service is not enabled, at the three save doors of #37983's ruling D, with the remedy "save an embedder provider, restart, then save". The package duplicate door is not refused then." Ruling D is the maintainer's 「D 拒绝保存并说明」 (record [`7220511579`](https://github.com/objectstack-ai/objectstack/issues/37983#issuecomment-7220511579) on #37983): where no knowledge service is registered, an author's save of a `knowledge_source` is refused at each door that saves one, and the engine's own write (a package install, a seed, a migration) is not. It stands. This refusal stands beside it and draws the same line, between an author's save and the engine's write, so a shipped source still installs and is held. The three doors are `PUT /meta/:type/:name` on both transports and the MCP draft save, and they ask one predicate (`packages/metadata-core/src/knowledge-source-save-admission.ts#authoredKnowledgeSourceRefusal`). The package duplicate door is `POST /packages/:id/duplicate`, which asks that predicate for each source it copies (`packages/runtime/src/domains/packages.ts#refuseDuplicatedKnowledgeSources`). What it answers where no knowledge service is registered, and to a caller who may not search what a source indexes, is unchanged; a service that is not enabled is no reason for it to refuse. +> - **◆ Ruled 2026-11-29 (point 1): the package move-in is an author's save.** One more door asks that predicate on `main`, as a save: `POST /packages/:id/move-in`, for a package-less source it moves into a package. It is an author's save: it is refused while the service is not enabled, with the save's remedy. No door value is added for it: the predicate's doors stay `save` and `duplicate`. +> - **◆ Ruled 2026-11-29 (point 4): the refusal names the half that is missing.** This is the refusal of an author's save, at each door above that refuses one. With no embedder it is the ruled sentence, unchanged: "save an embedder provider, restart, then save". Where the deployment's store is not mounted, the refusal says so and says that the boot's log names the reason, and its remedy is "mount the deployment's knowledge store, restart, then save". With both missing it says both. +> - **◆ Ruled: the log line.** "Log level: `info` when only a shipped item mounted the service and nothing was configured; `warn` when the stack lists `requires: ['knowledge']`, the saved settings are incomplete, or the store could not be mounted. Never a boot refusal (ADR-0078 §4)." ADR-0078 §4 is the rule that the runtime seam warns and never throws. It is about this state alone: a declared capability whose provider cannot be built still fails the boot, as before. +> - **◆ Ruled: a service the host mounts.** "A knowledge service a host mounts itself in `plugins[]` is outside this note: its adapters may embed on their own (K1)." K1 leaves to the adapter whether an embedding call is made at all, so the absence of the kernel's embedder says nothing about such a composition. This note changes nothing for it. +> - **A known gap.** A deployment that was enabled, built its indexes and then boots not enabled syncs nothing while it stays so. The boot that finds it enabled again builds by what each store holds (K7), and a store that holds a current index for a source is left as it is. The record changes made in between are repaired by the next reconcile, which runs daily by default on the job service for a store that lists its documents (`packages/services/service-knowledge/src/knowledge-service-plugin.ts#scheduleReconcile`), or by an operator's rebuild (`os knowledge rebuild`). They are not repaired by the enabling boot, because nothing records which changes went unsynced: the sync state the service keeps for a source (`packages/services/service-knowledge/src/knowledge-sync-state.ts`) holds its last build and its failed syncs, and a change that was never attempted is neither. A row deleted or reaped in between is such a change (point 3 above): its entry stays in a store that holds an earlier index until that reconcile or rebuild. +> - **Alternatives not taken.** Mounting by configuration, so that an unconfigured deployment has no knowledge service. The runtime decides what it mounts from the stack and the process environment before the kernel starts, and the settings service, which it mounts, reads a saved value only once its data engine is bound at `kernel:ready`. The `ai.embedder_*` keys are also contributed by the knowledge service itself (`packages/services/service-knowledge/src/knowledge-settings-contribution.ts#contributeKnowledgeSettings`), so the setting that would mount the service could be saved only where it is already mounted. An always-on knowledge service: ruling D's item 5 keeps it out (the same record), and `packages/spec/src/kernel/platform-capabilities.ts#PLATFORM_CAPABILITY_TOKENS` states the token as "Requested, never always-on". +> - **Cloud is out of scope**, by the maintainer's word above: 「云端不需要管」. +> +> This note adds no contract member, no settings key and no capability token: the list stays closed (rules 3 and 5). It declares, and [#38369](https://github.com/objectstack-ai/objectstack/issues/38369) builds it after this note merges. Until then `main` has no such state: a mounted service with no embedder registers a stand-in whose every use is refused with the reason, and still starts its boot build, its record sync and its reconcile job and hands out its tool. The code this note cites was read on `main` at `ff69bcabb2`. The table is left as written; read item 12 with this note. + **What "capabilities" became.** #36990's rule named "capabilities" among the members that waited for this record. Two things answer it. A method that is absent is the capability signal for listing, dropping, status, and the start and end of a build: the service asks whether the method is there. One flag covers what a method cannot say, `capabilities.chunks` (item 5). No wider descriptor is added. **What counts as a member** (for rule 5 below, and for the epic's "no new adapter-contract member"). A member is anything an adapter author must read to be correct: @@ -365,6 +443,30 @@ Rules for every member: 4. **The contract carries what an adapter reports, never how it is configured.** The descriptor of item 6 is a report. Which provider, which key, how to batch, hybrid weights, rerank toggles and parser options stay in the adapter's own plugin options. 5. **The list is closed.** A member that is not in the table needs a dated note on this record first. +> **Note (2026-11-30, [#38692](https://github.com/objectstack-ai/objectstack/issues/38692)) — rule 4 above, and the "Hybrid retrieval" row of [K1](#k1--the-boundary): a knowledge source declares which retrieval legs run and the vector leg's share; the adapter reports the modes it supports, and still decides how candidates are found and how the legs are fused; a parameter of one search request is not configuration.** Decided by the maintainer on 2026-11-30: ruling record [`7270218011`](https://github.com/objectstack-ai/objectstack/issues/38692#issuecomment-7270218011) on #38692. Its first line carries his words, verbatim and untranslated: 「同意,更新决策卡」 at 2026-11-30T06:00Z, and, after an independent review of that first text, 「全部采纳,修正裁决」 at 2026-11-30T06:16Z. The text this note records is the record as revised at 06:16Z. It says what it replaces on the card, 「本评论取代原单正文第 1、2、7、8 节的写法。」, and it sums the ruling up: 「知识源可以声明检索方式(只用向量 / 只用关键词 / 混合),混合时可以设向量占比;驱动报告自己支持哪些方式和默认值。」 The record's 「驱动」 is this record's adapter, and a 「一路」 is a leg. Its section 八 lists eleven things this note must write. Each bullet below names the items it carries, and the substance is that of the record's sections 一 to 七. This note marks no ◆: it decides nothing past the record's words, and every quotation is the record's text, unchanged, but for one point the maintainer ruled after it, at 2026-11-30T07:57Z: the optional mark of `AdapterSearchOptions.retrieval`, which that member's bullet records and cites. +> +> - **Rule 4, amended (items 1 and 2).** Rule 4 says: "Which provider, which key, how to batch, hybrid weights, rerank toggles and parser options stay in the adapter's own plugin options." From the merge of this note it reads: "Which provider, which key, how to batch, rerank toggles and parser options stay in the adapter's own plugin options. Hybrid weights are declared by the knowledge source. A parameter of one search request is not configuration." The record's words for the two changes: 「K8 第 4 条:「hybrid weights」改划给知识源声明;rerank toggles、parser options 照旧留在驱动。」 and 「K8 第 4 条补一句:逐次检索的请求参数不属于「配置」。」 The rule's headline and its sentence on item 6 are unchanged: the contract carries what an adapter reports, never how it is configured. The member an adapter reports its modes by is such a report, and the record heads its section so: 「驱动契约(报告,不是配置)」. What no source ever declares is the record's section 六, 「永远不进知识源协议」: 「融合算法及其常数、重排、分数阈值、分词器。平台以后如果统一做重排,那是知识服务的配置。」 +> - **The "Hybrid retrieval" row of K1 (item 3).** The row gives the adapter "How vector and keyword scores are blended, which index or scan is used, and how candidates are found." From this note it is read as the record writes it: 「知识源声明跑哪几路、向量分量多少;驱动仍然决定怎么找候选、怎么融合。」 The source declares which legs run and how much the vector leg weighs. The adapter still decides how candidates are found and how the legs are fused. The table is left as written. +> - **The title, the D1 key-words line and TL;DR item 1 (item 4).** Each says that adapters own hybrid retrieval. The record: 「标题、D1 关键词行、TL;DR 第 1 条里「adapters own hybrid retrieval」的含义同步收窄。」 So in those three places "hybrid retrieval" means what the row means as read above: how candidates are found and how the legs are fused, and no longer which legs run or what share the vector leg has. The three texts are left as written; the D1 line is a quotation of the filing gate's record. +> - **The source keys (the record's section 一).** `source.retrieval?`, a strict object beside `source.affinity`, with two optional keys. `mode?` is `vector`, `keyword` or `hybrid`; a source that omits it is searched in the default mode of the adapter it binds to. `vectorWeight?` is a number above 0 and below 1, written only beside an explicit `mode: 'hybrid'`; omitted, the two legs weigh the same. The parse refuses a `vectorWeight` where `mode` is omitted or is `vector` or `keyword`, and an empty group reads as an omitted one: 「解析层拒绝:省略 `mode`、或 `mode` 为 `vector` / `keyword` 时写了 `vectorWeight`。`retrieval: {}` 允许,等同省略。」 Neither end of the range is a value, because a leg is switched off by `mode`: 「要关掉一路用 `mode`,所以权重不能取 0 或 1。」 The number is the vector leg's share, the direction of Weaviate's `alpha` and of RAGFlow's `vector_similarity_weight`, and the `keywordWeight` of the card's body is not used. The group stands beside `affinity`, and the two act one after the other: 「和 `source.affinity` 并列、先后作用。」 +> - **The three modes (section 一; item 11 for `keyword`).** `vector`: only the vector leg runs. `hybrid`: both legs run and are merged by the adapter's fusion algorithm. `keyword`: only the keyword leg runs, and the record fixes what that means: 「只跑关键词一路,**不调用嵌入器、不生成问题向量**;同分按段落 id 排,结果确定;问题里抽不出词就返回空。」 It is for exact lookups: 「它适合文号、条款编号这类精确查找。」 A source that wants the keyword leg to lead and the vector leg to settle the order writes `hybrid` with a low `vectorWeight`, not `keyword`: 「想要「关键词为主、向量定先后」,应写 `hybrid` 加低的向量占比。」 +> - **The member an adapter reports (item 5).** `AdapterCapabilities.retrieval?: { modes: readonly ('vector' | 'keyword' | 'hybrid')[], default: 'vector' | 'keyword' | 'hybrid' }`, on `packages/spec/src/contracts/knowledge-adapter.ts#AdapterCapabilities`, which holds `chunks` alone today. `modes` is the modes the adapter runs, and `default` is the one it runs for a source that omits `mode`. An adapter that reports `hybrid` takes `vectorWeight`, with no flag of its own: 「支持 `hybrid` 就必须支持 `vectorWeight`,不单独声明。」 `knowledge-turso` and `knowledge-pgvector` report all three, with the default `hybrid`, and the record's section 七 holds that default where it is: 「turso、pgvector 的默认**统一保持 `hybrid`**,不随探测到的档位变化。#38671 修好后重新实测,再议是否改默认。」 An adapter that does not declare the member serves only sources that omit `mode`, and `knowledge-memory` is one: 「没声明的驱动(含 memory;它不由运行时挂载):知识源只能省略 `mode`。检索报告和 Studio 显示「驱动未声明」。」 What an adapter probes in its own backend stays out of the report: 「驱动探测到的增强能力(pgvector 的 pg_bigm、HNSW 等)走驱动自己的健康检查或日志,不进这份契约。」 +> - **The member the service hands the adapter (items 2 and 5).** `AdapterSearchOptions.retrieval: { mode, vectorWeight? }`, on `packages/spec/src/contracts/knowledge-adapter.ts#AdapterSearchOptions`, written here as the record writes it. It carries the value in effect for this search, which the service resolves: 「生效值放进 `AdapterSearchOptions.retrieval: { mode, vectorWeight? }`,由服务解析后交给驱动。这是**逐次请求参数**(同 `topK`、`scope`),不是配置。」 The order it is resolved in: 「单次检索参数(第二期)> 知识源声明 > 驱动默认。」 This is the request parameter that the sentence added to rule 4 speaks of. The record's spelling carries no optional mark, and the maintainer ruled on it later that day: the member is optional, `AdapterSearchOptions.retrieval?`, as rule 2 says of every member; an adapter that declares no `capabilities.retrieval`, such as `knowledge-memory`, keeps working; and whenever the service settles a mode, it always passes it (his choice of the decision card's option 「可选(推荐)」 at 2026-11-30T07:57Z, ruling record [`7272337479`](https://github.com/objectstack-ai/objectstack/issues/38692#issuecomment-7272337479) on #38692). +> - **The suite cases the two members land with (item 5; rule 1).** In the contract test suite (`packages/services/service-knowledge/src/testing.ts#runKnowledgeAdapterContract`): 「契约测试套件加用例:三种方式各一个;权重 0.5 与现状逐位相同;不支持的方式被拒。」 +> - **`vectorWeight`: what it means, and what the two SQL stores compute (item 6).** The meaning is abstract: 「混合时向量一路的相对分量。0.5 等于驱动的等权行为;调高不会让向量一路的命中名次变差。具体公式属于驱动的现行实现,不属于字段含义(见第五节)。」 The implementation of `knowledge-turso` and `knowledge-pgvector` is a weighted reciprocal rank fusion with the constant 60. With `w` the `vectorWeight`, and `v` and `k` a passage's rank in the vector leg and in the keyword leg, the record's formula for its score is `(w/(60+v) + (1−w)/(60+k)) / (w/61 + (1−w)/61)`. The division by the best score is kept on purpose: 「**保留「除以最佳分」的写法**。改写成「乘以 61」会有大量末位差异(全组合实测 13,369 / 40,400 处)。」 A pin holds `w = 0.5` to today's function over every combination of ranks, and the tie rule does not move: 「钉子测试:全名次组合下 `w = 0.5` 与现在的 `fuse()` 逐位相等。同分规则(先比向量名次,再比段落 id)不动。」 The weight changes the TypeScript function and the mode changes the SQL: 「权重改的是 TypeScript 的 `fuse()`,`mode` 改的是 SQL(少拼一路)。」 Under a single-leg mode the passage ranked n scores `61/(60+n)`, `knowledge-memory` keeps answering the cosine similarity, and the contract asks one thing of a score: 「契约只要求同一知识源内分数随名次不增。」 The constant is not opened as an option: 「RRF 常数等引擎参数**本期不开放**为插件选项。」 Read at `5a77a7063e`: the function is `packages/plugins/knowledge-turso/src/turso-adapter.ts#fuse` and `packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts#fuse`. Each divides the sum of the two legs' `1 / (RRF_K + rank)` by `2 / (RRF_K + 1)`, with `RRF_K` at 60; a leg that does not rank a passage adds nothing; and a tie goes to the better vector rank, then to the chunk id. +> - **Two sentences of the note of 2026-11-29 (item 7).** Under K1, "◆ Why position" refuses a rank fusion that takes an `affinity` declaration as one more leg, and says of it: "a smaller weight has no unit an author can check". It also says: "a passage only one leg ranks scores at most 0.5". The record: 「回应 2026-11-29 修订里「权重没有作者能核对的单位」那句,并说明「只被一路命中最多 0.5 分」不再成立。」 On the first: `vectorWeight` weighs another thing, one retrieval leg of a source against the other, and nothing of `affinity` changes. The record does not give the key a unit. Its meaning is abstract, a relative share: 0.5 is the adapter's equal weight, and a higher value never ranks a hit of the vector leg worse. What an author is told beside the number is a direction, in the Studio form: 「向量占比稍高于 0.5,只被关键词一路找到的段落就可能进不了答案,阈值随 topK 变化」. And the key is built only once a usable range has been measured (phase 1b, below). On the second: it was true of every search of the two SQL stores when it was written, and from phase 1a it is true only of a hybrid search at equal weight. Under a single-leg mode the passage ranked first scores 1. Under `hybrid` with a declared weight, by the formula above, a passage only the vector leg ranks scores at most the weight, and a passage only the keyword leg ranks scores at most the rest. The other sentences of that note are left as written. +> - **The intended exception to "builds on every store" (item 8).** K4 makes `adapter` optional because "one source written as metadata must build on `os dev`, on a hosted environment and on PostgreSQL", and the note of 2026-11-29 says "A source is written once and builds on every store (K4)". The record names one intended exception: 「「一份知识源在每种存储上都能建」的有意例外:显式声明了存储不支持的方式会被拒。」 A source that omits `mode` is not in it: omitted means the adapter's default, whichever adapter that is. The index of a source in the exception is still built, and the next bullet lists where it is refused. +> - **Where an unsupported mode is refused (item 9).** Four points, in the record's order. (1) When an author saves, at Studio, REST and the MCP draft door: `400 VALIDATION_ERROR`, and the refusal lists the modes the adapter supports. (2) At registration, and only when the adapter can already be resolved at that moment: 「只有此刻驱动已经可以解析时才拒绝,否则不下结论(启动期驱动在 `start()` 才注册,按 AGENTS.md 的启动期注册表规则,不在 `init()` 下结论)。软件包安装不经过保存门,靠第 3、4 条兜住。」 (3) Once, when the boot has completed, after the precedent of `reportUnmountedAdapters`: a line in the log at `error` that names the source and the modes its adapter supports. (4) At every search: the source is listed in `refused` with its code, and it is never searched in the default mode in its place (「不悄悄按默认方式跑」). The index is not refused: 「方式不被支持的知识源**照常建索引**,只拒绝检索。」 Read at `5a77a7063e`: adapters register in their plugins' `start()`, after a source registered in code at `init()` (the note on `packages/services/service-knowledge/src/knowledge-service.ts#KnowledgeService.adapterIdFor`); the boot's reading of unmounted adapters is taken at `kernel:bootstrapped` (`#KnowledgeService.reportUnmountedAdapters`); and the save predicate does not judge the engine's own write, a package install among them (`packages/metadata-core/src/knowledge-source-save-admission.ts#authoredKnowledgeSourceRefusal`). +> - **Known gaps (item 10).** 「已知缺口:检索方式不同的知识源之间分数不可比;单路方式下分数只反映名次。」 The scores of two sources searched in different modes cannot be compared. Under a single-leg mode a score says the rank and nothing more, and the first hit always scores 1. The record adds this sentence to the description of `search_knowledge`: 「分数只表示同一知识源内的先后,不表示相关程度」. This note closes neither gap. The record's own line on a search that merges several sources: 「跨知识源混排:BrightRule 只有一个知识源,今天不受影响。」 +> - **The way out of a single number (item 11).** 「单个数权重的退出路径:将来真有第三路时,加按路写法,旧写法保留原意。」 One number can weigh two legs against each other. If a third leg ever exists, a per-leg spelling is added, and a `vectorWeight` already written keeps its meaning. The same item asks for the meaning of `keyword`, which is under "The three modes" above. +> - **No index is rebuilt for either key.** Neither enters the fingerprint or the recipe hash (K7), and a change of mode rebuilds nothing: 「不计入索引指纹和 recipe hash,切换方式不用重建索引。」 A source searched by vector alone keeps its keyword index (「只用向量的知识源**照常维护关键词索引**。」), and the record says the free switch depends on that. +> - **The sequence (the record's 分期).** Phase 0 is this note, which the maintainer merges. Phase 1a builds `mode` with its three values, the adapter's report, the four refusal points, the Studio form and the tool's text. Phase 1b builds `vectorWeight`, after #38671: 「**排在 #38671 修好切词之后**,修好后实测,确认权重有可用的区间。」 So `vectorWeight` is ruled here and is in no schema until that phase; K4's rule holds for both keys ("A key added later lands with its first reader"). Phase 2 is the per-search override on `search_knowledge`, and it opens `mode` only: 「`search_knowledge` 单次覆盖,只开放 `mode`。届时还要定两件事:知识源能不能声明「不许覆盖」;覆盖成混合时用哪个权重。cloud 应用内 agent 的工具定义要同步。」 +> - **Not in this note.** The texts that state today's behaviour are rewritten by the PRs whose code makes the new sentences true (K2), and the record routes them: 「`content/docs/protocol/knowledge.mdx` §7.1 的修改随代码 PR 走。`ui/`(Studio 表单)和 `skills/`(AI 作者文档)是受治理路径,各自单独提 PR。」 The per-search argument of phase 2 is not registered here. Rerank, a score threshold, a tokenizer and the fusion algorithm with its constant never enter the source (section 六, above). +> +> This note registers exactly two members, `AdapterCapabilities.retrieval` and `AdapterSearchOptions.retrieval`, and no other: the list stays closed beyond them (rules 3 and 5). It declares, and the phases above build it; the PR that lands it changes no file under `packages/`. Until phase 1a lands, `main` has no `source.retrieval` key, `AdapterCapabilities` holds `chunks` alone, and `knowledge-turso` and `knowledge-pgvector` answer every search by the equal-weight fusion of two legs. The code this note cites was read on `main` at `5a77a7063e`. The title, the tables of K1 and K8, the rules above and every earlier note are left as written; read rule 4 and the "Hybrid retrieval" row with this note. + +> **Cross-reference (2026-11-30, [#38760](https://github.com/objectstack-ai/objectstack/issues/38760)).** Rule 4 above, and the three sentences of the note of 2026-11-30 above that speak of rerank, are read with the dated note of 2026-11-30 on #38760 under "What follows from the two lists" in [K1](#k1--the-boundary), which is written on the maintainer's later words of that day. Whether a source's searches are reranked is declared by the knowledge source, so "rerank toggles" leaves the adapter's plugin options in rule 4. Of rerank, a switch enters the source and no model does. The sentence 「平台以后如果统一做重排,那是知识服务的配置。」 of the record of #38692 stands: the knowledge service reranks, with the reranker the deployment configures. That note adds no member: `IKnowledgeAdapter` and `AdapterSearchOptions` are unchanged, and the list stays closed (rules 3 and 5). No sentence of K8 or of the note above is changed. + ### K9 — One `search_knowledge` definition, and every knowledge tool goes through the tool registry and the MCP seams **What landed** (PR #36823, merged as `8aecf6d770`, read in the tree at `254e396a29`). The tool has one definition, `packages/services/service-knowledge/src/knowledge-tools.ts#getKnowledgeToolDefinitions`, and one executor, bound by `packages/services/service-knowledge/src/knowledge-tools.ts#createKnowledgeTools`. The knowledge service hands both out through `knowledgeTools()`. Both MCP transports register that definition and call that executor as the principal they bind, where the grant admits `data:read` (`packages/mcp/src/mcp-http-tools.ts#registerKnowledgeTools`; the HTTP bridge in `packages/runtime/src/domains/mcp.ts`, the stdio bridge in `packages/mcp/src/stdio-data-bridge.ts`). diff --git a/docs/adr/0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md b/docs/adr/0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md index 9e7c7481736..7396a76ce26 100644 --- a/docs/adr/0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md +++ b/docs/adr/0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md @@ -1,6 +1,6 @@ # ADR-0162: An object declares its closed states — in them the record and its master-detail lines are closed to change for every caller, a closed record is not deleted, and one lock read answers for pending approvals and for closed states -**Status**: Proposed — 2026-11-26, written for objectstack#36253 on the maintainer's ruling of 2026-11-22 (ruling record [`7073676422`](https://github.com/objectstack-ai/objectstack/issues/32004#issuecomment-7073676422), item ② = C). `docs/adr/**` is Tier H (Prime Directive #14): this record becomes **Accepted** by an authorized approval or the maintainer's merge of the PR that carries it, and is in force from that merge. **This record declares; it implements nothing** — no schema key, no engine code, no route, no changeset; every mechanism below lands through a build card ([Execution](#execution-after-acceptance)). **Five points go past the ruling's words**; each is marked ▲ where it stands and all five are listed in [Points the ruling does not settle](#points-the-ruling-does-not-settle). The maintainer ruled on four of them on 2026-11-26 (ruling record [`7200732942`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7200732942)): each stands as written, and item ③ of the same batch is scoped to `readonlyWhen`. A second ruling the same day (ruling record [`7201405662`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7201405662)) adds one platform rule: an abandoned approval never writes a closed value ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). A third ruling the same day (ruling record [`7205949718`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7205949718)) settles the fifth point, in [D5](#d5--who-is-bound-every-caller-a-system-context-is-not): the platform refuses the configuration that would leave a document reading a decision its approval did not finish. **Revised 2026-11-27** on two further rulings of the maintainer, made that day on the design of [Execution](#execution-after-acceptance) item 8 (ruling record [`7210179412`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7210179412)): on a field the object closes on at an approval's outcome, each step's decision is written only when the approval is over for the record, and on an object that declares `closedStates` a document is held through every approval ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). After the contract review of the revision the seat read both rulings by their words (seat rulings [`7211509661`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211509661) and [`7211531658`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211531658)). The revision implements nothing either. +**Status**: Proposed — 2026-11-26, written for objectstack#36253 on the maintainer's ruling of 2026-11-22 (ruling record [`7073676422`](https://github.com/objectstack-ai/objectstack/issues/32004#issuecomment-7073676422), item ② = C). `docs/adr/**` is Tier H (Prime Directive #14): this record becomes **Accepted** by an authorized approval or the maintainer's merge of the PR that carries it, and is in force from that merge. **This record declares; it implements nothing** — no schema key, no engine code, no route, no changeset; every mechanism below lands through a build card ([Execution](#execution-after-acceptance)). **Five points go past the ruling's words**; each is marked ▲ where it stands and all five are listed in [Points the ruling does not settle](#points-the-ruling-does-not-settle). The maintainer ruled on four of them on 2026-11-26 (ruling record [`7200732942`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7200732942)): each stands as written, and item ③ of the same batch is scoped to `readonlyWhen`. A second ruling the same day (ruling record [`7201405662`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7201405662)) adds one platform rule: an abandoned approval never writes a closed value ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). A third ruling the same day (ruling record [`7205949718`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7205949718)) settles the fifth point, in [D5](#d5--who-is-bound-every-caller-a-system-context-is-not): the platform refuses the configuration that would leave a document reading a decision its approval did not finish. **Revised 2026-11-27** on two further rulings of the maintainer, made that day on the design of [Execution](#execution-after-acceptance) item 8 (ruling record [`7210179412`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7210179412)): on a field the object closes on at an approval's outcome, each step's decision is written only when the approval is over for the record, and on an object that declares `closedStates` a document is held through every approval ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). After the contract review of the revision the seat read both rulings by their words (seat rulings [`7211509661`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211509661) and [`7211531658`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211531658)). The revision implements nothing either. · **Amended** (2026-11-29, option D on [#37766](https://github.com/objectstack-ai/objectstack/issues/37766), ruling record [`7253749311`](https://github.com/objectstack-ai/objectstack/issues/37766#issuecomment-7253749311), maintainer 「D 统一校验,各入口都拒绝」): where a flow or an object is authored, the conditions an approval opens on are refused at every authoring door, and no longer only reported. One dated note under [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) says how four passages of this record read after that ruling, and marks what in the note is not in the ruling's words. The refusal at the first request stays the rule, and the four passages are left as written. · **Revised again** (2026-11-29, on three rulings the maintainer made that day on the build of [Execution](#execution-after-acceptance) item 8, ruling records [`7256254988`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7256254988) and [`7257388557`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7257388557), 「审批插件自己记下结论」, 「一小时后退回重提并通知」 and 「满一小时后结果通知一起写」): the approvals plugin keeps on the approval's own rows what it read of the approval's runs, and past an age bound a run that can no longer be read, or that never went on from the last decision, has stopped at the step last decided. Within the bound nothing is written for such a run, at the approval's last step as at every other. The revision was completed on 2026-11-30, when the build of item 8 had been reviewed. It adds one ruling of that day (ruling record [`7268216330`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7268216330), 「A 维持现状,只写进文档」), by which a step log that has lost whole steps is read as it was kept, and the seat's readings that the build was reviewed on, each named as the seat's where it stands: which runs with no row are placed, two more states that are read as a run that cannot be read, and that a run is read as stopped only once two judgements in a row read it so, which makes the hour an hour and one pass of the reconciler more where no judgement read the approval within it. The reconciler's part of item 8, one passage of [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) and one sentence of [Consequences](#consequences) are revised where they stand, and nothing else is. One sentence of item 8 was false and is replaced: a process that dies while it advances a run leaves no row of that run behind, and not a history that says paused. - **Date**: 2026-11-26 - **Card**: [#36253](https://github.com/objectstack-ai/objectstack/issues/36253) (p2, `area:data`). Its rule, as the card carries it: @@ -202,7 +202,7 @@ The rule concerns a mirror field on which the object closes on `approved` or on A document under an approval of three steps therefore reads `pending` from its submission until the last step is decided and the flow behind that decision has run, and then reads `approved`, and is closed where the object closes on that value. On `main` it reads `approved` after each step. Where its second step rejects it, it reads `pending` until the flow behind the rejection has run, and then `rejected`. -**How the plugin learns that an approval is over.** At the decision it cannot know whether another step follows, which is why this record first turned the rule down. After it has resumed the run it can find out: it reads the run that carries the record, and asks its own table for a request of the approval on the record. It does so at every door that resumes or cancels a run of an approval: a decision, by a person or by the platform's own clock, a send-back, a resubmission, a recall, and the continuation of a restored run. It does not take the resume's own answer for it. That answer is for the request's own run. A child run that completes resumes its parent inside the same call, and the door is told of the parent's failure only where the parent's resume answered `stranded`; a parent that was cancelled, a store that could not be read and a resume that another process holds each end in a line of the log (`packages/services/service-automation/src/engine.ts#bubbleToParent`). Where the door cannot tell, because another process is advancing the run or the run cannot be read, it writes nothing. A decision leaves a mark on its request, a field the store can filter on, and a reconciler judges every marked request the door did not: after a process that died, after a run that was cancelled, after a parent run that is gone. The mark says that what follows the decision has not been judged yet. Every decision of an approval on an object that declares `closedStates` leaves it, also where the decision is written at once, because the hold, below, is read off it. [Execution](#execution-after-acceptance) item 8 has the means. The reconciler is what ends an approval that nobody is at the door for, so an approval on an object that declares `closedStates` opens only on a host that runs one, below. +**How the plugin learns that an approval is over.** At the decision it cannot know whether another step follows, which is why this record first turned the rule down. After it has resumed the run it can find out: it reads the run that carries the record, and asks its own table for a request of the approval on the record. It does so at every door that resumes or cancels a run of an approval: a decision, by a person or by the platform's own clock, a send-back, a resubmission, a recall, and the continuation of a restored run. It does not take the resume's own answer for it. That answer is for the request's own run. A child run that completes resumes its parent inside the same call, and the door is told of the parent's failure only where the parent's resume answered `stranded`; a parent that was cancelled, a store that could not be read and a resume that another process holds each end in a line of the log (`packages/services/service-automation/src/engine.ts#bubbleToParent`). Where the door cannot tell, because another process is advancing the run or the run cannot be read, it writes nothing. A decision leaves a mark on its request, a field the store can filter on, and a reconciler judges every marked request the door did not: after a process that died, after a run that was cancelled, after a parent run that is gone, after a run whose history is gone or does not name every run it started, after a decision whose run never went on, and after a tree of more runs than it can read in full. For a run it can no longer follow, three rulings of 2026-11-29 give the rule. The first two are in ruling record [`7256254988`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7256254988). The maintainer chose on two decision cards, verbatim and untranslated. On 「审批的流程运行记录被清理或读不到时,单据怎么判?」, how a document is judged when the run records of its approval were cleaned up or cannot be read: 「审批插件自己记下结论」, the approvals plugin records the conclusion itself. On 「决定已记下但流程没接着走(服务中断),单据怎么处理?」, what becomes of a document whose decision is recorded while its flow did not go on, in an outage: 「一小时后退回重提并通知」, after one hour it is put back to be submitted again, and a notice is sent. As the ruling record states them: the plugin keeps what it read. At each door, and as each request opens, it records on the approval's own rows what the runs it could read showed, which is whether the approval has, so far, a failure between two steps that no later request answered. A later judgement does not read those runs again, so a history that was trimmed and a process that died do not leave a document on `pending`. A run the plugin never read is placed by the step last decided, and that placement and the second ruling are one rule: past an age bound, with no request of the approval open on the record, a run that cannot be read, or that is still parked at the node of the request last decided, has stopped at that step. Where a step can follow the step it stopped at, the approval ended between two steps and is abandoned, as the bullet on a run that ends between two steps has it, below, and a run that is still parked is cancelled. Where none can, the approval has finished, and where the run never went on from that last decision the administrators are told. The third ruling is in ruling record [`7257388557`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7257388557), and it settles what the first two leave open at the approval's last step: when the outcome is written, and whether the administrators are told where the run cannot be read. The maintainer chose on one decision card, verbatim and untranslated. On 「最后一步已批准但流程没接着走时,审批结果什么时候写到单据上?」, when the outcome of the approval is written to the document where the last step was approved and the flow did not go on: 「满一小时后结果通知一起写」, once the full hour has passed the outcome and the notice are written together. As that record states it: nothing is written for such a run within the bound, at the last step as at every other. Once the bound has passed, the outcome and the administrators' notice are written in one stroke, and the notice also covers a last step whose run has no row. It is one rule, with no special case for the last step. For this record that means: a run that has not left the node of a decided request has not gone on from the decision, and within the bound it is not read as parked at a pause that no step can follow, above. Four things stand beside the three rulings, and [Execution](#execution-after-acceptance) item 8 carries each where it applies. One is a ruling of 2026-11-30, in ruling record [`7268216330`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7268216330). The maintainer chose, verbatim and untranslated, 「A 维持现状,只写进文档」, A, keep what is built and only write it into the documentation: a step log that has lost whole steps carries no mark of it, the plugin reads what the log kept, and that is a stated limit of this release. The other three are the seat's, and none is a ruling. The seat reads "a run the plugin never read", in the first ruling, as a run that no run the plugin read speaks for: a run with no row counts as passed where a run the plugin read went on past the step that names it, and going on along a failure route is not going on past the step (seat reading [`7257555103`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7257555103), which ruling record [`7257604888`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7257604888) lists for the rebuild). The seat reads as runs that cannot be read a run whose step log does not name every child run it started (seat ruling [`7258590209`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7258590209)) and a tree of more runs than the judgements can read in full (the seat's note [`7269166540`](https://github.com/objectstack-ai/objectstack/pull/38634#issuecomment-7269166540) on the review of item 8's build). And the seat has a run read as stopped, past the bound, only once two judgements in a row read it in the same state, because the hour runs from the mark and a run that is being resumed reads as a run that stopped does (the same note, on a finding of review [`7269135624`](https://github.com/objectstack-ai/objectstack/pull/38634#issuecomment-7269135624)). The order changes when an end the rulings give comes, and not which end it is. The option the maintainer chose in the third ruling read 「一条规则、不分最后一步;这种少见情况单据最多显示审批中一小时,之后结果和管理员通知一起落。读不到运行记录的最后一步也通知。」: one rule, with no special case for the last step; in this rare case the document shows in approval for at most one hour, and after it the outcome and the administrators' notice land together; a last step whose run records cannot be read is notified as well. The hour holds wherever a judgement read the approval's state within it. Where none did, it is the hour and one pass of the reconciler more, which is one sweep interval, five minutes by default, and more only in the cases item 8 names. That holds for every marked approval, one that holds a decision back included, and nothing is written early. The reading is the seat's and asks no new ruling (seat note [`7270603869`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7270603869), whose third line the seat's correction [`7272498941`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7272498941) replaces: the note first gave the pass more only to approvals that hold nothing back). The mark says that what follows the decision has not been judged yet. Every decision of an approval on an object that declares `closedStates` leaves it, also where the decision is written at once, because the hold, below, is read off it. [Execution](#execution-after-acceptance) item 8 has the means. The reconciler is what ends an approval that nobody is at the door for, so an approval on an object that declares `closedStates` opens only on a host that runs one, below. **On an object that declares `closedStates`, a document under approval is held for the whole of the approval.** Ruled 2026-11-27 at 04:50Z (the same ruling record): 「随新能力一起全程锁」, locked the whole way, and shipped with the new capability. The ruling record states the rule: 「只对声明了 `closedStates` 的对象,从提交到审批结束都锁住,随键一起发布。」, only on objects that declare `closedStates`: held from the submission to the end of the approval, and shipped with the key. The option the maintainer read says 「只对声明了关闭状态的对象,从提交到审批结束别人都改不了」: only on objects that declare closed states, from the submission to the end of the approval nobody else can change the document. The seat reads those words as they stand (seat ruling [`7211509661`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211509661)), and the hold below is that reading. @@ -241,6 +241,29 @@ An approval none of whose steps mirrors onto a field the object closes on is ask **The approval is judged whole, once, at its first request.** That is the first point at which the objects and the flows are certainly all in hand: they are published apart, and any of them can change after the others. The node reads the approval from its definition: every approval step of the flow the record's run was started on, and of every flow that a `subflow` or a `map` in it names, to any depth. It judges each step on that step's own mirror field and on each object the step can act on: the object of the run's record, and under a `map` the object that node names for its items as well. Every step has therefore been judged before the first request is written, one that opens later on another record or another object too. A first step that names no mirror field does not open the approval unjudged: where another step that can act on the same object is one the conditions concern, the approval is refused for the step that names none. A later request of the same approval is not judged again: refusing it would end the approval between two steps, after steps that were already decided. A request that the plugin cannot place as first or later is not judged either, for the same reason, below. Where a part of the approval cannot be read ahead, a flow that a node names and the plugin cannot read, the approval cannot be judged, and its first request is refused. The same conditions are reported where a flow or an object is authored, wherever the parts are in view together; that report is early notice, and the refusal at the first request is the rule. The rule holds for an approval of one step as for one of several, since a single step fails too, on a decided document that is sent for approval again. In an application where no object declares the key, nothing is read and no approval is refused. +> **Note (2026-11-29, ruling record [`7253749311`](https://github.com/objectstack-ai/objectstack/issues/37766#issuecomment-7253749311) on [#37766](https://github.com/objectstack-ai/objectstack/issues/37766), option D) — where a flow or an object is authored, the conditions are refused at every authoring door, and no longer only reported.** Card #37766 builds [Execution](#execution-after-acceptance) item 7. One item of it asked what an author is told before the first request: an error, or only a notice. The seat put that to the maintainer as a choice, and the maintainer chose the option that reads, verbatim and untranslated, 「D 统一校验,各入口都拒绝」, D: one check, and every door refuses. The line under that option, as the maintainer read it, reads in full 「写文件的项目在校验和构建时、设计器和 AI 在发布时都报错并说明缺什么。现有草稿 PR 的入口部分作废,重做一个 PR;您批一条决策记录修订。」: a project written in files gets an error at validate and at build, and the designer and an AI author get one at publish, each error saying what is missing; the door half of the draft PR is set aside and the work is redone as one PR; the maintainer approves one amendment of a decision record. As the ruling record states it: at authoring the gap is an error, and a notice alone is not the answer; the refusal is made at every authoring door, from one check in the platform's shared rule table; this record is amended by one dated note, and [ADR-0094](./0094-sys-permission-set-pure-projection.md) is not amended. This note is that amendment. +> +> Four passages of this record are read with this note, and each is left as written. +> +> - **The paragraph above**: "The same conditions are reported where a flow or an object is authored, wherever the parts are in view together; that report is early notice, and the refusal at the first request is the rule." For "reported" read "refused", and for "that report is early notice" read "that refusal comes early". The rest of the sentence stands. +> - **[Execution](#execution-after-acceptance) item 7, the check**: "The same conditions are reported at authoring wherever the parts are in view together." For "reported" read "refused". +> - **[Points the ruling does not settle](#points-the-ruling-does-not-settle), the list under the third ruling of 2026-11-26**: "the refusal is made when an approval opens and reported at authoring, and is not made at publish, where the option's words allow either". Read: the refusal is made when an approval opens, and at authoring too, publish included. Not refusing at publish was this record's choice inside that ruling, and the ruling of 2026-11-29 replaces it. The other points of the list are untouched. +> - **[Alternatives considered](#alternatives-considered)**: "Refuse the configuration only where the object or the flow is published." It stays not chosen as the rule, for the reason the entry gives: a publish check sees the pair only some of the time. For its last sentence, "It is kept as early notice.", read: it is kept as a refusal beside the rule. +> +> The rest of this note is not in the maintainer's words. The ruling record lists each point below as carried from the decision analysis ([`7252928345`](https://github.com/objectstack-ai/objectstack/issues/37766#issuecomment-7252928345)) or as not ruled. They are the seat's proposals, built in the change that carries this note, for the maintainer to accept with it or strike. +> +> - **The first request stays the rule** (carried from the analysis). The refusal at authoring is added to it and replaces nothing. An authoring door has the parts of an approval in view only some of the time, and the first request has them all. +> - **One judge** (carried from the analysis; where it lives is the seat's choice). The first request and the rule ask the same code (`packages/metadata-core/src/approval-opening.ts#judgeApprovalOpening`, `#judgeApprovalOpeningSync`): the first request through the entry that awaits each flow it reads, the rule through the entry that reads a stack in hand. Both entries drive one walk of the approval's flows and one judging function, so the conditions are written once. The two verdicts can still differ, because the two doors do not have the same things in view: the last point below says where. +> - **Released with the key** (carried from the analysis). The refusal at authoring is part of item 7's check and is released as item 7 is: the release that first publishes `closedStates` carries it. +> - **The rule** (the seat's). `validateApprovalClosedStates` (`packages/lint/src/validate-approval-closed-states.ts#validateApprovalClosedStates`) reports the finding `approval-closed-state-gap` at severity `error`. It is a member of the reference-integrity suite (`packages/lint/src/reference-integrity-suite.ts#REFERENCE_INTEGRITY_RULES`), which is one entry of the shared author-time rule table (`packages/lint/src/authoring-rules.ts#AUTHORING_RULES`), so `os validate`, `os build` and `os lint` run it over a project's stack. The approvals plugin registers no gate of its own, and the authoring-gate seam that ADR-0094 records gains no member. +> - **The runtime publish door** (the seat's). The write path behind Studio, REST `/meta` and MCP runs the rule on a `flow` write and on an `object` write: at an active save, at a draft's promotion, at a restore, and for each draft of a package publish. It refuses with `INVALID_METADATA` (422), a code that door already gives. A draft is not refused, because no rule of the table refuses a draft there. On an `object` write the door judges the live flows of the written object's package against the written object, and charges the write only with a gap it adds: a gap the stored universe already holds is not that write's. In a package publish each draft is judged against the batch's objects, and a flow the batch redrafts is judged as its draft, at its own write. A package that declares `closedStates` and repairs its flow in one publish therefore passes, and one that declares it without repairing the live flow is refused (`packages/plugins/plugin-approvals/src/approval-closed-states-37766.integration.test.ts`). +> - **What an authoring door does not judge** (the seat's). At authoring there is no run. The first request judges on the object its root run was started on. The rule reads an object off the flow's definition instead (`packages/lint/src/validate-approval-closed-states.ts#approvalRootObjectsOf`): the `start` node's object where the flow declares one, and only where it declares none, the object of each start input that is a record, each read as a record the flow can be started on. It judges each flow in view as the root of an approval, on the objects so read. A door refuses only for what it has in view, and not for the following. The first request has each of them in hand and judges it: +> - a run on a record of an object the rule did not read: a flow that declares no object, neither a `start` object nor a record input, and is started by an action or by name on a record, is judged at authoring with no object for the run's record; and a flow that declares only record inputs can be started on a record of another object, on which the first request then judges; +> - a flow that is not in view: one that a `subflow` or a `map` names and the stack does not hold; on a `flow` write at the runtime door, every flow but the written one, the flows it calls and the flows that call it included; on an `object` write, every flow of another package; +> - a pause by a node whose type the spec does not list as pausing (`packages/spec/src/automation/flow.zod.ts#FLOW_PAUSE_CAPABLE_NODE_TYPES`, a `wait` and a `screen` among them): at every authoring door, the runtime door included, such a node counts as one that does not pause, a plugin's type too, because the rule is handed none of the engine's descriptors; +> - the host's `job` service, which is a fact of the deployment and not of what is authored; +> - an object that is not in view. + **What the conditions do not reach.** The platform reads ahead what can be read: a field's options, with the `visibleWhen` of those the mirror writes for a request's status, and its `readonlyWhen`; an object's closed values; the one move of a `state_machine` rule that a lock depends on; and the nodes of the approval's flows, with each step's mirror field, every node that pauses, and every `map` that holds an approval step. An author who puts a `state_machine` rule on the mirror field owes the mirror its other moves as well, from one status to the next and out of `pending` and `returned` when a request is abandoned. A move the rule refuses leaves the field on the status it holds, which is then an open one, and it is a refused write of the mirror like any other, below. Four things cannot be read ahead. When this record was merged, each of them could leave a record on an earlier step's outcome, closed, with its approval unfinished. For the first three it fixed what must hold, that the record is not left closed on a value its own approval wrote, and left the means to a card of its own ([Execution](#execution-after-acceptance), item 8). The ruling of 2026-11-27 meets that bound for the three at its root: the outcome is not on the record before the approval is over, so none of them can leave it there. What each leaves in its place is stated here, as the seat ruled it on that card's design note (ruling record [`7210179412`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7210179412)). The key is still not released before that card is built. - **A rule or a hook of the app's own that refuses a write of the mirror.** A rule of another kind than `state_machine`, or a hook, can turn on the record's data, so no reading of a definition shows what it will do. A `visibleWhen` on an option that is not a request's status can refuse a value the mirror puts back, and it is held to the same. On `main` every such refusal is logged and swallowed, on every write of the mirror. On a field the object closes on at `approved` or `rejected` none is swallowed, and what follows depends on the write. @@ -397,7 +420,7 @@ Nothing below starts before this record is Accepted. The seat files the cards; t 8. **The status mirror on a closing field: the outcome when the approval is over, an approval that does not finish, and the hold.** The child card the recommendations adopted on 2026-11-26 give the mirror's failed write ([`7202242844`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7202242844)), filed as [#37767](https://github.com/objectstack-ai/objectstack/issues/37767). When this record was merged, [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) fixed what the card delivers and left it the means: on a field the object closes on, nothing leaves a record closed on a value its own approval wrote and did not finish. The card's design note set the means out, the maintainer ruled its two questions on 2026-11-27, and the seat ruled the rest (ruling record [`7210179412`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7210179412)). [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) now states the rules, and the parts below are their scope. The parts on a refused write and on the outcome are kept to an approval the conditions concern. The mark, the reconciler and the hold reach every approval on an object that declares `closedStates` (seat ruling [`7211531658`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211531658)). An object that declares no closed value behaves as it does today. Item 1 waits for all of them, the hold included: the key is not released before this item is built. The seat files it as one card or as several. - **No refused write is swallowed.** On a field the object closes on at `approved` or `rejected`, a write of the mirror that a rule or a hook of the app refuses, or a `visibleWhen` on an option, is reported: an `error` line in the log, a line with no actor on the request's timeline, and a notice to the organization's administrators. A refused `pending` at an approval's first request refuses the opening. The request's row is written first and the `pending` second, and on a refusal the row is voided as `cancelled`; the other order could leave a decided document on `pending` with no request. Its tests pin, for each transition of a request, the value the field keeps when the write is refused. - **The outcome when the approval is over.** On a field the object closes on at `approved` or `rejected`, every step's decision is held back, whichever of the two the object closes on. A decided request carries a mark: one new field of the request, which the store can filter on, set in the update that records the decision and cleared when the approval has been judged (`Clause-②: yes`). The mark is set at every decision of an approval on an object that declares `closedStates`, also where nothing is held back, because the hold is read off it. After every resume, and after the resume or the cancel a recall makes, the door reads the run that carries the record and asks its own table for a request of the approval on the record. It has four answers. Finished: it writes the decision of the approval's latest request on the record, where that request was decided. In progress: it writes nothing. Ended between two steps: it abandons the approval as [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) says, puts the field back by item 7's order, marks the approval abandoned on the request, and leaves a line with no actor. Cannot tell yet, for a run another process is advancing or one it cannot read: it writes nothing and leaves the mark. In an approval that holds nothing back, the first and the third answer both end the hold: the mark is cleared and nothing is written. The door places a stop or a pause against the set item 7 stamps. It reads the run's step log for a failure the flow routed, and keeps a durable note on the approval's latest request where a later step could not open, so that the judgement does not depend on how that failure was routed. The door that continues a restored run refuses an approval marked abandoned, and tells the operator to cancel the restored run. A recall, an override and the dead-run sweep clear the mark on the approval's earlier requests. Its tests include: a first step approved, a second recalled, and a run that then completes, after which no `approved` is written; the same for a returned request that is recalled in its revise window; a second step that rejects on an object that closes on `approved` alone, and a first step that approves on an object that closes on `rejected` alone, in each of which the field keeps `pending` until the approval is over; a `wait` after the last step, where the outcome is written as the run parks; a node that fails after the last step, where the outcome stands; an item of a `map` that is a record, whose outcome does not wait for the later items and is not undone by a later item's failure; a next step that fails to open, on an empty slate and on a request of another approval already pending on the record, where the field keeps that approval's `pending`; a later step that fails to open with a `fault` edge to an end, which is abandoned, and with a `fault` edge to a second step that opens, which is in progress; another node that fails between two steps with a `fault` edge to an end, which is abandoned; and that node's failure handled in a `try_catch` region, after which a gateway ends the flow, which is finished. - - **The reconciler.** For an approval on an object that declares `closedStates` it takes the place of the reader of stranded requests (`packages/plugins/plugin-approvals/src/approval-service.ts#inspectStrandedRequests`). It scans the mark, oldest first, so that its scan is bounded, and judges each marked request as the door would have. It places three states that reader skips today: a cancelled run; a run whose history says paused while its pause is gone, which a process that died in a passage leaves for good; and a run still parked at a `subflow` or a `map` whose child has ended, which nothing will resume. The last two need an age bound, which the build chooses and states. It writes in the name of the request's recorded decider, as the door would have: a write with no actor would leave a flow that reacts to the change, and runs as the user, without an identity. It tries a refused outcome or put-back again while the mark stands, and sends the administrators' notice. Where nothing was held back it clears the mark and writes nothing. For a record that was deleted it clears the mark and writes nothing, and it neither tries again nor notifies. On a host with no `job` service the first request of every approval on an object that declares `closedStates` is refused, with an error that says what is missing, also where the approval's field closes on nothing. Its tests include a parent run that is cancelled while its child's request is pending; a process that dies between a decision and the write of its outcome; an approval whose field the object does not close on, whose hold the reconciler ends; a host with no `job` service, on which such an approval is refused as well; and a record deleted in a passage, whose mark is cleared once. + - **The reconciler.** For an approval on an object that declares `closedStates` it takes the place of the reader of stranded requests (`packages/plugins/plugin-approvals/src/approval-service.ts#inspectStrandedRequests`). It scans the mark, oldest first, so that its scan is bounded, and judges each marked request as the door would have. It places seven states. That reader places none of them: it reports a run that has no row and changes nothing, and it passes over a run that was cancelled or is paused. The seven are a cancelled run; a run whose history says paused while its pause is gone; a run that has no row at all, where no run the plugin read speaks for it; a run still parked at a `subflow` or a `map` on a child run that will not resume it; a run still parked at the node of the request last decided, whose decision is recorded and which never went on; a run whose step log is cut, so that it does not name every child run the run started; and a tree of more runs than the judgements can read in full. The list was revised on 2026-11-29, on the maintainer's three rulings of that day (ruling records [`7256254988`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7256254988) and [`7257388557`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7257388557), stated in [D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). It had three states, the first, the second and the fourth, and it said of the second that a process that died in a passage leaves it for good. That is not so. A resume takes the pause away before it runs anything behind it (`packages/services/service-automation/src/run-resume.ts#resumeInternal`), and the history keeps a lasting row only for a run that has ended (`packages/services/service-automation/src/run-history.ts#recordLog`). Only a process whose own memory still holds the run's paused entry reads the second state. After a restart, and in a process that never held the run, a run that a process died advancing has no row at all (`#getRun`), which is the third state, and a run that ended is in it too once the history has trimmed its row (`packages/services/service-automation/src/suspended-run-store.ts#DEFAULT_MAX_TERMINAL_RUNS_PER_FLOW`). Both were read on the trunk at `37e97a8366`. The sixth and the seventh state were added on 2026-11-30, when the build of this item had been reviewed, with the readings of the other states that follow. Each is given to the record it comes from, and those that are the seat's are not rulings. A run with no row is in the third state only where no run the plugin read speaks for it. Where a run the plugin read went on past the step that names such a run, the run counts as passed at that step and is not placed: it is kept as ended, and the approval is judged by its other runs, at the door or within the bound, with no notice. A run went on past a step where the step succeeded and the run then reached an end of its flow, or logged a later step and is not parked at that step. A step that failed is never passed, also where the flow routed its failure and went on. A run whose step log is cut speaks for no run, and a run the plugin had read to its end over a child run it had not read is not passed once its own row is gone, because nothing names that child any more. That a run the plugin read speaks for the child runs it went on past is the seat's reading of the first ruling, and not a ruling (seat reading [`7257555103`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7257555103), its second point), and that going on along a failure route is not going on past the step is the pin with which ruling record [`7257604888`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7257604888) lists the reading for the rebuild. What going on past a step means in a run's log, and the two bounds on a cut log and on a run whose own row is gone, are the build's, and each narrows the reading toward the ruling's own rule. [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) keeps the ruling record's sentence on a run the plugin never read, and the reading says which runs those are. The fourth state is a run parked on a child run that has ended, that has no row, or that has itself stopped in the second or the fourth state. It covers a `map` whose items are records. An item run of such a `map` carries another record, and its steps are that record's own approval, so the plugin reads none of them: it reads only whether the item run has ended, which it has once it is in a terminal status. [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) leaves no `map` with an approval step in its body in an approval the conditions concern, unless none of its items is a record, and no other pause between two steps of one. So a run parked at a `map` on an item run that carries another record belongs to an approval that holds nothing back. The sixth state is a run whose step log is cut. Two logs are read so. One has a step that carries the engine's mark `childRunIdsTruncated`: the step started more child runs than the 200 a step names, or the history row shed the step's list to fit its size. The other is the log of a run that has ended whose history row cannot be shown to keep every step the run logged: it keeps fewer than the run's summary counts, or the summary gives nothing to compare. The child runs such a log does name are still read, and it speaks for none of them. The seat ruled the state (seat ruling [`7258590209`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7258590209)): within the bound the plugin cannot tell, and past it the approval is placed by the step last decided, with the notice at a last step. One limit stands beside it, by the maintainer's ruling of 2026-11-30 (ruling record [`7268216330`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7268216330), stated in [D5](#d5--who-is-bound-every-caller-a-system-context-is-not)): a log that loses whole steps carries no mark. The engine keeps 200 steps of a longer log, and nothing tells the plugin which steps that compaction dropped, so it reads what the log kept, and a child run named only by a dropped step reads as one the run went past. A failure between two steps in such a child run is then not seen, and the approval can be written as finished with no notice. That is a stated limit of this release, and no engine change follows from the ruling. A history row that was halved over its size cap, or stored as null, is still told from the run's summary and is read as cut (the seat's line on that ruling, in its note [`7269166540`](https://github.com/objectstack-ai/objectstack/pull/38634#issuecomment-7269166540) on the review of the build). The seventh state is a tree of more runs than the judgements can read in full. One judgement reads at most 200 runs beside those the plugin keeps as read to their end, and the next judgement reads on from what was kept. Within the bound the plugin cannot tell of a tree it has not read to its end. Past the bound a judgement reads on only while it keeps a run the approval had not kept, and the kept list holds 200 runs, so at most 200 judgements read on. The one that keeps no further run cannot finish the tree, and the approval is placed by the step last decided, as one whose run the plugin never read. The seat accepted that rule with its two costs (the same note, under seat ruling `7258590209`). A tree the judgements cannot finish is placed without having been read in full, and a tree of about 399 runs can already be one, because a judgement reads the runs it starts from before the runs below them. And the placement follows from the shape of the flow, so an approval submitted again on the same flow can meet the same end. The last six states need an age bound. The build chooses it and states it, and it chose one hour from the mark, the hour the maintainer's choices name: every mark the approval carries has stood that long. Within the bound the reconciler writes nothing for them and leaves the mark, as the door does, because the run may still be going on in another process. That holds at the approval's last step as at every other, which the third ruling settles. The read tells a run with no row from a store that did not answer, and where the store did not answer nothing is written at any age. Past the bound, with no request of the approval open on the record, each of the six is read as a run that has stopped once two judgements in a row have read it in the same state: the same state of the same run, and for a run parked on a child run, the same child. One reading does not show it. The hour is counted from the mark and not from the run's last movement. A run the engine is resuming reads as the second state or as the third, for the reason given above, and a run whose child run has just ended reads as the fourth until the engine resumes it. An approval whose flow waits between two steps for longer than the hour, as its author meant it to, would be read as stopped in the first instant of its next resume. The state a resume leaves is gone when the resume is done, and the state a dead process left reads the same again. So every judgement keeps the states it read on the approval's own rows, in place of those kept before, a door's judgement and one within the bound included; a door that leaves a request open keeps none, because a run parked at the step of an open request has not stopped; and the judgement that reads a state for the first time writes nothing on the record. This is the seat's order on the review of the build, and not a ruling (review [`7269135624`](https://github.com/objectstack-ai/objectstack/pull/38634#issuecomment-7269135624) raised it, the seat's note [`7269166540`](https://github.com/objectstack-ai/objectstack/pull/38634#issuecomment-7269166540) ordered it, and review [`7270552441`](https://github.com/objectstack-ai/objectstack/pull/38634#issuecomment-7270552441) read it as built). Only an approval that holds nothing back can wait so: [D5](#d5--who-is-bound-every-caller-a-system-context-is-not)'s condition that no flow of the approval pauses between two steps refuses a `wait`, a `map` over records that are approved one by one, and a child run that pauses there, in every approval the conditions concern. A placement in an approval that holds nothing back ends the hold and writes nothing. What the rule leaves is two judgements in a row that each fall inside a resume of the same run, one resume or two, and that is the engine's to end, by reporting a run it is advancing (card [#38708](https://github.com/objectstack-ai/objectstack/issues/38708)). A reading that could not be kept leaves on the request the reading kept before it, and the next judgement stands on that one; where none was kept nothing is placed, so an approval whose reading is never kept is held with no end, as one whose store does not answer is. The hour of the maintainer's choices therefore holds wherever a judgement, a door's or the reconciler's, read the state within it: the first pass after the hour places the run. Where none did, that pass reads the state and keeps it, and the pass after it places the run, which is one pass of the reconciler more. A pass comes once in each sweep interval, which is five minutes by default (`packages/plugins/plugin-approvals/src/approval-service.ts#ESCALATION_SCAN_INTERVAL_MS`), and where more requests are marked than one pass reads, the oldest marks are still read on every pass and the others once in each turn of the scan. A reading ends at a run that reports paused with its pause gone and keeps only what it read by then, so each run of a tree in the second state can cost a pass more; the other states of a tree are read in one reading, kept together, and stand together. The seventh state takes the passes that read on. The seat states this against the option text of the third ruling, which named one hour and which [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) quotes, and asks no new ruling (seat note [`7270603869`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7270603869), with the seat's correction [`7272498941`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7272498941) of its third line: the pass more can fall on any marked approval, one that holds a decision back included). The second has stopped where its own log ends, and the fourth where it is parked, as before. The other four are placed by the one rule of the rulings, at the step last decided: the third and the fifth as the rulings state it, and the sixth and the seventh as runs that cannot be read, by the seat's ruling and acceptance above. Whether a step can follow the step last decided is asked in the request's own flow: the flow of the run still parked at that step, and otherwise the flow the request records. Where the set of nodes the request carries ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)) names that flow, a node of another flow of the approval that carries the step's id does not answer for it. Where the set names no such flow, or the request records none, the id alone decides, which can only cost a resubmission. What came before that step the reconciler does not read again, because the plugin keeps it: at each door, also one that leaves a request open (the first point of the seat's reading), and as each request opens, it records on the approval's own rows whether the approval has, so far, a failure between two steps that no later request answered. It keeps there, too, which runs it has read to their end, so that a judgement reads on from the one before it. Where a step can follow the step last decided, the approval ended between two steps and is abandoned as [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) says. Where the approval holds a decision back, the run still parked in the fifth state is then cancelled, and with it every run above it that waits on it, up to the run that carries the record, through a `map` as through a `subflow`, so that nothing resumes the approval on a record that was put back. A `map` in that chain has items that are not records, so its items are steps of this one approval, and the batch is cancelled with its item and does not go on to the next. The cancel is not tried again once the put-back has landed: where it fails, the run stays parked, the approval stays abandoned, and the door that continues a restored run refuses it, as [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) has it. Where the approval holds nothing back, nothing is written, told or cancelled: the mark is cleared and the run stays parked. Where none can, the approval has finished: its outcome is written and the administrators are told in one stroke, in the third state as in the fifth, as the third ruling has it, and in the sixth and the seventh as well. The notice goes only on the pass whose write of the outcome landed: a refused write sends no such notice, and the pass on which the write lands sends it. It goes out on the topic `approval.flow_not_continued` and says that the flow could not be seen through to its end after its last step, because the flow's nodes behind that last decision did not run, or cannot be shown to have run. In the sixth and the seventh state the flow may have gone on where the plugin could not read it, so the notice asks for a check and states no failure. In the fifth state the pause is left, so that an operator can still continue the run (`packages/plugins/plugin-approvals/src/approval-service.ts#continueRestoredRun`). It writes in the name of the request's recorded decider, as the door would have: a write with no actor would leave a flow that reacts to the change, and runs as the user, without an identity. It tries a refused outcome or put-back again while the mark stands, and sends the administrators' notice. Where nothing was held back it clears the mark and writes nothing: no outcome, no put-back, no notice and no cancel, also where it placed a run, and a line in the log says what it concluded. For a record that was deleted it clears the mark and writes nothing, and it neither tries again nor notifies. On a host with no `job` service the first request of every approval on an object that declares `closedStates` is refused, with an error that says what is missing, also where the approval's field closes on nothing. Its tests include a parent run that is cancelled while its child's request is pending; a process that dies between a decision and the write of its outcome; a run that has no row, past the bound, where a step can follow the step last decided, which is abandoned, and where none can, whose outcome is written and whose administrators are told; a run that has no row under a run that went on past its step, which is passed, so that the approval finishes at the door and nobody is told, and the same under a run that went on along a failure route, which is held and then placed; a decision whose run never went on, before the last step, where the approval is abandoned and the parked run cancelled, with the batch above it where it is an item run of a `map` whose items are not records, and at the last step, where the outcome is written once the bound has passed, the administrators are told and the pause is left; a step that started more child runs than it names, which is held to the bound and then placed; a tree of more runs than the judgements can read in full, which is placed once a judgement keeps no further run; a run parked at a `map` whose items are records, on an item run that has ended and on one that has not; a run the engine is resuming past the bound, which is not placed, and a state that two judgements in a row read, which is; a judgement whose reading cannot be kept, which places nothing; a step last decided whose id a node of another flow carries; an approval that holds nothing back in which a run is placed, where nothing is written, told or cancelled; an approval whose field the object does not close on, whose hold the reconciler ends; a host with no `job` service, on which such an approval is refused as well; and a record deleted in a passage, whose mark is cleared once. - **The hold.** On an object that declares `closedStates` the pending lock's reads honour the mark, so that the record and its lines are held through every passage of every approval, with the passes and the limits [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) gives: the revise window, a caller's delete of the record, a system context, a write that carries only the mirror field, and the approval's own runs, known by their root run. In a passage those reads do not ask the node's `lockRecord`. The one lock read of item 2 answers `approval` in a passage. The approvals-family read is not touched and answers as published. This part settles two things the design note left open. The first is how the lock reads a writer's root run, and with it which indirect writes carry a run of the approval: a hook of the app that writes back to the record, and a cascade from another object. One that carries none is refused, and the build pins each case. The second is how the approval of a record that is deleted in a passage ends, where `main` cancels a pending request and no other (`packages/plugins/plugin-approvals/src/approval-service.ts#cancelForDeletedRecord`): the approval is marked abandoned, its marks are cleared and nothing is written, so that no mark of a deleted record stands for good and the reconciler has nothing to try again or to notify for. Its tests include a caller's write between two steps and after the last decision, each of which is refused; the same on an approval whose field the object does not close on, and on an object that closes only on values of its own; a write by a node of a parent run after its child's step is decided, which lands; a line write in a passage; a node that declares `lockRecord: false`, under which a caller's write lands while its request is pending and is refused after its decision; a revise window that follows an earlier step's decision, which is open to every caller who may edit; a caller's delete in a passage, which lands and ends the approval; a hook's write-back and a cascade in a passage, each with the approval's run and without it; the approvals-family read in a passage, which answers as on `main`; an approval that opened before the object declared the key, which is not held; and a process that dies in a passage, after which the reconciler ends the hold. - **The docs.** The approvals guide says what an author and an administrator see in each case: that the document reads `pending` until its approval is over; that a flow which fires on `approved` fires once on such an object, when the approval is over; that a node after a decision reads `pending`; what a refused write and an abandoned approval look like on the request; that on an object that declares `closedStates` every approval holds the document between its steps, whatever its field and whatever a node's `lockRecord` says, and that a pause there holds it for as long as it lasts; that a client which asks only the approvals-family lock read is not told of that hold; and that every approval on such an object needs a host with a `job` service. @@ -533,7 +556,7 @@ Left open on purpose, each a later decision if it is ever wanted: - An approval on an object that closes on `approved` or `rejected` is refused when it opens until five things hold: `pending` is declared and open and `returned` is open, a `state_machine` rule on the field lets the closed outcome move to `pending`, the field carries no `readonlyWhen` and its options for a request's statuses no `visibleWhen`, every step that can act on the object names the one field, and no flow pauses between two steps. An object that closes on `pending` or on `returned` runs no approval onto that field, and an approval the platform cannot read whole is refused ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). - Every approval on an object that declares `closedStates` needs a host that runs a `job` service, also one whose field closes on nothing (seat ruling [`7211531658`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211531658)). With none, nothing would end an approval, or its hold, that nobody is at the door for, and the approval is refused when it opens. An object that runs approvals on a host without that service cannot declare the key until the host has one. - A fault between two approval steps costs a resubmission, and every step already decided is decided again: a fault at step four of five costs four approvals. The platform abandons the approval at once and does not wait for an administrator ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). -- A document reads `pending` for longer than it does on `main`. Its outcome waits for the flow behind the last decision, and, where the door cannot tell that the run has ended, for the reconciler's next pass. One status mirror has two timings: on a field the object closes on at `approved` or `rejected` every decision waits for the end of its approval, and every other status is written at once. That includes a decision the object does not close on. Where an object closes on `rejected` alone, an approved step shows only when the approval is over, and a view or a flow that reads the field between two steps reads `pending`. +- A document reads `pending` for longer than it does on `main`. Its outcome waits for the flow behind the last decision, and, where the door cannot tell that the run has ended, for the reconciler: for its next pass where the run can then be read, and, in the six states [Execution](#execution-after-acceptance) item 8 holds to its age bound, for that bound, which is an hour from the mark, and for one pass more where no judgement read the approval's state within that hour. What ends the wait there is the outcome, or the put-back where the approval ended between two steps. One status mirror has two timings: on a field the object closes on at `approved` or `rejected` every decision waits for the end of its approval, and every other status is written at once. That includes a decision the object does not close on. Where an object closes on `rejected` alone, an approved step shows only when the approval is over, and a view or a flow that reads the field between two steps reads `pending`. - A caller who can edit a document between two approval steps on `main` cannot on an object that declares `closedStates`: the hold keeps it, in every approval on the object, whether or not the approval closes anything and whatever its nodes' `lockRecord` says. An author who declares a closed value of the object's own, `paid`, changes how an approval that has nothing to do with that value behaves between its steps. A node that follows the last step after a pause, in a flow that runs as the user, meets a closed document. - A pause between two steps of an approval the conditions do not concern holds its document for as long as the pause lasts, where on `main` the document is open through it. Nobody is asked meanwhile, and the way to end it sooner is to cancel the run. - The request gains one field, the mark, and the approvals plugin gains a reconciler that correctness depends on, where `main` has a report. Every approval on an object that declares `closedStates` carries the mark at each decision and is reconciled, also one that holds nothing back. diff --git a/docs/adr/0163-field-write-locks-two-tiers-two-forms-two-levels-ui-prefix-admission.md b/docs/adr/0163-field-write-locks-two-tiers-two-forms-two-levels-ui-prefix-admission.md new file mode 100644 index 00000000000..4530857cb94 --- /dev/null +++ b/docs/adr/0163-field-write-locks-two-tiers-two-forms-two-levels-ui-prefix-admission.md @@ -0,0 +1,141 @@ +# ADR-0163: A field's write lock has two tiers, two forms and two levels — `readonly` / `readonlyWhen` keep every client write out, `uiReadonly` / `uiReadonlyWhen` keep a person's hand out at the console, a field's own declaration wins over its object's default, and a `ui`-prefixed key is admitted only where the console's answer and the server's legitimately differ + +**Status**: Accepted (2026-11-26) — maintainer ruling on [#36806](https://github.com/objectstack-ai/objectstack/issues/36806), ruling record [`7180466652`](https://github.com/objectstack-ai/objectstack/issues/36806#issuecomment-7180466652), verbatim 「按长远模型」, and the maintainer's ruling of 2026-11-28 on the object level, ruling record [`7235326611`](https://github.com/objectstack-ai/objectstack/issues/37402#issuecomment-7235326611), verbatim 「B 不算放开 (Recommended)」. `docs/adr/**` is Tier H (Prime Directive #14): this record lands by the maintainer's merge or enqueue, or by an authorised approval. **This record declares.** The keys it describes are on `main` already, landed by [#37436](https://github.com/objectstack-ai/objectstack/pull/37436), [#37888](https://github.com/objectstack-ai/objectstack/pull/37888) and [#38169](https://github.com/objectstack-ai/objectstack/pull/38169); the PR that carries this record changes one refusal message so that it names this record ([D6](#d6--contradictions)). Three things the rulings decide are held by no code yet, each with its card: [Ruled and not yet held](#ruled-and-not-yet-held). + +- **Date**: 2026-11-28 +- **Card**: [#37405](https://github.com/objectstack-ai/objectstack/issues/37405) (p2, `area:data`), a sub-issue of #36806, filed by the ruling record so that the model and the naming rule have a record to cite and do not live only in the keys' describe texts. +- **Decided by**: the maintainer, 2026-11-26, in the decision thread 「裁决 #36806 只读字段命名」: option A 「新增 uiReadonly 布尔键」 on the decision card, then 「按长远模型」, after 「我说的合理的方案是从元数据应用实际可能发生的业务需求角度出发,不等卡」 and 「考虑长远合理的方案」. Ruling record `7180466652` states the model, its phases and the naming rule. The ruling's own text is the authority this record writes down; where the two differ in words, the ruling wins and this record is corrected. +- **Ruled since**: the maintainer, 2026-11-28, on two questions the object level raised, both on [#37402](https://github.com/objectstack-ai/objectstack/issues/37402). Ruling record `7235326611`: 「B 不算放开 (Recommended)」, a field's explicit `uiReadonly: false` does not open it inside a locked record ([D3](#d3--two-levels-the-field-and-the-object-and-the-fields-own-declaration-wins)). Ruling record [`7237772411`](https://github.com/objectstack-ai/objectstack/issues/37402#issuecomment-7237772411): 「本 PR 按字面落地+立跟进卡 (Recommended)」, the inline line rows of a hand-locked parent are a follow-up card ([Ruled and not yet held](#ruled-and-not-yet-held)). +- **Builds on**: [ADR-0049](./0049-no-unenforced-security-properties.md) (a declared key is enforced on every surface it names). [ADR-0085](./0085-object-semantic-roles-over-surface-hint-blocks.md) §2 (the admission test for future keys: a key binds the object across surfaces, and fails if its honest name contains a page name). [ADR-0092](./0092-sys-user-profile-field-delegation.md) (history: it recorded field-level `readonly` as a UI hint and not a server boundary; the write-path strip has since made it one, which is why the hand lock needs a name of its own). [ADR-0124](./0124-server-enforces-client-is-courtesy.md) (the server is the enforcement point; a client gate stricter than the server is a presentation choice, D4). [ADR-0137](./0137-predicate-fault-semantics-are-contract.md) D2 (what a field-rule predicate that faults does). [ADR-0020](./0020-state-machine-converge-and-enforce.md) (the `state_machine` rule that judges the writes the hand lock lets through). +- **Leaves unchanged**: `readonly` and `readonlyWhen`, in every respect; every permission grant; the closed-state lock of [ADR-0162](./0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md), which is a record lock that refuses and not a field lock. +- **Inputs**: code and docs text read on `objectstack-ai/objectstack` `main` at `c610020e`. Positions are in [As built](#as-built-read-at-c610020e). + +--- + +## Provenance + +Two kinds of statement appear below, and they are kept apart. + +1. **Ruled.** [Decision](#decision) carries only what the rulings say: ruling record `7180466652` (the model, the naming rule, what counts as by hand, the contradiction handling), and ruling records `7235326611` and `7237772411` (the object level). Where a D-item quotes, the words are the ruling record's. +2. **Readings.** [As built](#as-built-read-at-c610020e) says what the code on `main` does at `c610020e`, cited by symbol anchor (`path#symbol`). A behaviour that appears only there was settled by the PR that landed it and its contract review. It is not a decision of this record. + +## TL;DR + +| | Server lock: no client may write | Hand lock: no person edits by hand; API, import, actions and flows write, judged by validations | +|:--|:--|:--| +| Always | `readonly` | `uiReadonly` | +| Conditional (CEL over `record`) | `readonlyWhen` | `uiReadonlyWhen` | + +- Two **tiers**. The engine reads the server lock and never the hand lock. The console reads both. +- Two **forms**. A boolean, and a predicate over the record's own columns. `readonlyWhen: P\`true\`` is "set once on create"; there is no key for it. +- Two **levels**. An object's `uiReadonlyWhen` hand-locks the whole record, and a field's own hand-lock declaration replaces it for that field. +- **One naming rule.** A `ui`-prefixed twin of a key exists only where the console and the server legitimately answer the same question differently. Read-only is the only such concept today: `uiVisibleWhen` and `uiRequiredWhen` are refused. +- The hand lock is **not a security boundary**. Who may write a field is a permission. + +## Context + +A document's status usually moves only through its actions: an order is confirmed by Confirm, not by picking "Confirmed" in a form. Until this ruling the platform had one word for a field nobody edits, `readonly`, and that word is a server boundary: a non-system write that carries a `readonly` field has the field dropped and the rest lands. Measured on the hotcrm sales order (the body of #36806, for objectstack-ai/hotcrm#2716): with `status` declared `readonly`, a declarative update action answered success while the status stayed `draft`, a `PATCH` answered 200 with `X-ObjectStack-Dropped-Fields: status;reason=readonly`, and an import update reported the field dropped. The state machine saw none of them. So an author could keep people out of the field only by keeping the action, the import and the API out with them. + +The ruling adds the second fact a field can carry, under its own name, and settles the whole model at once so that later cards do not each invent a spelling: which keys exist, at which levels, what "by hand" means, and when a `ui`-prefixed key may be added at all. + +## Decision + +### D1 — Two tiers: the server lock and the hand lock + +A field carries two independent write facts. + +- **The server lock** (`readonly`, `readonlyWhen`): no client may write the field. It is enforced on the write path, for every door. +- **The hand lock** (`uiReadonly`, `uiReadonlyWhen`): no person edits the field by hand. Writes through the API, import, actions and flows keep the field, and the object's validations judge each of them exactly as they judge an ordinary field, a `state_machine` rule included. + +The engine never reads the hand-lock keys. A write to a hand-locked field is not dropped and is not reported as dropped. The console reads both tiers through one verdict: a field is read-only by hand now when `readonly` is true, or `readonlyWhen` is TRUE, or `uiReadonly` is true, or `uiReadonlyWhen` is TRUE. + +The hand lock answers a different question from a permission, and it is not one. It says by which route a person changes the field, not who may change it: a caller who may edit the record can write a hand-locked field through the API. Deleting the console's check would let no caller land a write the server refuses, so under ADR-0124 the check is a presentation rule and not an enforcement point in the wrong place. Who may write a field is the permission set's `editable` grant. An object whose fields carry only hand locks is no more protected than one with none, which is the boundary ADR-0092 refused to draw in the interface and this record does not draw there either. + +### D2 — Two forms: always and conditional + +Each tier has a boolean and a predicate. The predicate is CEL over `record`, the bound record's own columns, and both tiers' predicates have the same scope. + +"Set on create, fixed afterwards" is `readonlyWhen: P\`true\``, in the ruling record's words "the RAP `readonly:update` / OData `Core.Immutable` shape; no new key". + +A create from the console leaves a `uiReadonly` field out, and the server applies the field's `defaultValue`. An insert through the API, an import or an action may set the field, judged by the validations (a state machine's initial states). + +### D3 — Two levels: the field and the object, and the field's own declaration wins + +The object level of the hand lock is `uiReadonlyWhen` on the object: while TRUE the whole record is locked by hand. It is a default for each field. A field that declares a hand lock of its own, `uiReadonly: true` or a `uiReadonlyWhen`, is judged by that declaration instead, in both directions: a field whose own `uiReadonlyWhen` is `P\`false\`` stays editable inside a locked record, and a field's own predicate can lock it where the object does not. + +An explicit `uiReadonly: false` is not such a declaration (ruling record `7235326611`). It is that key's default, and a Studio switch turned on and then off stores it; read as an opt-out, it would silently open the field on every locked record. The one opt-out spelling is `uiReadonlyWhen: P\`false\``. + +A field's server lock is not a hand-lock declaration. It keeps locking on its own, whatever the object declares. + +The ruling record names an object-level `readonlyWhen` as "the symmetric completion the model allows later; not filed". This record files nothing for it either. The object level has one key today. + +### D4 — What "by hand" is + +Quoted from the ruling record: + +> "By hand" = create/edit dialogs (and the submitted payload), record-page inline edit, highlight-strip chip, grid inline edit and multi-row save, kanban drag, calendar drag, duplicating a record from the console, and an in-app assistant acting for a person. Not by hand = REST create/update, import (including the console import wizard's mapping), declarative and script actions, flows. + +ADR-0049 holds the key to every surface it names. A console surface through which a person changes a field's stored value reads the one verdict of D1, and a surface added later joins that read in the PR that adds it. + +### D5 — The `ui` prefix has an admission rule + +Quoted from the ruling record, which asks to be cited for it: + +> a `ui`-prefixed twin of a key is admitted only where the console's and the server's answers to the same question legitimately differ. Read-only is the only such concept today: visibility has one tier (the server side is permission masking, `requiredPermissions` / FLS `readable`, a different key) and required-ness has one tier (the server; the console mirrors `requiredWhen` for feedback). `uiVisibleWhen` and `uiRequiredWhen` are refused by this rule. + +`ui` names the console as a channel and not a page, which is how the two keys pass ADR-0085 §2. A later card that wants a `ui`-prefixed key cites this rule and shows the two answers that legitimately differ. One that cannot show them does not add the key. + +### D6 — Contradictions + +- `uiReadonly: true` beside `readonly: true` is refused at validate, at `['uiReadonly']`, at every door that parses a field. The server lock already keeps every client out, so the pair says two things at once. The refusal's text names this record. +- `uiReadonlyWhen` beside `readonlyWhen` is allowed. The two predicates can differ, and where `readonlyWhen` is TRUE the server lock is the stricter one. + +### D7 — The server lock stays a strip + +This record changes nothing on the write path. A client write that carries a server-locked field has the field dropped and the rest lands, and the answer names the dropped field (`X-ObjectStack-Dropped-Fields`, `droppedFields`). A mode in which the server lock refuses the write instead is out of this record's scope. The option a caller can already pass to have such a write refused whole is unchanged. + +## Ruled and not yet held + +Three things the rulings decide have no code holding them at `c610020e`. Each is a card, and none is re-opened here. + +| Ruled | Today | Card | +|:--|:--|:--| +| An in-app assistant acting for a person is a hand surface (D4). | Its writes run in the AI service, outside this repository, which does not read the hand lock. The keys' describe texts say so. | [#37898](https://github.com/objectstack-ai/objectstack/issues/37898) | +| Duplicating a record from the console is by hand (D4): the copy takes each hand-locked field's `defaultValue`. | The console has no person-triggered duplicate. The REST clone door is an API write, which the ruling keeps. | [#38202](https://github.com/objectstack-ai/objectstack/issues/38202) | +| The inline line rows of a hand-locked parent come under its lock (ruling record `7237772411`). | A line-item column follows the child object's own lock. | [#38249](https://github.com/objectstack-ai/objectstack/issues/38249) | + +## As built, read at `c610020e` + +- **The four field keys and the object key**: `packages/spec/src/data/field.zod.ts#FieldSchema` (`readonly`, `readonlyWhen`, `uiReadonly`, `uiReadonlyWhen`, and the refusal of D6 in its refinement); `packages/spec/src/data/object.zod.ts#ObjectSchemaBase` (`uiReadonlyWhen`). `uiReadonly` is optional with no default materialised: absent reads as false. +- **The server lock**: `packages/objectql/src/validation/rule-validator.ts#stripReadonlyFields` and `#stripReadonlyWhenFields`. Neither reads a hand-lock key. A conditional lock is not judged on a create, which is what makes `readonlyWhen: P\`true\`` set-once. The dropped fields reach the caller through `packages/rest/src/error-response.ts#applyDroppedFieldsHeader`; the refusal a caller can opt into is `packages/objectql/src/readonly-strict-errors.ts#ReadonlyFieldRejectedError`. +- **The one hand-lock verdict**: `ui/packages/core/src/evaluator/handLock.ts#fieldReadOnlyByHand`, with the object level folded in by `#effectiveUiReadonlyWhen`. Beyond the surfaces the ruling lists, the same verdict is read by the stage path, the line-item grid, the calendar quick-create, the Gantt (drag, resize, progress handle, dependency link, in-place edit), the timesheet cell and the command palette's create-as prefill. The import wizard's target mapping and the Studio authoring reads stay on the raw `readonly`. +- **A conditional hand lock is judged on an existing record only.** The create dialog does not read `uiReadonlyWhen`. +- **A hand-lock predicate that cannot be evaluated locks the field**, since no server judges it, and the edit dialog refuses to submit until it is fixed. `os validate` checks a field's and an object's `uiReadonlyWhen` as it checks `readonlyWhen` (`packages/lint/src/validate-expressions.ts`). +- **A caller denied a field the predicate reads** is served the lock closed instead of the predicate: `uiReadonly: true` on the field, a constant TRUE for the object's (`packages/metadata-core/src/object-schema-fls-references.ts`). +- **MCP `describe_object`** reports the hand-lock keys as their own keys, never folded into `readonly`, which tells an agent to leave a field out of a write (`packages/runtime/src/domains/mcp.ts#describeServedObject`). +- **Proof that every write keeps a hand-locked field**: `packages/qa/dogfood/test/ui-readonly-hand-lock-36806.dogfood.test.ts`. Over HTTP, a `PATCH`, an import and a declarative action write a `uiReadonly` field with no dropped-fields header, the `state_machine` rule refuses an illegal move with its own message on each door, and a `readonly` sibling is stripped as the control. The verdict's pins are `ui/packages/core/src/evaluator/__tests__/handLock-36806.test.ts`; the refusal's is `packages/spec/src/data/field-ui-readonly.test.ts`. + +## Consequences + +- An author has an honest declaration for "people do not type this; the buttons, the imports and the API set it": `uiReadonly`. `readonly` keeps its strong meaning, and nothing about it moves. +- The console can be stricter than the server by declaration. A person who may edit the record can still write a hand-locked field through the API. Where that must not happen, the answer is a permission, or the server lock. +- The hand lock has no server judge. It holds only as far as every console surface reads the one verdict, and a surface that forgets it opens the field with no refusal anywhere. The three rows of [Ruled and not yet held](#ruled-and-not-yet-held) are that cost today. +- A card that wants another `ui`-prefixed key has a rule to meet (D5) before it has a name to pick. + +## Alternatives considered + +The decision analysis the maintainer read is comment [`7179210173`](https://github.com/objectstack-ai/objectstack/issues/36806#issuecomment-7179210173) on #36806. In short: + +| Alternative | Why not | +|:--|:--| +| `editable: 'actions'` on the field | `editable` is the permission set's write grant. The word would mean "may write" on a grant and "the console may not write" on a field, and the value misdescribes API, import and flow writes. | +| Widen `readonly` to `boolean \| 'ui'` | The engine strips on a truthy `readonly`, so `'ui'` would be stripped on every write, the opposite of the ask, on a shipped server-enforced key. | +| No key: `readonly` plus a script action, which runs in a system context | The button works, and API and import writes to the field are still dropped silently. | +| A key for "editable on create, locked afterwards" | `readonlyWhen: P\`true\`` already says it (D2). | +| `uiVisibleWhen`, `uiRequiredWhen` | Refused by D5: each of those questions has one tier. | + +## Refs + +- Card [#37405](https://github.com/objectstack-ai/objectstack/issues/37405); parent [#36806](https://github.com/objectstack-ai/objectstack/issues/36806), ruling record [`7180466652`](https://github.com/objectstack-ai/objectstack/issues/36806#issuecomment-7180466652); object level [#37402](https://github.com/objectstack-ai/objectstack/issues/37402), ruling records [`7235326611`](https://github.com/objectstack-ai/objectstack/issues/37402#issuecomment-7235326611) and [`7237772411`](https://github.com/objectstack-ai/objectstack/issues/37402#issuecomment-7237772411). +- Landed by [#37436](https://github.com/objectstack-ai/objectstack/pull/37436) (the field keys and the console surfaces), [#37888](https://github.com/objectstack-ai/objectstack/pull/37888) (the Gantt, the timesheet, the calendar quick-create and the palette prefill) and [#38169](https://github.com/objectstack-ai/objectstack/pull/38169) (the object level). +- Open: [#37898](https://github.com/objectstack-ai/objectstack/issues/37898), [#38202](https://github.com/objectstack-ai/objectstack/issues/38202), [#38249](https://github.com/objectstack-ai/objectstack/issues/38249). diff --git a/docs/adr/README.md b/docs/adr/README.md index ef063606780..30d5db78151 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -13,11 +13,11 @@ ## Summary -163 records under `docs/adr/` (158 numbers), 11 under `ui/docs/adr/` (listed separately below). +164 records under `docs/adr/` (159 numbers), 11 under `ui/docs/adr/` (listed separately below). | Status | Records | |---|---| -| Accepted | 139 | +| Accepted | 140 | | Proposed | 10 | | Superseded | 4 | | Draft | 3 | @@ -26,7 +26,7 @@ | Amended | 1 | | Partially implemented | 1 | | Revised | 1 | -| **Total** | **163** | +| **Total** | **164** | ## Shared numbers @@ -230,6 +230,7 @@ A bare `ADR-0006` names the decision; its current text is [0006-project-environm | [ADR-0160](./0160-record-scoped-ai-inquiry.md) | Record-scoped AI inquiry — a context pack is its own metadata type, read as the caller and served by one tool… | Accepted — merged 2026-11-24 (PR objectstack#37115); amended 2026-11-25, 2… | 2026-11-24 | — | — | | [ADR-0161](./0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md) | The knowledge platform boundary — the platform owns document assembly, sync and reconcile, structural split a… | Proposed — 2026-11-24, written for objectstack#37001 on the maintainer's r… | 2026-11-24 | — | — | | [ADR-0162](./0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md) | An object declares its closed states — in them the record and its master-detail lines are closed to change fo… | Proposed — 2026-11-26, written for objectstack#36253 on the maintainer's r… | 2026-11-26 | — | — | +| [ADR-0163](./0163-field-write-locks-two-tiers-two-forms-two-levels-ui-prefix-admission.md) | A field's write lock has two tiers, two forms and two levels — `readonly` / `readonlyWhen` keep every client… | Accepted — 2026-11-26 — maintainer ruling on #36806, ruling record `718046… | 2026-11-28 | — | — | ## ObjectUI registry — `ui/docs/adr/` (`ui-` prefix) diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md index 5f25e0c458c..3ecff028bbc 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `ai/` | 121 | +| `ai/` | 123 | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md index 9c83f7ff346..c78b923b74b 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `api/` | 545 | +| `api/` | 544 | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md index 16f509d22ee..66ff6fbb0f8 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md @@ -21,7 +21,7 @@ The `strict` column is the one the campaign schedules against; it counts both th | Dir | Sites | strict | passthrough | catchall | strip | |---|---|---|---|---|---| -| `data/` | 184 | 115 | 2 | 0 | 67 | +| `data/` | 185 | 116 | 2 | 0 | 67 | ## `data/` — sites @@ -54,7 +54,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `hook-body.zod.ts` | 2 | | `hook.zod.ts` | 7 | | `mapping.zod.ts` | 8 | -| `object.zod.ts` | 31 | +| `object.zod.ts` | 32 | | `picklist.zod.ts` | 3 | | `query.zod.ts` | 5 | | `recycle-bin.zod.ts` | 4 | @@ -62,7 +62,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `seed-loader.zod.ts` | 12 | | `seed.zod.ts` | 2 | | `validation.zod.ts` | 6 | -| **total** | **184** | +| **total** | **185** | ## `data/` — open @@ -70,7 +70,7 @@ Per file, how many of its sites still silently discard unknown keys. The `Class` column that decides the bucket split is hand-written in the ledger; the arithmetic over it is here. -**67 strip of 184**, in 11 file(s). +**67 strip of 185**, in 11 file(s). | File | Strip | Sites | |---|---|---| @@ -85,7 +85,7 @@ over it is here. | `query.zod.ts` | 3 | 5 | | `recycle-bin.zod.ts` | 4 | 4 | | `seed-loader.zod.ts` | 12 | 12 | -| **total** | **67** | **184** | +| **total** | **67** | **185** | | Bucket | Sites | |---|---| diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/security.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/security.md index e2f5ec35cb8..696d4b99601 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/security.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/security.md @@ -21,7 +21,7 @@ The `strict` column is the one the campaign schedules against; it counts both th | Dir | Sites | strict | passthrough | catchall | strip | |---|---|---|---|---|---| -| `security/` | 24 | 11 | 0 | 0 | 13 | +| `security/` | 27 | 11 | 0 | 0 | 16 | ## `security/` — sites @@ -31,12 +31,12 @@ classify and is not listed (it becomes reportable the day it grows its first sit | File | Sites | |---|---| -| `explain.zod.ts` | 11 | +| `explain.zod.ts` | 14 | | `permission.zod.ts` | 4 | | `queue.zod.ts` | 2 | | `rls.zod.ts` | 5 | | `sharing.zod.ts` | 2 | -| **total** | **24** | +| **total** | **27** | ## `security/` — open @@ -44,19 +44,19 @@ Per file, how many of its sites still silently discard unknown keys. The `Class` column that decides the bucket split is hand-written in the ledger; the arithmetic over it is here. -**13 strip of 24**, in 2 file(s). +**16 strip of 27**, in 2 file(s). | File | Strip | Sites | |---|---|---| -| `explain.zod.ts` | 11 | 11 | +| `explain.zod.ts` | 14 | 14 | | `rls.zod.ts` | 2 | 5 | -| **total** | **13** | **24** | +| **total** | **16** | **27** | | Bucket | Sites | |---|---| | authorable — the ruling's forced scope | 0 | | unresolved — needs a per-schema verdict | 0 | -| wire / open — out of forced scope | 13 | +| wire / open — out of forced scope | 16 | | no door — no carrier, ADR-0049 territory | 0 | | no gate — carrier live, no parse | 0 | | covered — no carrier, no parse, guarded at every consumer | 0 | diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md index 9944d4a929d..bcaeb4fd4f9 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 42 | -| Object name statically decidable | 40 | +| Write call sites | 51 | +| Object name statically decidable | 49 | | Object name chosen at run time | 2 | -| Object name spelled inline | 38 | +| Object name spelled inline | 47 | | Object name spelled through a `const` | 2 | | Object name is an `object: string` parameter | 1 | | Object name is some other run-time expression | 1 | -| Against a tenancy-enabled object | 40 | +| Against a tenancy-enabled object | 49 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 42 | +| Threading a tenant context | 51 | | Provably carrying none (options read, no context key) | 0 | | …and decidably tenancy-enabled | 0 | | Options argument unreadable | 0 | | …and decidably tenancy-enabled | 0 | -| Threading a decidably elevated (`isSystem`) context | 40 | +| Threading a decidably elevated (`isSystem`) context | 49 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 2 | -| Receiver carried a readable engine type | 42 | +| Receiver carried a readable engine type | 51 | | Receiver erased, placed by the object NAME | 0 | | Receiver erased, placed by an `object: string` PARAMETER | 0 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 | @@ -50,11 +50,11 @@ a row or a number here — fix the code, or the census, and regenerate. | `packages/plugins/plugin-approvals/src/action-slot-backfill.ts` | `update` | `sys_approval_action` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-activity-feed.ts` | `insert` | `sys_activity` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `object` | undecidable | context, elevation undecidable | 1 | -| `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_action` | enabled | elevated | 17 | +| `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_action` | enabled | elevated | 20 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `delete` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_request` | enabled | elevated | 1 | -| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 10 | +| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 16 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/backfill-platform-row-organizations.ts` | `update` | `objectPlan.object` | undecidable | context, elevation undecidable | 1 | diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-queue.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-queue.md index 2a1ba6b06ea..6b212481cd7 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-queue.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-queue.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 11 | -| Object name statically decidable | 11 | +| Write call sites | 13 | +| Object name statically decidable | 13 | | Object name chosen at run time | 0 | | Object name spelled inline | 0 | -| Object name spelled through a `const` | 11 | +| Object name spelled through a `const` | 13 | | Object name is an `object: string` parameter | 0 | | Object name is some other run-time expression | 0 | -| Against a tenancy-enabled object | 11 | +| Against a tenancy-enabled object | 13 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 11 | +| Threading a tenant context | 13 | | Provably carrying none (options read, no context key) | 0 | | …and decidably tenancy-enabled | 0 | | Options argument unreadable | 0 | | …and decidably tenancy-enabled | 0 | | Threading a decidably elevated (`isSystem`) context | 0 | | Threading a decidably non-elevated context | 0 | -| Threading a context of undecidable elevation | 11 | -| Receiver carried a readable engine type | 11 | +| Threading a context of undecidable elevation | 13 | +| Receiver carried a readable engine type | 13 | | Receiver erased, placed by the object NAME | 0 | | Receiver erased, placed by an `object: string` PARAMETER | 0 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 | @@ -49,4 +49,4 @@ a row or a number here — fix the code, or the census, and regenerate. |---|---|---|---|---|---:| | `packages/services/service-queue/src/db-queue-adapter.ts` | `delete` | `sys_job_queue` | enabled | context, elevation undecidable | 2 | | `packages/services/service-queue/src/db-queue-adapter.ts` | `insert` | `sys_job_queue` | enabled | context, elevation undecidable | 1 | -| `packages/services/service-queue/src/db-queue-adapter.ts` | `update` | `sys_job_queue` | enabled | context, elevation undecidable | 8 | +| `packages/services/service-queue/src/db-queue-adapter.ts` | `update` | `sys_job_queue` | enabled | context, elevation undecidable | 10 | diff --git a/docs/qa/platform-checklist/FOLLOW-UPS.md b/docs/qa/platform-checklist/FOLLOW-UPS.md index 22cb11170e6..feead8af512 100644 --- a/docs/qa/platform-checklist/FOLLOW-UPS.md +++ b/docs/qa/platform-checklist/FOLLOW-UPS.md @@ -1441,3 +1441,7 @@ listed in `releaseSweeps` with why. ### 19d. Security note No security finding was made, and none is withheld. + +## 20. Checklist drift 2026-11-29 — Studio's package-less scope is retired (#38150) + +Not a sweep: one follow-up, recorded by the change that retired the scope (ADR-0084's amendment of 2026-11-26, `#amendment-2026-11-26-org`), which edited no item. Every `/studio/~org/…` address now lands on `/studio/~all/metadata/flow?source=loose`, a flow that belongs to no package opens on its item page on the cross-package leg and not in the flow designer, and the scope's Changes row and batch publish are gone, so the live text of five items no longer describes the product: `studio-authoring.org-scope-flows` (the whole item: its title, steps[0], [4] and [5] and its three acceptance clauses describe the retired scope, so it is re-authored against the Loose list or retired), `automation.flow-run-step-nesting` steps[4], `automation.flow-error-handling` fixtures.requires[1], `automation.packaged-flow-clone-contract` steps[7], acceptance[6].verify and negative[4], and `integration-system.flow-connector-picker` steps[1]; `automation.flow-node-type-matrix` names the scope in a history row only and needs nothing. Each is re-measured with the product running before its text is changed. diff --git a/docs/qa/platform-checklist/RUNNER.md b/docs/qa/platform-checklist/RUNNER.md index b0741e08b25..89e740aee86 100644 --- a/docs/qa/platform-checklist/RUNNER.md +++ b/docs/qa/platform-checklist/RUNNER.md @@ -294,10 +294,11 @@ contradicts it, and correct it here when it does. packaged (`packages/apps/studio`, `com.objectstack.studio`), but **no stock boot loads it, by design** — both boot paths skip it with the identical note, "`@objectstack/studio` is intentionally NOT default-loaded — the console ships a dedicated Studio surface at - `/_console/studio//`, so Studio no longer needs to exist as a navigable + `/_console/studio/`, so Studio no longer needs to exist as a navigable app tile" (`packages/plugins/plugin-dev/src/dev-plugin.ts`, the ADR-0048 app-package loop; `packages/cli/src/commands/serve.ts`, same loop — both register only - `@objectstack/setup` and `@objectstack/account`). So `?id=studio` is legitimately empty + `@objectstack/setup` and `@objectstack/account`). The bare package address lands on + its 概览 Overview; the old pillar segments only redirect (`studioPillarRedirectModel.ts`). So `?id=studio` is legitimately empty on every stock boot, not just on the showcase, and a stock admin list is `["showcase_app","setup","account"]`. ⛔ Do not file the absence as a missing built-in, and do not install the package to "restore" it — that changes what the boot ships. @@ -1006,7 +1007,7 @@ contradicts it, and correct it here when it does. | trap | what it fakes | counter | |---|---|---| | `hydration-race` | empty nav/list right after navigation | screenshot first; settle; then read DOM | -| `stale-console-bundle` | UI bug already fixed upstream in objectui | check against objectui HMR console / fresh build (skill §2). `packages/console/dist` is a gitignored copy that `pnpm build` never refreshes, so a console older than the tree, or a 404 `/_console/`, reads "rebuild with `pnpm console:build`", never "console broken" | +| `stale-console-bundle` | UI bug already fixed upstream in objectui | check against objectui HMR console / fresh build (skill §2). `packages/console/dist` is a gitignored copy that `pnpm build` never refreshes, so a console older than the tree, or a `/_console/` that answers 503 with "The ObjectStack Console is not built" and that remedy, reads "rebuild with `pnpm console:build`", never "console broken" | | `stale-dist` | src edits with no runtime effect | rebuild package + restart before judging | | `automation-input` | dead buttons / empty submits caused by the driver | ref-targeted clicks; native setter + input/change events | | `shared-browser-tab` | drifting origin, foreign drafts | pin absolute origin; own port/DB (skill §0) | diff --git a/docs/qa/platform-checklist/areas/access-security.json b/docs/qa/platform-checklist/areas/access-security.json index 92bbb3e7e29..ea182c942c9 100644 --- a/docs/qa/platform-checklist/areas/access-security.json +++ b/docs/qa/platform-checklist/areas/access-security.json @@ -3070,7 +3070,7 @@ "since": "v16", "status": "retired", "retiredReason": "C3 stage 8 (ADR-0131 D3) retired the sys_permission_set row object: its data door, its Activate / Deactivate / Clone row actions and its `active` column are gone. A packaged set's base stays locked at the metadata door, a copy is made with POST /api/v1/security/permission-sets/:name/clone, and a set is switched off in the activation ledger (sys_metadata_activation).", - "revision": 2, + "revision": 3, "priority": "P2", "surface": "mixed", "personas": [ @@ -3081,7 +3081,7 @@ "app": "showcase", "requires": [ "a package-declared permission set: showcase_contributor (declared by com.example.showcase in examples/app-showcase/src/security/permission-sets.ts, projected to a sys_permission_set row at boot) — the SchemaRegistry, not the row's managed_by column, is what the lock reads (packaged-permission-set-lock.ts)", - "the Setup permission-sets surface rendering the object's own actions (Activate / Deactivate / Clone on locations list_item + record_header — packages/plugins/plugin-security/src/objects/sys-permission-set.object.ts)", + "the Setup permission-sets surface rendering the object's own actions (Activate / Deactivate / Clone on locations list_item + record_header, the page-part words protocol 19 later retired — packages/plugins/plugin-security/src/objects/sys-permission-set.object.ts, removed with the object by C3 stage 8; this item is retired and records the surface as it was)", "member M granted showcase_contributor, with a showcase_contributor-only verb to probe (e.g. a project PATCH the everyone baseline does not grant — compute the baseline union per access-security.crud-permission-matrix's knownGaps before picking it)" ], "knownGaps": [ @@ -3171,6 +3171,12 @@ "date": "2026-10-12", "change": "retired — the sys_permission_set row object, its data door and its row actions are retired with C3 stage 8 (ADR-0131 D3)", "ref": "#15204" + }, + { + "revision": 3, + "date": "2026-11-29", + "change": "fixtures.requires[1] marks its location words (list_item, record_header) as the pre-19 words protocol 19 retired (#36495) and its cited object file as removed with the object, so the retired item reads as the record it is. Nothing else changed; the item stays retired", + "ref": "#38046" } ] }, diff --git a/docs/qa/platform-checklist/areas/approvals.json b/docs/qa/platform-checklist/areas/approvals.json index d70eeb9e49e..e9803663bc8 100644 --- a/docs/qa/platform-checklist/areas/approvals.json +++ b/docs/qa/platform-checklist/areas/approvals.json @@ -1183,7 +1183,7 @@ "title": "A non-admin reaches the full Approvals Inbox from the account app's Approvals entry", "since": "v17", "status": "active", - "revision": 10, + "revision": 11, "priority": "P0", "surface": "browser", "personas": ["a NON-ADMIN business user who is a pending approver and has no Setup access"], @@ -1227,13 +1227,13 @@ { "clause": "decision actions render on the request page the inbox opens, and one of them actually moves the request", "oracle": "api", - "verify": "a row click opens /apps/APP/sys_approval_request/record/ID, the request's served record page (objectui#12484 retired the side sheet), where APP is the app that owns the request's RECORD, not the inbox's app: since objectstack#32667 the inbox's requestPagePath asks objectHostAppSegment (ui/apps/console/src/pages/system/ApprovalsInboxPage.tsx), so an invoice sign-off request opens under com.example.showcase (the app whose navigation lists showcase_invoice), and only when the reader can open no app that lists the record's object, nor Setup, does it stay in the inbox's app. That page's decision panel renders the server-declared action set for a request where this user is a pending approver; executing one decision moves the node tally, drops the user from pending_approvers, appends an action row (read it from GET /api/v1/approvals/requests/:id/actions: the request read carries no timeline, and there is no /history route), and the decision actions stop rendering for this viewer — their visible predicates read record.viewer.can_act, now false", + "verify": "a row click opens /apps/APP/sys_approval_request/record/ID, the request's served record page (objectui#12484 retired the side sheet), where APP is the app the inbox is mounted in: since objectstack#35412 a queue row keeps the reader in the inbox's own app (openRequest in ui/apps/console/src/pages/system/ApprovalsInboxPage.tsx), so from the account app's inbox an invoice sign-off request opens under com.objectstack.account (or its alias account, whichever segment the inbox URL carries). Only an inbox with no app segment asks requestPagePath, which sends the request to the app that owns its RECORD (objectHostAppSegment, objectstack#32667) the way acceptance[4]'s ?request= deep link does; a row click from this inbox landing under com.example.showcase is not the route this clause expects. That page's decision panel renders the server-declared action set for a request where this user is a pending approver; executing one decision moves the node tally, drops the user from pending_approvers, appends an action row (read it from GET /api/v1/approvals/requests/:id/actions: the request read carries no timeline, and there is no /history route), and the decision actions stop rendering for this viewer — their visible predicates read record.viewer.can_act, now false", "evidence": "before/after request-page screenshots + before/after GET /api/v1/approvals/requests/:id and its /actions" }, { "clause": "?request= deep-links to the request's record page from this component route too (route parity with /system/approvals)", "oracle": "screenshot", - "verify": "cold-load /apps//component/approvals/inbox?request=; the route replaces itself in history with /apps//sys_approval_request/record/, where is the app that owns the request's record (objectHostAppSegment, as acceptance[3]; com.example.showcase for an invoice sign-off), not necessarily this component route's , and that page shows that exact request. Cross-checked against the same id on /system/approvals by approvals.notification-deep-link", + "verify": "cold-load /apps//component/approvals/inbox?request=; the route replaces itself in history with /apps//sys_approval_request/record/, where is the app that owns the request's record (objectHostAppSegment, objectstack#32667, unlike a queue row, which acceptance[3] keeps in the inbox's app; com.example.showcase for an invoice sign-off), not necessarily this component route's , and that page shows that exact request. Cross-checked against the same id on /system/approvals by approvals.notification-deep-link", "evidence": "screenshot with the URL and the request identity visible" }, { @@ -1300,7 +1300,8 @@ "ref": "#28545" }, { "revision": 9, "date": "2026-11-08", "change": "The invite step presents the invitation: under invite_only a self-serve sign-up is admitted only by the invitation it presents, so the sign-up sends the id invite-member answered as invitationId beside the email, and the address alone answers 403 SELF_REGISTRATION_CLOSED. Prose only; no clause changed" }, - { "revision": 10, "date": "2026-11-14", "change": "steps[2] and acceptance[3], [4], [6] (verify) re-pointed (stale spec, card #33332; QA run #32953 R1 record comment 6840055541 and body checklist-accuracy notes, #33087 comment 6850382730). Since objectstack#32667 a request opens under the app that owns its record (objectHostAppSegment, read by ApprovalsInboxPage's requestPagePath): an invoice sign-off opens under com.example.showcase, not the inbox's com.objectstack.account, so acceptance[3] and [4] name that app. acceptance[6]'s picker entry is 简体中文 stored as zh-Hans (the platform locale table), not 中文(中国) zh-CN. steps[2] says the single-app persona lands in Showcase after sign-in, not on /home (RootLandingRedirect rule 2). The record-link clause acceptance[5] is unchanged: recordHref keeps the inbox's own app. No clause changed. Read from source at base fca5f89c", "ref": "#33332" } + { "revision": 10, "date": "2026-11-14", "change": "steps[2] and acceptance[3], [4], [6] (verify) re-pointed (stale spec, card #33332; QA run #32953 R1 record comment 6840055541 and body checklist-accuracy notes, #33087 comment 6850382730). Since objectstack#32667 a request opens under the app that owns its record (objectHostAppSegment, read by ApprovalsInboxPage's requestPagePath): an invoice sign-off opens under com.example.showcase, not the inbox's com.objectstack.account, so acceptance[3] and [4] name that app. acceptance[6]'s picker entry is 简体中文 stored as zh-Hans (the platform locale table), not 中文(中国) zh-CN. steps[2] says the single-app persona lands in Showcase after sign-in, not on /home (RootLandingRedirect rule 2). The record-link clause acceptance[5] is unchanged: recordHref keeps the inbox's own app. No clause changed. Read from source at base fca5f89c", "ref": "#33332" }, + { "revision": 11, "date": "2026-11-29", "change": "acceptance[3].verify re-pointed, and acceptance[4].verify's cross-reference to it (stale text, card #38426; QA run #38417, at ff69bcab, its clause-3 note). Since objectstack#35412 a queue row opens in the app the inbox is mounted in (ApprovalsInboxPage.tsx openRequest), so from the account app an invoice sign-off opens under com.objectstack.account, not com.example.showcase; only an inbox with no app segment, and the ?request= deep link of acceptance[4], go to the record's host app (objectHostAppSegment, objectstack#32667). No clause changed: the decision still has to render and move the request. Read from source at base 0c1b2ffe; no product change", "ref": "#38426" } ] }, { diff --git a/docs/qa/platform-checklist/areas/cli.json b/docs/qa/platform-checklist/areas/cli.json index b8fcb220f11..374934e4074 100644 --- a/docs/qa/platform-checklist/areas/cli.json +++ b/docs/qa/platform-checklist/areas/cli.json @@ -2150,7 +2150,7 @@ "title": "`os migrate organization-ownership` upgrades a database 17.x or an 18.0 pre-release (18.0.0-next.*) created (18.x): a bare run writes the reviewed plan and changes nothing; `--apply --plan-file PLAN --backup-taken` runs every step — attribution through the moves, the declared webhook and sharing-rule settlements, the column drops and NOT NULL — and certifies the marker at this release's ownership shape generation; the served boot refuses an uncertified database, naming the command, and boots a certified one; `os migrate apply --allow-destructive` still withholds every organization_id drop the ceremony owns, and `os migrate comment-reactions --apply` stays pinned", "since": "v18", "status": "active", - "revision": 13, + "revision": 14, "priority": "P0", "surface": "cli", "personas": [ @@ -2215,7 +2215,7 @@ { "clause": "an 18.0 pre-release database (one an 18.0.0-next.* release created and served) takes the same path as a v17 one and keeps its data: the served boot refuses it, the reviewed apply completes, and the next boot serves it with its identity mail, its global setting audit, its pending mail jobs and its declared webhook carried over", "oracle": "build", - "verify": "steps[5], each leg read at its own layer. Boot output: the first `os serve` exits 1 before any listening line, opening \"This database carries no organization-ownership marker\" and naming the tables still carrying organization_id (sys_flow_credential and sys_secret on 18.0.0-next.5); a database an 18.0.0-next.3 ceremony already certified at shape generation 0 is refused instead with \"… certified by an organization-ownership ceremony of shape generation 0, and this release requires generation 1 …\". The apply exits 0 with complete true and blocking 0, and the second boot reaches its serving line. Row reads, before the plan and after the second boot: every identity mail row (related_object sys_user, which is the reset and verification mail, and any magic-link mail) is in sys_identity_email under its original id, equal over the columns both tables hold, and gone from sys_email, while organization invitations stay in sys_email (packages/cli/src/utils/organization-ownership-apply.ts#SIBLING_MOVES); every sys_setting_audit row with scope 'global' is in sys_platform_setting_audit and gone from sys_setting_audit; every pending or running email.send.async or email.attachment.reclaim job naming a moved mail carries object sys_identity_email in its payload and metadata, while completed jobs and the organization-invitation job are unchanged; and no row disappears outside the apply report: every row id read before the plan is still in its table after the second boot, except the rows the report's steps say they moved (read in their new table, above) or deleted, whose numbers match the report. A count may grow: the second boot serves this release's composition, whose seed and bookkeeping add rows (on the cli-18-prerelease-db restore, QA runs #33784 and #33909: showcase_invoice_line 5 → 10, sys_user_position 5 → 10, sys_exchange_rate 0 → 4, sys_seed_landed_key 0 → 141, sys_migration 4 → 6, sys_oauth_resource 1 → 2, sys_metadata_activation 0 → 1), and an added row is no loss. On the cli-18-prerelease-db restore, sys_automation_run in the telemetry sibling keeps its count across the second boot but not two of its ids: the recipe's knownGaps[3] says why, and those two ids are not data the apply lost. On the same restore, the telemetry sibling's sys_activity shard is re-dated by the restore to the day before the run, so the first, refused boot keeps it (the recipe's knownGaps[4]) and sys_activity is read like any table. The door's answer: each pre-release user signs in with its 18.0 password (200; a wrong one 401); the token read from the moved reset mail resets (200); and the one showcase_task PATCH writes exactly one sys_http_delivery row whose ref_id is declared:com.example.showcase/showcase_task_changed (the declaring package's id, then the name: packages/qa/dogfood/test/upgrade-18x-harness.dogfood.test.ts pins it)", + "verify": "steps[5], each leg read at its own layer. Boot output: the first `os serve` exits 1 before any listening line, opening \"This database carries no organization-ownership marker\" and naming the tables still carrying organization_id (sys_flow_credential and sys_secret on 18.0.0-next.5); a database an 18.0.0-next.3 ceremony already certified at shape generation 0 is refused instead with \"… certified by an organization-ownership ceremony of shape generation 0, and this release requires generation 1 …\". The apply exits 0 with complete true and blocking 0, and the second boot reaches its serving line. Row reads, before the plan and after the second boot: every identity mail row (related_object sys_user, which is the reset and verification mail, and any magic-link mail) is in sys_identity_email under its original id, equal over the columns both tables hold, and gone from sys_email, while organization invitations stay in sys_email (packages/cli/src/utils/organization-ownership-apply.ts#SIBLING_MOVES); every sys_setting_audit row with scope 'global' is in sys_platform_setting_audit and gone from sys_setting_audit; every pending or running email.send.async or email.attachment.reclaim job naming a moved mail carries object sys_identity_email in its payload and metadata, while completed jobs and the organization-invitation job are unchanged; and no row disappears outside the apply report: every row id read before the plan is still in its table after the second boot, except the rows the report's steps say they moved (read in their new table, above) or deleted, whose numbers match the report. A count may grow: the second boot serves this release's composition, whose seed and bookkeeping add rows (on the cli-18-prerelease-db restore, QA runs #33784 and #33909: showcase_invoice_line 5 → 10, sys_user_position 5 → 10, sys_exchange_rate 0 → 4, sys_seed_landed_key 0 → 141, sys_migration 4 → 6, sys_oauth_resource 1 → 2, sys_metadata_activation 0 → 1), and an added row is no loss. On the cli-18-prerelease-db restore, sys_automation_run in the telemetry sibling keeps its count across the second boot but not two of its ids: the recipe's knownGaps[3] says why, and those two ids are not data the apply lost. Two more carve-outs on the same restore, neither of them data the apply lost (QA run #38417, at ff69bcab): (i) sys_record_share loses its one rule-sourced row at the second boot and gains its replacement, equal on object, record, recipient and access level, with source_id share_key_account_qualified_contacts_with_managers (the rule's name in the 18.0.0-next.5 dump) replaced by showcase_share_key_account_qualified_contacts_with_managers (examples/app-showcase/src/security/sharing-rules.ts): the showcase renamed the rule since, so the sharing engine drops the share of a rule that no longer exists and materialises the renamed rule's. Score it as a re-key, by those four columns, never as a lost row; a plain restart of a database this release created does not re-key shares. (ii) the fixture ages: the restore re-dates the shard names, not the rows' timestamps, so once the dump's rows are older than a retention window the second boot's reaper removes them, sys_activity at 14 days (packages/plugins/plugin-audit/src/objects/sys-activity.object.ts, retention.maxAge '14d') and terminal sys_automation_run rows at 30 days (packages/services/service-automation/src/sys-automation-run.object.ts, maxAge '30d'). On the 2026-10-27 dump the run read the 66 sys_activity rows and 4 terminal runs present at the second boot's ready and at ready plus 60 s, and gone a minute after the door calls. Read the row set at the second boot's ready, before any door call; a row past its window that is gone later is a reap, not a loss. On the same restore, the telemetry sibling's sys_activity shard is re-dated by the restore to the day before the run, so the first, refused boot keeps it (the recipe's knownGaps[4]) and sys_activity is read like any table. The door's answer: each pre-release user signs in with its 18.0 password (200; a wrong one 401); the token read from the moved reset mail resets (200); and the one showcase_task PATCH writes exactly one sys_http_delivery row whose ref_id is declared:com.example.showcase/showcase_task_changed (the declaring package's id, then the name: packages/qa/dogfood/test/upgrade-18x-harness.dogfood.test.ts pins it)", "evidence": "the refused boot's excerpt and exit code, the apply report's complete and blocking, the serving line; the before and after reads of sys_email, sys_identity_email, sys_setting_audit, sys_platform_setting_audit and the mail jobs, with per-table counts; the sign-in, reset and delivery answers" } ], @@ -2316,6 +2316,12 @@ "date": "2026-11-15", "change": "acceptance[0].verify names `--reporter=tree`, the reporter that prints the one line per pin file this is scored on: in a runner's non-TTY shell vitest's default reporter prints the run's totals only (RUNNER.md's environment facts; QA run #33784's note 10, comment 6893243542). No clause or threshold changed. Card #33969", "ref": "#34068" + }, + { + "revision": 14, + "date": "2026-11-29", + "change": "acceptance[5].verify gains two carve-outs (under-specified clause, card #38426; QA run #38417, at ff69bcab, its a5 note): the one rule-sourced sys_record_share row is re-keyed at the second boot because the showcase renamed the sharing rule since 18.0.0-next.5 (showcase_share_key_account_qualified_contacts_with_managers in examples/app-showcase/src/security/sharing-rules.ts), and the restored fixture ages into the 14-day sys_activity and 30-day terminal sys_automation_run retention windows, so rows are read at the second boot's ready, before any door call. No clause weakened: every other row id must still survive, and a re-keyed share must match on object, record, recipient and access level. Read from source at base 0c1b2ffe; no product change", + "ref": "#38426" } ] }, @@ -2770,6 +2776,87 @@ } ] }, + { + "id": "cli.stored-forms-census-and-precheck", + "title": "`os migrate stored-forms` lists, read-only, what the upgrade to the next protocol major does with each stored old-shape form row — kept, moved, folded, removed as an internal record form, left in place, or holding the upgrade — and whether the upgrade can switch", + "since": "v18", + "status": "active", + "revision": 1, + "priority": "P1", + "surface": "cli", + "personas": [ + "operator (runs the CLI against the deployment's database before upgrading)" + ], + "fixtures": { + "app": "showcase", + "requires": [ + "a showcase database of the run's own (dogfood §0); the CLI from this tree (`os` / `node packages/cli/bin/run.js`)", + "the stock read-only base com.example.showcase (examples/app-showcase/objectstack.config.ts) and a form it ships in an old shape or as a `form` item, named FORM" + ], + "knownGaps": [ + "The rows the census classifies are rows an older release left: a run stages them with the server stopped, as the command's integration test does (packages/cli/src/commands/migrate/stored-forms.integration.test.ts): insert into sys_metadata a row with type 'view', state 'active', version 1 and an old-shape form body (a `viewKind: 'form'` item named FORM, or a container with a `form` or `formViews` entry) bound to no package or to com.example.showcase. Without one, only acceptance[0] runs" + ] + }, + "steps": [ + "empty census: on a fresh showcase DB, run `os migrate stored-forms --json`; record the exit code, canSwitch and that nothing was written", + "stage a package-less `viewKind: 'form'` row named FORM with a sharing.publicLink (fixtures.knownGaps[0]); run `os migrate stored-forms --json` again and read the plan for FORM at com.example.showcase", + "stage a second row whose form content cannot be read (a `viewKind: 'form'` item with no `config`); run the census again; boot the server and read its start-up log", + "run `os migrate stored-forms` (text) and read the summary line and each row's sentence" + ], + "acceptance": [ + { + "clause": "the census is read-only: with nothing stored it lists nothing, says the upgrade can switch, and exits 0", + "oracle": "build", + "verify": "step 1: exit 0, canSwitch true, forms []; the sys_metadata and sys_packages contents are unchanged", + "evidence": "the JSON output + exit code + the before/after store reads" + }, + { + "clause": "a linked package-less form row over a shipped form is listed as moving into the base's .custom pair as a declared override, and nothing is written", + "oracle": "build", + "verify": "step 2: FORM at base com.example.showcase reads outcome move, destination pair_override com.example.showcase.custom with basedOn the base's version; canSwitch true; the store is unchanged", + "evidence": "the census JSON + the store read" + }, + { + "clause": "a body the projection cannot read holds the upgrade, and the start-up message names this command", + "oracle": "build", + "verify": "step 3: unreadable lists the row with cause unreadable and the repair action; canSwitch false; the boot log's error line for the row names `os migrate stored-forms`", + "evidence": "the census JSON + the boot log line" + }, + { + "clause": "the text report names each row with its outcome and ends with the counts and the switch verdict", + "oracle": "build", + "verify": "step 4: one line per form and address; the last lines read the counts and 'The upgrade would not switch: 1 row(s) hold it'", + "evidence": "the text output" + } + ], + "negative": [ + "a census that writes a row, creates a .custom package or offers deletion for a row that declares a public link is the FAIL: the command is read-only, and deleting a switched-off form's row switches it back on (ADR-0159 D7-e)" + ], + "traps": [ + "destructive-in-place", + "silent-coercion" + ], + "automated": { + "kind": "unit", + "ref": "packages/metadata-protocol/src/protocol-stored-form-migration.test.ts (the planner: each outcome and hold cause on its seed fixture) + packages/objectql/src/protocol-stored-form-migration.test.ts (the census over the real protocol: acceptance[1]–[2]) + packages/cli/src/commands/migrate/stored-forms.integration.test.ts (the CLI over a seeded database: acceptance[0]–[2]; integration tier) + packages/rest/src/public-form-two-type-withdrawal.test.ts pin 6 (the start-up message names the command)" + }, + "source": [ + "packages/cli/src/commands/migrate/stored-forms.ts#storedFormPlanText (the command; --json, --database-url, --preset, --dev)", + "packages/metadata-protocol/src/protocol-stored-form-migration.ts#planStoredForms (keep, move, remove, hold, left_in_place)", + "packages/metadata-protocol/src/protocol-stored-form-migration.ts#INTERNAL_AHEAD_OF_LINKED_ROW (the one place the internal-ahead-of-linked case is decided)", + "packages/metadata-protocol/src/protocol-form-reads.ts#readUnreadableFormBodies (the start-up message)", + "docs/adr/0159-forms-are-their-own-metadata-type-public-forms-are-form-items-view-is-lists-only.md D7 (the ceremony, D7-a to D7-e)", + "#37111 (ADR-0159 card ⑤a)" + ], + "history": [ + { + "revision": 1, + "date": "2026-11-29", + "change": "new item (ADR-0159 card ⑤a #37111, PR 1): the read-only census and precheck of the stored-form ceremony. Read from source at base 5df10ecc", + "ref": "#37111" + } + ] + }, { "id": "cli.address-grammar-reserved-names", "title": "The address grammar reserves its segments: a bucket 2/3 name led by _ is refused at defineStack and os validate; a namespace that spells a grammar literal is refused by os validate and os build (exit 1, no artifact) and at the running install door, while a package the boot registers keeps booting with a warning; and lint's namespace-prefix rule judges only capabilities and positions", diff --git a/docs/qa/platform-checklist/areas/i18n.json b/docs/qa/platform-checklist/areas/i18n.json index 9694702d065..af023c2fba6 100644 --- a/docs/qa/platform-checklist/areas/i18n.json +++ b/docs/qa/platform-checklist/areas/i18n.json @@ -185,7 +185,7 @@ "title": "Every translatable surface localizes on a zh-CN session — one pass over the full translation-group vocabulary, plus the runtime i18n routes it resolves through", "since": "v15", "status": "active", - "revision": 17, + "revision": 18, "priority": "P1", "surface": "browser", "personas": ["admin on a zh-CN session"], @@ -199,7 +199,7 @@ "the showcase's declared surface carries FROZEN untranslated debt, ratcheted by scripts/check-i18n-coverage.mjs + i18n-coverage-baseline.json — expect some declared strings to legitimately fall back to en; the per-surface check is 'translated keys render translated, untranslated keys render the SOURCE label (never a raw dotted key)', not 100% coverage", "objects._views..emptyState WAS unafforded and no longer is: the #7714 specimen has landed. examples/app-showcase/src/ui/views/task.view.ts authors an emptyState on the `urgent` view (its comment block cites #7714) and src/system/translations/index.ts carries the zh-CN half under objects.showcase_task._views.urgent.emptyState.{title,message}. The variant is runnable; the only setup it needs is an empty `urgent` view (demote the two urgent seed rows)", "objects._sections is addressable ONLY on sections that declare a `name` (packages/spec/src/ui/component.zod.ts: a nameless section renders its authored label in every locale; packages/lint's translation-section-name-missing rule nudges authors toward the name). On the stock showcase every surface this item reads declares one: showcase_task's DEFAULT form (the New/Edit form, section `task`), the task record page — examples/app-showcase/src/ui/pages/task-detail.page.ts's record:details block names its sections overview / schedule / details since #22036, reusing objects.showcase_task._sections — and showcase_contact's create and edit forms, whose sections are its four fieldGroups (#36553). QA run #23163 read all three in zh under zh-CN, so the old reading (the record page renders EN in every locale) is stale. ⚠ The named formViews tabbed / wizard / split are reachable from NO console door: `…/showcase_task/view/tabbed` is a LIST-view route and renders the grid (records-forms.form-view-gallery says why), so do not read _sections there", - "acceptance[5]'s CONFIRM half HAS a stock specimen, so it is no longer pin-only (the old reading, QA run #21782's blocked(fixture) 'no zh confirmText', parked on #22017 row 8, is stale): sys_session's revoke_my_other_sessions, a list_toolbar action on the sys_session list (packages/platform-objects/src/identity/sys-session.object.ts; confirmText 'Sign out of every other device where you're currently logged in? Your current session will remain active.'), whose zh-CN entry in platform-objects' bundle (packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts) reads 要退出你当前已登录的其他所有设备吗?当前会话将保持活跃。 with successMessage 其他所有会话已撤销. Read from source at base f68b47ca and since driven live (QA run #33853: as the zh-CN admin with a second session open, the 退出其他设备 toolbar action on /_console/apps/setup/sys_session showed the zh confirm and the zh toast): drive it the same way, capture the confirm and the toast, and record it. No showcase action declares a `confirmText` still, so the showcase's live row is the toast half (e.g. showcase_recalc_estimate's zh successMessage); the unit pins `automated` names stay the copy's pin" + "acceptance[5]'s CONFIRM half HAS a stock specimen, so it is no longer pin-only (the old reading, QA run #21782's blocked(fixture) 'no zh confirmText', parked on #22017 row 8, is stale): sys_session's revoke_my_other_sessions, a list action (the list toolbar) on the sys_session list (packages/platform-objects/src/identity/sys-session.object.ts; confirmText 'Sign out of every other device where you're currently logged in? Your current session will remain active.'), whose zh-CN entry in platform-objects' bundle (packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts) reads 要退出你当前已登录的其他所有设备吗?当前会话将保持活跃。 with successMessage 其他所有会话已撤销. Read from source at base f68b47ca and since driven live (QA run #33853: as the zh-CN admin with a second session open, the 退出其他设备 toolbar action on /_console/apps/setup/sys_session showed the zh confirm and the zh toast): drive it the same way, capture the confirm and the toast, and record it. No showcase action declares a `confirmText` still, so the showcase's live row is the toast half (e.g. showcase_recalc_estimate's zh successMessage); the unit pins `automated` names stay the copy's pin" ] }, "steps": [ @@ -380,6 +380,12 @@ "date": "2026-11-27", "change": "steps[7] and fixtures.knownGaps[2] re-anchored on the contact's field groups. They read the contact's four section headings off ui/views/contact.view.ts's default form and its one create heading (who_is_this, 这是谁) off formViews.create. The internal-form retirement (#36425) stopped the Console loading both, and #36553 deletes them: the contact's create and edit forms are laid out by the object's four fieldGroups (contact / work / status / notes), the create leaving out the fields marked showOnCreate false, and the bundle no longer carries _sections.who_is_this. Revision 13's text stays as the record of what was true at its base. No clause's assertion changed", "ref": "#36553" + }, + { + "revision": 18, + "date": "2026-11-29", + "change": "fixtures.knownGaps (acceptance[5]'s confirm specimen) names revoke_my_other_sessions' location as list, the protocol-19 word it declares in packages/platform-objects/src/identity/sys-session.object.ts (it said list_toolbar, which protocol 19 retired, #36495). The action still draws on the sys_session list toolbar. No clause changed", + "ref": "#38046" } ] }, diff --git a/docs/qa/platform-checklist/areas/platform-core.json b/docs/qa/platform-checklist/areas/platform-core.json index b3e27b52cdc..8f278c862f2 100644 --- a/docs/qa/platform-checklist/areas/platform-core.json +++ b/docs/qa/platform-checklist/areas/platform-core.json @@ -9,17 +9,17 @@ "title": "Showcase boots clean: health + ready 200, no degraded startup banners, console + app metadata served", "since": "v15", "status": "active", - "revision": 15, + "revision": 16, "priority": "P0", "surface": "mixed", "preconditions": [ - "the run's own boot per dogfood-verification §0: own free port (not 3000/3001/3210, checked with lsof), own file DB (--seed-admin -d file:/tmp//data.db)" + "the run's own boot per dogfood-verification §0: own free port (not 3000, not one a tracked .claude/launch.json entry holds, checked with lsof), own file DB (--seed-admin -d file:/tmp//data.db)" ], "steps": [ "boot examples/app-showcase via `objectstack dev --ui --seed-admin -p -d file:/tmp//data.db`", "poll GET http://localhost:/api/v1/health until 200; record time-to-healthy", "GET /api/v1/ready and record the status (the readiness probe is a separate route — packages/runtime/src/route-ledger.ts)", - "read the FULL boot log: capture the Flows: banner, any ⚠ lines, any ERROR-level lines, and the seed outcome. ⚠️ at the default log level (warn) SeedLoader prints NO success line, so a grep for one finds nothing on a healthy boot. Read the ready banner's `Seeds:` row instead — it is immune to the level (packages/runtime/src/seed-summary.ts), e.g. `Seeds: com.example.showcase 138 rows`, and turns yellow with ⚠ and an `N ok / M errors` or `lost links` count when rows were dropped. `--log-level info` additionally prints `[Seeder] Seed loading complete {inserted, updated, skipped, errored}`; a load that dropped records logs `[Seeder] Seed loading completed with N dropped record(s)…` at warn and is visible at either level. `os dev` compiles before it serves (the default since #26130), and the compile prints its author-time lint findings as ⚠ lines first (30 on the stock showcase since #32168, which brought QA run #32135's 76 down; each of the 30 is named, with the reason it stays, in examples/app-showcase/test/author-time-advisories.test.ts, which fails on a new one; a checkout whose Console is not built prints one more, the `sdui/jsx-parse-level-only` info notice that the JSX component check had no manifest to run against, which reports the build state rather than the app): they are build advisories, not boot lines, so start the ⚠ read at the server's startup, after the compile output. Only a compiling boot prints them: they come from the `compile` subprocess `os dev` spawns before it serves, and `--no-compile` skips that subprocess (packages/cli/src/commands/dev.ts, the needsCompile branch), so a `--no-compile` boot, the shape QA runners use over a prebuilt artifact, prints none of the 30, and their absence there is not a finding. ⚠️ /api/v1/health answers 200 as soon as the port is bound, BEFORE the ready banner (`Flows:`, `Seeds:`) is printed (packages/cli/src/commands/serve.ts prints the banner after the bind), so a log cut at the health-green line can stop short of the very lines this step reads: capture the boot log to its own file, wait for the banner's last line (`Press Ctrl+C to stop`), and end the boot window at the first NON-health request the run issues", + "read the FULL boot log: capture the Flows: banner, any ⚠ lines, any ERROR-level lines, and the seed outcome. ⚠️ at the default log level (warn) SeedLoader prints NO success line, so a grep for one finds nothing on a healthy boot. Read the ready banner's `Seeds:` row instead — it is immune to the level (packages/runtime/src/seed-summary.ts), e.g. `Seeds: com.example.showcase 138 rows`, and turns yellow with ⚠ and an `N ok / M errors` or `lost links` count when rows were dropped. `--log-level info` additionally prints `[Seeder] Seed loading complete {inserted, updated, skipped, errored}`; a load that dropped records logs `[Seeder] Seed loading completed with N dropped record(s)…` at warn and is visible at either level. `os dev` compiles before it serves (the default since #26130), and the compile prints its author-time lint findings as ⚠ lines first (44 on the stock showcase: the compile's own summary line read `⚠ 44 author-time warning(s)` in QA run #38417, at ff69bcab, with examples/app-showcase/test/author-time-advisories.test.ts green; it was 30 after #32168 brought QA run #32135's 76 down. That test allow-lists every finding `validate --json` reports, each with the reason it stays, and fails on a new one; a checkout whose Console is not built prints one more, the `sdui/jsx-parse-level-only` info notice that the JSX component check had no manifest to run against, which reports the build state rather than the app): they are build advisories, not boot lines, so start the ⚠ read at the server's startup, after the compile output. Only a compiling boot prints them: they come from the `compile` subprocess `os dev` spawns before it serves, and `--no-compile` skips that subprocess (packages/cli/src/commands/dev.ts, the needsCompile branch), so a `--no-compile` boot, the shape QA runners use over a prebuilt artifact, prints none of the 44, and their absence there is not a finding. ⚠️ /api/v1/health answers 200 as soon as the port is bound, BEFORE the ready banner (`Flows:`, `Seeds:`) is printed (packages/cli/src/commands/serve.ts prints the banner after the bind), so a log cut at the health-green line can stop short of the very lines this step reads: capture the boot log to its own file, wait for the banner's last line (`Press Ctrl+C to stop`), and end the boot window at the first NON-health request the run issues", "GET /_console/ and confirm the console shell HTML is served (200, text/html)", "GET /api/v1/meta/app?id=showcase_app and capture the merged app/nav metadata (?id= matches the App document's NAME, never the package id — ?id=com.example.showcase answers an empty items array, which reads exactly like missing metadata)", "cross-check the nav payload: the grp_data group lists the seeded objects (showcase_project, showcase_task, showcase_account, showcase_contact, showcase_invoice, showcase_field_zoo, …)" @@ -150,6 +150,12 @@ "date": "2026-11-14", "change": "steps[3] says the 30 author-time advisories appear only on a compiling boot (under-specified, card #33330, row 26 of the #32908 close-out ledger, from QA run #32953, whose showcase boots all ran --no-compile --no-watch). packages/cli/src/commands/dev.ts spawns `compile --output ARTIFACT` with inherited stdio only when the boot compiles, so the advisories print from that subprocess; `--no-compile` boots the existing artifact and never runs it. A runner reading a --no-compile boot no longer looks for 30 lines that cannot appear. No clause changed. Read from source at base 87330e89, not driven live", "ref": "#33330" + }, + { + "revision": 16, + "date": "2026-11-29", + "change": "steps[3]'s compile-advisory count re-pointed, 30 → 44 (stale count, card #38426; QA run #38417, at ff69bcab, read the compile's summary line ⚠ 44 author-time warning(s) with examples/app-showcase/test/author-time-advisories.test.ts green). Only the count changed: the ERROR clause of acceptance[2] is untouched, and the false knowledge ERROR that run met is the product defect #38418, not a text re-point. Read from source at base 0c1b2ffe; no product change", + "ref": "#38426" } ] }, @@ -266,7 +272,7 @@ "title": "Seeded admin signs in through the console; the session survives reload and re-authenticates cleanly after expiry", "since": "v15", "status": "active", - "revision": 5, + "revision": 6, "priority": "P0", "surface": "browser", "personas": ["seeded admin (admin@objectos.ai / admin123)"], @@ -275,16 +281,16 @@ "sign in with the seeded admin credentials — drive the React controlled inputs with the native setter + input/change events, or POST the auth endpoint from the page (dogfood skill §4; naive fills submit empty)", "screenshot the post-login shell; capture the first authed API responses", "reload the page; capture the first authed API request after reload", - "expire the session SERVER-side: POST /api/v1/auth/sign-out. Then drive BOTH legs, each scored on its own, in this order: (a) an IN-APP navigation with no reload — click a tile on Home (the Showcase app) or a sidebar link, which the console routes client-side; then (b) a full page RELOAD. They are different code paths and can disagree: the reload reads the session afresh at page load, while the in-app navigation only meets the 401s its data calls answer (QA run #32135: the reload went to /_console/login?redirect=…, the in-app navigation kept the full shell over 'Page Not Found', #32138). ⛔ Do NOT use a clearCookies() gesture: the console authenticates with a bearer token in localStorage under `auth-session-token`, sent as an Authorization header, so clearing cookies expires NOTHING and the shell legitimately keeps rendering authed data — which reads exactly like the dead-shell failure clause 3 exists to catch (this nearly produced a false P0). Clearing localStorage as well is the client-side equivalent", + "expire the session SERVER-side: POST /api/v1/auth/sign-out. Then drive BOTH legs, each scored on its own, in this order: (a) an IN-APP navigation with no reload — click a sidebar link to a page other than the one open, which the console routes client-side (a link to the current page navigates nowhere, and the leg then drives nothing: QA run #38417 met this on its first attempt); then (b) a full page RELOAD. They are different code paths and can disagree: the reload reads the session afresh at page load, while the in-app navigation only meets the 401s its data calls answer (QA run #32135: the reload went to /_console/login?redirect=…, the in-app navigation kept the full shell over 'Page Not Found', #32138). ⛔ Do NOT use a clearCookies() gesture: the console authenticates with a bearer token in localStorage under `auth-session-token`, sent as an Authorization header, so clearing cookies expires NOTHING and the shell legitimately keeps rendering authed data — which reads exactly like the dead-shell failure clause 3 exists to catch (this nearly produced a false P0). Clearing localStorage as well is the client-side equivalent", "observe the console's reaction after EACH leg of steps[4] (redirect to login vs dead shell); screenshot each", "sign in again and verify the console restores a working session on the same route", "negative pass: sign out, then attempt login with a wrong password; capture the auth response and the UI" ], "acceptance": [ { - "clause": "login succeeds and lands in the console shell, not the login form — on stock showcase that is /_console/home, whose layout is the header plus the app launcher and deliberately NO sidebar nav (objectui app-shell HomeLayout)", + "clause": "login succeeds and lands in the console shell, not the login form — on a desktop viewport (768 px and up) that is an app: the reader's last app, else the default app, else the first visible product app, which on a fresh stock showcase boot is the Showcase app (/_console/apps/com.example.showcase/…), drawn with the header, the app's sidebar nav and the avatar menu. The platform home page is retired from 768 px up (objectstack#36732; ui/apps/console/src/components/RootLandingRedirect.tsx resolveDesktopLandingPath, and /_console/home itself redirects into an app there, HomeRoute in ui/apps/console/src/App.tsx); only a phone viewport keeps /home and its app list", "oracle": "screenshot", - "verify": "post-login screenshot shows the header and the launcher; the absent sidebar on /home is the design, never a failure of this clause", + "verify": "the post-login screenshot shows the authed shell (header, sidebar, avatar) and the URL reads /_console/apps/APP/…, not /_console/login; on a desktop viewport a landing on /_console/home is no longer the expected route, and a phone-width run reads /home and its app list instead", "evidence": "screenshot" }, { @@ -327,7 +333,8 @@ { "revision": 2, "date": "2026-08-07", "change": "expanded to deep-test contract: concrete steps, multi-clause acceptance, negatives, variants", "ref": "claude/platform-test-checklist-ocwugl" }, { "revision": 3, "date": "2026-08-18", "change": "corrected step 5's expiry gesture and the clause-2 ?id= example. The console authenticates by bearer token in localStorage (auth-session-token), so the documented clearCookies() gesture expires nothing and leaves a fully authed shell rendering — the exact shape of the c3 failure mode, which nearly produced a false P0 (#9453 CF-8). True expiry is POST /api/v1/auth/sign-out. Also corrected ?id=com.example.showcase to the app name showcase_app (#9334)", "ref": "#9386" }, { "revision": 4, "date": "2026-10-01", "change": "checklist-accuracy findings of QA run #21056: acceptance[2].verify still said 'after clearing cookies', contradicting the rev-3 sign-out in steps[4]; acceptance[0] asked for 'nav + header', but the post-login landing /_console/home renders the header and the launcher with no sidebar by design", "ref": "#21060" }, - { "revision": 5, "date": "2026-11-10", "change": "steps[4], steps[5] and acceptance[3] name both expiry legs. Checklist-accuracy finding of QA run #32135 (at ff04ad81; card #32168): after the server-side sign-out, an in-app navigation and a full reload behave differently — the reload returned to /_console/login?redirect=…, the in-app navigation kept the signed-in shell over 'Page Not Found' (the product defect #32138) — and steps[4] said only 'an authed navigation/API call', so a run could score the clause on whichever leg it happened to drive. Each leg is now driven and screenshotted, and the clause holds only when both return to login. Not loosened: the reload leg passing no longer stands for the in-app one", "ref": "#32168" } + { "revision": 5, "date": "2026-11-10", "change": "steps[4], steps[5] and acceptance[3] name both expiry legs. Checklist-accuracy finding of QA run #32135 (at ff04ad81; card #32168): after the server-side sign-out, an in-app navigation and a full reload behave differently — the reload returned to /_console/login?redirect=…, the in-app navigation kept the signed-in shell over 'Page Not Found' (the product defect #32138) — and steps[4] said only 'an authed navigation/API call', so a run could score the clause on whichever leg it happened to drive. Each leg is now driven and screenshotted, and the clause holds only when both return to login. Not loosened: the reload leg passing no longer stands for the in-app one", "ref": "#32168" }, + { "revision": 6, "date": "2026-11-29", "change": "acceptance[0] (clause and verify) and steps[4] re-pointed (stale text, card #38426; QA run #38417, at ff69bcab, its clause-0 note). Since objectstack#36732 retired the platform home page from 768 px up, a desktop sign-in lands in an app (RootLandingRedirect.tsx resolveDesktopLandingPath; on a fresh stock showcase boot the Showcase app, with its sidebar), not on /_console/home with the launcher and no sidebar, which /home itself now redirects away from on a desktop. steps[4]'s in-app leg clicks a sidebar link to another page, since Home has no tiles to click. No clause weakened: the clause still holds only on the authed shell, never the login form. Read from source at base 0c1b2ffe; no product change", "ref": "#38426" } ] }, { @@ -640,7 +647,7 @@ "title": "The built-in apps a stock boot REGISTERS (Setup / Account) render every merged-nav destination; app-level and entry-level gates are enforced, not errored — and Studio's deliberate absence is asserted, never hunted", "since": "v15", "status": "active", - "revision": 20, + "revision": 21, "priority": "P0", "surface": "browser", "personas": [ @@ -655,7 +662,7 @@ ], "knownGaps": [ "the SSO Providers entry (nav_sso_providers → sys_sso_provider) is contributed ONLY when the external-IdP RP is wired (OS_SSO_ENABLED self-host / cloud planAllowsSso — plugin-auth auth-plugin.ts isSsoWired()). On a stock open-framework boot it is ABSENT by design (not gated-and-erroring); assert its absence, never treat it as a missing surface", - "Studio is NOT registered on a stock boot, by product decision — this is a carve-out to ASSERT, not a fixture to provision. STUDIO_APP is defined (packages/platform-objects/src/apps/studio.app.ts) and packaged (packages/apps/studio, com.objectstack.studio), but both boot paths deliberately skip it with the identical note: '@objectstack/studio is intentionally NOT default-loaded — the console ships a dedicated Studio surface at /_console/studio//, so Studio no longer needs to exist as a navigable app tile' (plugin-dev/src/dev-plugin.ts and cli/src/commands/serve.ts, the ADR-0048 app-package loop in each — both register only setup and account). So ?id=studio answering 200 {\\\"items\\\":[]} is the CORRECT observation on every stock boot, not a showcase-specific gap and not a missing built-in. ⛔ Do not install the package to 'restore' it: that changes what the boot ships and is a maintainer decision, not a run's. The prior wave already walked everything reachable here — Setup 43/43 and Account 7/7 destinations, 50/50 ok, zero pageerror (#9453). Studio's own surfaces are covered by area studio-authoring against /_console/studio, not through a nav tile.", + "Studio is NOT registered on a stock boot, by product decision — this is a carve-out to ASSERT, not a fixture to provision. STUDIO_APP is defined (packages/platform-objects/src/apps/studio.app.ts) and packaged (packages/apps/studio, com.objectstack.studio), but both boot paths deliberately skip it with the identical note: '@objectstack/studio is intentionally NOT default-loaded — the console ships a dedicated Studio surface at /_console/studio/, so Studio no longer needs to exist as a navigable app tile' (plugin-dev/src/dev-plugin.ts and cli/src/commands/serve.ts, the ADR-0048 app-package loop in each — both register only setup and account). So ?id=studio answering 200 {\\\"items\\\":[]} is the CORRECT observation on every stock boot, not a showcase-specific gap and not a missing built-in. ⛔ Do not install the package to 'restore' it: that changes what the boot ships and is a maintainer decision, not a run's. The prior wave already walked everything reachable here — Setup 43/43 and Account 7/7 destinations, 50/50 ok, zero pageerror (#9453). Studio's own surfaces are covered by area studio-authoring against /_console/studio, not through a nav tile.", "Browse Marketplace's catalog comes from the cloud registry (default https://cloud.objectos.ai, DEFAULT_CLOUD_URL; cloud ADR-0009 marketplace plugins). Where the environment denies that egress the surface renders the named state 'Failed to load marketplace' with the cause the server answered: where the control plane cannot be reached at all, the runtime's marketplace proxy answers 502 MARKETPLACE_PROXY_FAILED (packages/cloud-connection/src/marketplace-proxy-plugin.ts) and the page reads 'Failed to load marketplace — The marketplace catalog could not be reached.', the raw transport text behind its More control (ui/packages/app-shell/src/console/marketplace/MarketplacePage.tsx, LoadFailureCause; QA run #25812 read the older 'HTTP 502 · fetch failed'); where an egress proxy answers its own refusal, the runtime forwards it and the page names that body (objectui#11688 — QA run #21056 read the older bare 'Forbidden'): score the catalog content blocked(environment) and the named error as the surface rendering honestly — never as a render failure of this item. The environment the catalog leg needs is a boot whose process can reach the control plane: the default packages/cloud-connection/src/cloud-url.ts#DEFAULT_CLOUD_URL (https://cloud.objectos.ai), or an OS_CLOUD_URL that answers. No CI job drives this item, and the QA sandbox's egress proxy denies the host (QA run #21782, parked on #22017 row 10)" ] }, @@ -663,9 +670,9 @@ "as admin, GET /api/v1/meta/app?id=setup and extract every merged nav destination — Setup is a SHELL of empty group anchors (packages/platform-objects/src/apps/setup.app.ts: group_overview/apps/people_org/access_control/approvals/configuration/diagnostics/integrations/advanced) filled by SETUP_NAV_CONTRIBUTIONS (setup-nav.contributions.ts) plus capability-plugin contributions (plugin-security Positions/Permission Sets, plugin-sharing Sharing Rules/Record Shares, plugin-approvals, plugin-webhooks)", "GET /api/v1/meta/app with NO query first and record the names actually served — a stock boot answers exactly showcase_app, setup, account. Then GET /api/v1/meta/app?id=account (account.app.ts — Profile + Inbox/Security/Developer groups). ⚠️ GET /api/v1/meta/app?id=studio answers 200 {\"items\":[]} on every stock boot and that is the expected result (knownGap): record the absence as an assertion and move on — do NOT install @objectstack/studio to make the step runnable", "as admin, hand-walk each destination in each app. At a window narrower than 1280 px a browser with no choice kept opens Setup and Account with the sidebar collapsed, and from 1280 px expanded (ui/packages/app-shell/src/layout/consoleSidebarRail.ts CONSOLE_SIDEBAR_RAIL_BELOW_WIDTH, ruling 7069868269 on objectstack#36112); a reader's own collapse or expand is kept per browser, on each side of that width. Collapsed, the sidebar is hidden, with no icon column (ruling 6973617688 on objectstack#35062): press the expand button at the page header's left edge, or press Ctrl/⌘+B, which does the same (ruling 7074574380 on objectstack#36112), to put it back beside the page before expanding any group — or rest the pointer on the window's left edge to float the full menu over the page; the float folds back after each chosen entry, so float it again for the next destination. EXPAND every nav group first: some render collapsed by default — Setup's Advanced group and Account's Developer group declare `expanded: false` (packages/platform-objects/src/apps/setup.app.ts, account.app.ts), and QA run #24557 found Setup's Configuration group collapsed as well — so a walk that never expands them never reaches their entries. Then navigate, wait for render, SCREENSHOT FIRST, then read the DOM — assert no pageerror, no 'failed to load', no blank
, no 'no actions configured' placeholder", - "Setup detail: confirm each settings URL entry (nav_settings_* → /apps/setup/system/settings/) opens the settings namespace form — the 10 namespaces of a stock single-posture boot, localization/company/branding/auth/access_policy/mail/sms/storage/ai/lifecycle: the nav_settings_* entries of packages/platform-objects/src/apps/setup-nav.contributions.ts, plus nav_settings_branding, which packages/services/service-settings/src/settings-service-plugin.ts contributes only where no organization wall stands (Knowledge, nav_settings_knowledge, is contributed by packages/services/service-knowledge/src/knowledge-settings-contribution.ts only where the knowledge service is mounted, which no stock app does), and Users / Organization / Business Units / Teams / Sessions / OAuth Applications render. User preferences and identity links are not Setup destinations: open a user's record page, /_console/apps/setup/sys_user/record/ID (a row click on the Users list opens a side panel at ?recordId=, which is not that page: take the id from the row or the panel), and confirm the user page's Preferences and Linked Accounts tabs (packages/platform-objects/src/pages/sys-user.page.ts#SysUserDetailPage) render that user's rows", - "Studio detail is NOT walked from here — the app is not registered on a stock boot (knownGap), so there is no merged nav to render. Its metadata:resource lists and component surfaces (App Builder, All Metadata Types, Packages, API Console, Flow Runs, Public Forms) are reached through the console surface at /_console/studio// and are covered by area studio-authoring. What THIS item asserts about Studio is the absence itself, per clause 6", - "Account detail: confirm Profile (account:profile_card), Notifications (sys_inbox_message/mine), Approvals (nav_account_approvals, the approvals:inbox component, served as …/component/approvals/inbox — the Approvals Inbox, not the sys_approval_request grid; account.app.ts), Linked Accounts (sys_account), Active Sessions (sys_session/mine), API Keys (sys_api_key/mine), OAuth Applications (sys_oauth_application/mine) and Connect an Agent (nav_connect_agent) each render — 8 Account destinations and 46 Setup destinations for the admin on a stock single-org showcase boot, read from source after #33933 took Knowledge (nav_settings_knowledge) out of the stock Setup tree (47 before it, after objectstack#34724 retired Setup › Packaged Actions, nav_packaged_actions, whose switch moved onto the action in Studio); QA runs #32953 (at 5fb79bc0) and #33087 (at 8e3d4a54) read 48 before objectstack#34724 (GET /api/v1/meta/app leaves, which match the nav source minus its gates). QA run #29877 read 46 at 589049b0, before Access policy (nav_settings_access_policy, the access_policy namespace) joined the Configuration group. Since QA run #28545's reading Setup's Packaged automation page retired under ADR-0146 D11, leaving Packaged Actions (nav_packaged_actions, automation:packaged-actions; #28785, itself retired by objectstack#34724), and its unfiltered Packages entry moved to Studio (#29547) (47 for #28927, 50 at eeec88d1 for QA run #28545, 48 re-measured at 3fd80337 for #28338, QA run #27481 read 44 and 8, QA run #24557 read 42 at 5b14b7f3, 45 on 2026-10-01, and #9453 recorded 43 and 7). Recount from the payload each run", + "Setup detail: confirm each settings URL entry (nav_settings_* → /apps/setup/system/settings/) opens the settings namespace form — the 11 namespaces of a stock single-posture showcase boot, localization/company/branding/auth/access_policy/mail/sms/storage/ai/lifecycle/knowledge: the nav_settings_* entries of packages/platform-objects/src/apps/setup-nav.contributions.ts, plus nav_settings_branding, which packages/services/service-settings/src/settings-service-plugin.ts contributes only where no organization wall stands (Knowledge, nav_settings_knowledge, is contributed by packages/services/service-knowledge/src/knowledge-settings-contribution.ts only where the knowledge service is mounted, and the showcase mounts it: KnowledgeServicePlugin in examples/app-showcase/objectstack.config.ts, ADR-0161 K4; QA run #38417, at ff69bcab, read all 11 namespaces), and Users / Organization / Business Units / Teams / Sessions / OAuth Applications render. User preferences and identity links are not Setup destinations: open a user's record page, /_console/apps/setup/sys_user/record/ID (a row click on the Users list opens a side panel at ?recordId=, which is not that page: take the id from the row or the panel), and confirm the user page's Preferences and Linked Accounts tabs (packages/platform-objects/src/pages/sys-user.page.ts#SysUserDetailPage) render that user's rows", + "Studio detail is NOT walked from here — the app is not registered on a stock boot (knownGap), so there is no merged nav to render. Its metadata:resource lists and component surfaces (App Builder, All Metadata Types, Packages, API Console, Flow Runs, and the form designer on the form list) are reached through the console surface at /_console/studio/ and are covered by area studio-authoring. What THIS item asserts about Studio is the absence itself, per clause 6", + "Account detail: confirm Profile (account:profile_card), Mobile App (nav_account_mobile_app), Notifications (sys_inbox_message/mine), Notification Settings (nav_account_notification_settings), Approvals (nav_account_approvals, the approvals:inbox component, served as …/component/approvals/inbox — the Approvals Inbox, not the sys_approval_request grid; account.app.ts), Linked Accounts (sys_account), Active Sessions (sys_session/mine), API Keys (sys_api_key/mine), OAuth Applications (sys_oauth_application/mine) and Connect an Agent (nav_connect_agent) each render — 10 Account destinations and 55 Setup destinations for the admin on a stock single-org showcase boot, as QA run #38417, at ff69bcab, read them served (GET /api/v1/meta/app leaves, which matched the rendered sidebar links one for one). The Account ten are packages/platform-objects/src/apps/account.app.ts's entries less nav_account_memberships (gated on the org-scoping service, absent single-org), with Mobile App and Notification Settings new since the eight, plus Connect an Agent (nav_connect_agent, packages/mcp/src/connect-ui.ts). Setup's 55 include the knowledge service's two entries, nav_settings_knowledge and nav_knowledge_sync_states (packages/services/service-knowledge), now that the showcase mounts that service. Earlier readings: 46 read from source after #33933 took Knowledge (nav_settings_knowledge) out of the stock Setup tree (47 before it, after objectstack#34724 retired Setup › Packaged Actions, nav_packaged_actions, whose switch moved onto the action in Studio); QA runs #32953 (at 5fb79bc0) and #33087 (at 8e3d4a54) read 48 before objectstack#34724 (GET /api/v1/meta/app leaves, which match the nav source minus its gates). QA run #29877 read 46 at 589049b0, before Access policy (nav_settings_access_policy, the access_policy namespace) joined the Configuration group. Since QA run #28545's reading Setup's Packaged automation page retired under ADR-0146 D11, leaving Packaged Actions (nav_packaged_actions, automation:packaged-actions; #28785, itself retired by objectstack#34724), and its unfiltered Packages entry moved to Studio (#29547) (47 for #28927, 50 at eeec88d1 for QA run #28545, 48 re-measured at 3fd80337 for #28338, QA run #27481 read 44 and 8, QA run #24557 read 42 at 5b14b7f3, 45 on 2026-10-01, and #9453 recorded 43 and 7). Recount from the payload each run", "confirm the gated entries resolve to ABSENT-not-erroring for the admin: nav_organizations (requiresService org-scoping) is absent in single-org mode; nav_jwks Signing Keys is ABSENT for EVERY persona, admin included — the entry was removed in #7544 because sys_jwks declares apiEnabled:false, so its list answers OBJECT_API_DISABLED (404) for all callers and no permission gate could prune it; SSO Providers is absent unless OS_SSO_ENABLED (knownGap)", "sign in as the plain member: attempt to open Setup (app name setup) — capture the app-level refusal (App.requiredPermissions setup.access); open Account (declares no requiredPermissions) — capture it opening. Studio is not part of this comparison: it is absent for EVERY persona including the admin, so a member failing to reach it proves nothing about the gate (the same reasoning #7544 applied to nav_jwks)", "as the member, GET /api/v1/meta/app for a reachable app and confirm every manage_platform_settings-gated entry (API Keys, the manage_platform_settings settings URLs) is ABSENT from the member's payload — the server prunes, the client does not merely hide. JWKS is deliberately NOT in this list any more: it is absent for admins too, so finding it absent for a member proves nothing about the gate (#7544)", @@ -699,7 +706,7 @@ { "clause": "the entry-level gate for Setup's permission-gated entries (nav_api_keys, the manage_platform_settings settings URLs) is enforced ONE LEVEL UP as a whole-app refusal: the member cannot obtain the setup app at all, so those entries are unreachable rather than pruned-from-a-served-nav. Assert the app-level absence; do NOT assert an admin-vs-member entry diff on stock fixtures, because there is no member-side Setup nav to diff", "oracle": "api", - "verify": "as the member, GET /api/v1/meta/app?id=setup → 200 {\"items\":[]}: no App document is served, so every entry inside it (including nav_api_keys and the manage_platform_settings settings URLs) is unreachable. ⚠️ Do NOT substitute the account app for this: account is the one app a member CAN obtain and it carries no permission-gated entries at all — every one of its entries is gated by requiresObject/requiresService (nav_account_api_keys → sys_api_key, nav_account_sessions → sys_session, nav_account_linked → sys_account, nav_account_approvals → requiresService approvals, nav_account_memberships → requiresService org-scoping; account.app.ts), which are PRESENCE gates that resolve identically for both personas. Admin and member account navs measured identical (7 vs 7 in #9453; 8 vs 8 re-measured 2026-10-01, nav_connect_agent having joined) — that is the contract behaving as authored and it proves nothing about permission gating, so scoring the clause off it is a false pass. The prior wave recorded the same shape as a named limitation on its own c4 (#9453)", + "verify": "as the member, GET /api/v1/meta/app?id=setup → 200 {\"items\":[]}: no App document is served, so every entry inside it (including nav_api_keys and the manage_platform_settings settings URLs) is unreachable. ⚠️ Do NOT substitute the account app for this: account is the one app a member CAN obtain and it carries no permission-gated entries at all — every one of its entries is gated by requiresObject/requiresService (nav_account_api_keys → sys_api_key, nav_account_sessions → sys_session, nav_account_linked → sys_account, nav_account_approvals → requiresService approvals, nav_account_memberships → requiresService org-scoping; account.app.ts), which are PRESENCE gates that resolve identically for both personas. Admin and member account navs measured identical (7 vs 7 in #9453; 8 vs 8 re-measured 2026-10-01, nav_connect_agent having joined; 10 vs 10 in QA run #38417, at ff69bcab) — that is the contract behaving as authored and it proves nothing about permission gating, so scoring the clause off it is a false pass. The prior wave recorded the same shape as a named limitation on its own c4 (#9453)", "evidence": "the member's empty ?id=setup payload, plus the admin-vs-member account nav comparison shown as the CONTROL that carries no gated entries (not as the gate's proof)" }, { @@ -736,7 +743,7 @@ { "revision": 3, "date": "2026-08-21", - "change": "two corrections from the 17.1.0 sweep, both about premises that fail one level up. (1) B2/Studio: the item named THREE built-in apps, so on stock fixtures it could never exceed partial — c0/c1/c2 were blocked(fixture) for one reason. Verified at source rather than assumed: Studio's absence is a deliberate product decision at the BOOT layer, not a showcase choice — both os dev and os serve carry the identical note that @objectstack/studio is intentionally not default-loaded because the console ships a dedicated Studio surface at /_console/studio//, and each registers only setup and account. Title, fixtures, steps 1/4/7 and clauses 0/1/2 now describe the two apps a stock boot registers; Studio's absence became an assertion with the carve-out recorded in knownGaps, and its surfaces stay covered by area studio-authoring. (2) A4/clause 4: the clause asked for permission-gated ENTRIES to be absent from the member's merged nav, but the member cannot obtain the setup app at all (GET /meta/app?id=setup → 200 items:[]), so no member-side Setup nav exists to diff — the gate is a whole-app refusal, which clause 3 already proves. Reworded for that case, with the account app named explicitly as a non-substitute: every account entry is gated by requiresObject/requiresService, so admin and member navs are identical (7 vs 7) by construction and scoring the clause off that comparison is a false pass (#10236 A4+B2, measured #10257, same shape as #9453's c4)", + "change": "two corrections from the 17.1.0 sweep, both about premises that fail one level up. (1) B2/Studio: the item named THREE built-in apps, so on stock fixtures it could never exceed partial — c0/c1/c2 were blocked(fixture) for one reason. Verified at source rather than assumed: Studio's absence is a deliberate product decision at the BOOT layer, not a showcase choice — both os dev and os serve carry the identical note that @objectstack/studio is intentionally not default-loaded because the console ships a dedicated Studio surface at /_console/studio// (that address family has since retired: the live address is /_console/studio/, landing on its Overview), and each registers only setup and account. Title, fixtures, steps 1/4/7 and clauses 0/1/2 now describe the two apps a stock boot registers; Studio's absence became an assertion with the carve-out recorded in knownGaps, and its surfaces stay covered by area studio-authoring. (2) A4/clause 4: the clause asked for permission-gated ENTRIES to be absent from the member's merged nav, but the member cannot obtain the setup app at all (GET /meta/app?id=setup → 200 items:[]), so no member-side Setup nav exists to diff — the gate is a whole-app refusal, which clause 3 already proves. Reworded for that case, with the account app named explicitly as a non-substitute: every account entry is gated by requiresObject/requiresService, so admin and member navs are identical (7 vs 7) by construction and scoring the clause off that comparison is a false pass (#10236 A4+B2, measured #10257, same shape as #9453's c4)", "ref": "#10236" }, { @@ -840,6 +847,12 @@ "date": "2026-11-24", "change": "steps[3] and steps[5] follow #33933: the knowledge settings page left the stock Setup tree. steps[3] lists the 10 namespaces of a stock single-posture boot (knowledge removed) and names where nav_settings_knowledge comes from now (packages/services/service-knowledge/src/knowledge-settings-contribution.ts, only where the knowledge service is mounted); steps[5] counts 46 Setup destinations, one fewer. No clause weakened. Read from source, not driven live", "ref": "#33933" + }, + { + "revision": 21, + "date": "2026-11-29", + "change": "steps[3] and steps[5] recounted, and acceptance[4].verify's account-nav parity reading extended (stale count, card #38426; QA run #38417, at ff69bcab, read 55 Setup and 10 Account destinations served and rendered). The showcase now mounts the knowledge service (examples/app-showcase/objectstack.config.ts, ADR-0161 K4), so steps[3] lists 11 settings namespaces, knowledge included, and Setup carries nav_settings_knowledge and nav_knowledge_sync_states; the Account app adds Mobile App and Notification Settings. No clause changed. Read from source at base 0c1b2ffe; no product change", + "ref": "#38426" } ] }, diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index 47cbed6ca5b..21b02e6b095 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -90,8 +90,7 @@ "type": "url", "target": "https://example.test/qaact-control", "locations": [ - "list_item", - "record_header" + "record" ] }, { @@ -101,8 +100,7 @@ "type": "url", "target": "https://example.test/qaact-throws", "locations": [ - "list_item", - "record_header" + "record" ], "visible": "qaact_undeclared_root.flag == true" }, @@ -122,7 +120,7 @@ { "step": 2, "call": "GET /api/v1/meta/object/showcase_task, then GET /api/v1/meta/action", - "expect": "the object's actions[] ends with qaact_control [list_item, record_header], qaact_visible_throws [list_item, record_header] with visible {dialect: 'cel', source: 'qaact_undeclared_root.flag == true'}, and qaact_no_locations with NO `locations` key; /meta/action lists the three. If the object does not carry them, nothing later measures anything (the runtime-authored failure shape)", + "expect": "the object's actions[] ends with qaact_control [record], qaact_visible_throws [record] with visible {dialect: 'cel', source: 'qaact_undeclared_root.flag == true'}, and qaact_no_locations with NO `locations` key; /meta/action lists the three. If the object does not carry them, nothing later measures anything (the runtime-authored failure shape)", "source": "packages/objectql/src/registry.ts#attachBoundActions (a code package's standalone action whose objectName is this object is attached to every served read of it)" }, { @@ -134,8 +132,9 @@ ], "teardown": "DELETE /api/v1/marketplace/install-local/com.objectstack.qaact.specimen → 200 with a cleanups list; showcase_task serves its stock actions again. Mandatory even on a throwaway DB (requires[3]); then stop the boot and the console dev server by their recorded PIDs", "knownGaps": [ - "Task Detail's page:header, its ⋯ overflow and its quick-actions bar render the action ids the page lists (examples/app-showcase/src/ui/pages/task-detail.page.ts), so no bound action reaches them: QA Control is absent there too (measured, #26625), and those three surfaces are no evidence for either half. The specimen's evidence comes from the list row menu and the Project Detail Related-tab row menus, where QA Control renders. The list toolbar showed none of the three, but the control declares no list_toolbar placement, so that surface has no positive control in this recipe", - "Proven by one live run (#26625, main 1708115e2f). The action names carry the namespace prefix (qaact_); an unprefixed name was not measured" + "Task Detail's page:header, its ⋯ overflow and its quick-actions bar render the action ids the page lists (examples/app-showcase/src/ui/pages/task-detail.page.ts), so no bound action reaches them: QA Control is absent there too (measured, #26625), and those three surfaces are no evidence for either half. The specimen's evidence comes from the list row menu and the Project Detail Related-tab row menus, where QA Control renders. The list toolbar showed none of the three, but the control declares no list location (it declares record: the record page and each list row), so that surface has no positive control in this recipe", + "Proven by one live run (#26625, main 1708115e2f). The action names carry the namespace prefix (qaact_); an unprefixed name was not measured", + "The inline manifest declares no engines.protocol, so the install converts nothing: a package body with no declared range is registered as sent, never replayed through the protocol conversions (packages/objectql/src/engine-package-registration.ts#convertPackageBodyForward returns it unchanged). Its action locations are spelled in protocol 19's words (record, where they said list_item beside record_header until 19), and any word this recipe carries must be one the running spec accepts. Read from source at d89d3e23; no live run since the rewrite" ] }, "qa-crm-import-console": { @@ -187,7 +186,7 @@ "title": "Create → read → update → delete a record through the console UI", "since": "v15", "status": "active", - "revision": 22, + "revision": 23, "priority": "P0", "surface": "browser", "personas": [ @@ -212,7 +211,7 @@ "click New; fill name with a distinctive value (os-qa-), status=active, and industry: the create form opens with Industry already on Technology (its option is default:true, examples/app-showcase/src/data/objects/account.object.ts), so pick another value if the run wants the field to carry a choice of its own; leave website empty; submit — the create form's button reads 'Create', not 'Save' (ui/packages/plugin-form: form.create / form.update). After the create the console lands on the NEW RECORD's page, not on the list (ui/packages/app-shell/src/console/AppContent.tsx, the objectstack#2604 save invariant: create takes you to the record), so acceptance[3]'s list read at create needs an explicit navigation back to the list and a reload", "capture the create request/response (expect POST /api/v1/data/showcase_account). The payload also carries the select defaults of fields the step leaves untouched — sales_region:'amer' (its AMER option is default:true, examples/app-showcase/src/data/objects/account.object.ts) — so expect that key in the body you diff (QA run #24556)", "re-read server-side: GET /api/v1/data/showcase_account?$filter=[[\"name\",\"=\",\"os-qa-\"]] — field-by-field vs the submitted payload", - "open the record detail; edit exactly one field, annual_revenue, to a new positive number; submit it (an edit form's button reads 'Update'); capture the PATCH /api/v1/data/showcase_account/; re-read the full row via GET /api/v1/data/showcase_account/. annual_revenue is the field because showcase_account has no rule-free TEXT field the later steps can spare: `name` is the key steps[3] and steps[8] filter on, and tax_id, billing_email and churn_reason are each judged by a validation rule (account.object.ts: tax_id_format, billing_email_format, churn_reason_consistency); annual_revenue carries none (its only constraint is the field's min 0). ⛔ Not `hq`: it is a location field (Field.location), whose input takes 'latitude, longitude', and text that is not a coordinate pair clears the stored value while the save still reports success (#32139) — a defect of its own, not this clause's subject", + "open the record detail; edit exactly one field, annual_revenue, to a new positive number; submit it: the record page's Edit opens the page's edit state, whose button reads 'Save' (sys_record_edit_save in ui/packages/app-shell/src/views/RecordDetailView.tsx; 'Update', form.update, labels a form opened in a modal or drawer, not this page). Capture the save's write: PATCH /api/v1/data/showcase_account/ when the edit state carries the record alone, or one POST /api/v1/batch, one transaction, when it carries the page's body tables too (ui/packages/app-shell/src/views/recordEditState.tsx), so listen for both (QA run #38417, at ff69bcab, watched only the data route and caught no write); re-read the full row via GET /api/v1/data/showcase_account/. annual_revenue is the field because showcase_account has no rule-free TEXT field the later steps can spare: `name` is the key steps[3] and steps[8] filter on, and tax_id, billing_email and churn_reason are each judged by a validation rule (account.object.ts: tax_id_format, billing_email_format, churn_reason_consistency); annual_revenue carries none (its only constraint is the field's min 0). ⛔ Not `hq`: it is a location field (Field.location), whose input takes 'latitude, longitude', and text that is not a coordinate pair clears the stored value while the save still reports success (#32139) — a defect of its own, not this clause's subject", "read the record's field-change history on the record page's timeline stream, under its Changes chip (变更). Record page v3 draws no tab named History at any width (#27055). The stream's whole face, with its chips, is the Activity (动态) tab of the record's tab row — Details (详情), one tab per related list in its order (an empty one muted, with no number), Attachments, Approvals (while a request exists), then Activity (动态) last with its count, the tabs that do not fit folded into its 'More N' (更多 N) dropdown (ui/packages/plugin-detail/src/RecordPageColumns.tsx, the tab row; ui/packages/plugin-detail/src/RecordTabRow.tsx; #35595). showcase_account's 'primary' Invoices and Projects tables sit among its details, so its full page never pins the details in a left column (ui/packages/plugin-detail/src/synth/recordPageColumns.ts#recordPagePinsDetails, #35890): the tab row, 详情 first, at every width. Open the stream from its Activity tab or by ?related=timeline (#27524); the right rail and its 最近动态 card are retired (#35890). The stream can lag the update line until a fresh read (QA run #28545): read the change lines on the Activity tab after a reload. Screenshot first, then read the change lines", "clone the record: POST /api/v1/data/showcase_account//clone (optionally with {overrides:{name:'os-qa--clone'}}); capture the 201 result (new id ≠ source, sourceId, record); re-read the clone via GET /api/v1/data/showcase_account/", "RLS probe on clone: as a persona WITHOUT read on the source row (a permission-zoo persona, or a non-owner under owner-RLS), POST the same clone route and capture the refusal — expect 404 RECORD_NOT_FOUND, never a silent duplicate (record blocked(fixture) if no non-reading persona is bound on this boot)", @@ -415,6 +414,12 @@ "date": "2026-11-22", "change": "steps[5] and acceptance[4].verify re-pointed after #35890 retired the right rail: the Overview rail's 最近动态 card is gone and the first tab reads 详情 (Details); showcase_account's 'primary' body tables keep its full page from pinning the details in a left column (recordPagePinsDetails), so the tab row stands at every width. The stream opens from its Activity tab or ?related=timeline. No clause changed. Read from source at base 28ba01fe", "ref": "#36188" + }, + { + "revision": 23, + "date": "2026-11-29", + "change": "steps[4] re-pointed (stale text, card #38426; QA run #38417, at ff69bcab). The record page's Edit opens the page's edit state, whose button reads 'Save' (RecordDetailView.tsx sys_record_edit_save), not 'Update'; and its write is a PATCH of the record alone or one POST /api/v1/batch when the edit state carries the page's body tables (recordEditState.tsx), so a runner listens for both. No clause changed: acceptance[1] is still scored on the full-row reads. Read from source at base 0c1b2ffe; no product change", + "ref": "#38426" } ] }, @@ -2217,10 +2222,10 @@ }, { "id": "records-forms.action-location-matrix", - "title": "Action buttons surface at exactly their declared locations — list toolbar, list row, record header/more/related/section — and each dispatches for real", + "title": "Action buttons surface at exactly their declared locations — list, record (page and row), record_page (button or ⋯), record_row, record_related, record_section, selection — and each dispatches for real", "since": "v15", "status": "active", - "revision": 18, + "revision": 20, "priority": "P1", "surface": "browser", "personas": [ @@ -2229,7 +2234,7 @@ "fixtures": { "app": "showcase", "requires": [ - "the per-location action fleet on showcase_task (examples/app-showcase/src/ui/actions/index.ts): showcase_bulk_reassign (list_item+list_toolbar, flow), showcase_quick_view (list_item, modal), showcase_mark_done (list_item+record_header, a declarative write on the default script route — operation 'update', patch {done: true, progress: 100} — visible 'has(record.done) && record.done != true'), showcase_log_time (record_header+record_related, form), showcase_open_docs (record_more, url), showcase_recalc_estimate (record_section only, api — the Task Detail quick-actions bar's action), showcase_recalc_selection (record_more, api — declares record_more ONLY, which is what keeps it off the toolbar; objectui#3142), showcase_new_task (locations: [] — the fleet's headless specimen, read by the empty-locations probe), showcase_reopen_task (list_item only, operation 'update' patch {done: false}, visible 'has(record.done) && record.done == true' — Mark Done's mirror, so a done task's row menu offers Reopen where a not-done one offers Mark Done; a click on it is refused by the showcase_guard_task_reopen hook by design, which records-forms.script-action-hook-refusal-toast drives)", + "the per-location action fleet on showcase_task (examples/app-showcase/src/ui/actions/index.ts): showcase_bulk_reassign (record_row+list, flow), showcase_quick_view (record_row, modal), showcase_mark_done (record — the record page AND each list row, one word for both; a declarative write on the default script route — operation 'update', patch {done: true, progress: 100} — visible 'has(record.done) && record.done != true'), showcase_log_time (record_page+record_related, form), showcase_archive_task (record_page, script, disabled until the task is done), showcase_open_docs (record_page folded with component 'action:menu', url), showcase_recalc_estimate (record_section, api — the Task Detail quick-actions bar's action; it also declares a folded record_page, for the standard page a phone or the side drawer shows, which the authored Task Detail header leaves out), showcase_recalc_selection (record_page folded with component 'action:menu', api — that single-record placement ONLY, which is what keeps it off the list toolbar; objectui#3142), showcase_new_task (locations: [] — the fleet's headless specimen, read by the empty-locations probe), showcase_reopen_task (record_row only, operation 'update' patch {done: false}, visible 'has(record.done) && record.done == true' — Mark Done's mirror, so a done task's row menu offers Reopen where a not-done one offers Mark Done; a click on it is refused by the showcase_guard_task_reopen hook by design, which records-forms.script-action-hook-refusal-toast drives)", "seeded tasks in both done and not-done states for the CEL visibility both-sides check" ], "provisioning": { @@ -2238,18 +2243,19 @@ }, "knownGaps": [ "NO PIN COVERS A FULL CLAUSE — `automated` was dropped at revision 13, so this P1 item is hand-driven (Tier 2). The two objectui live specs it cited are adjacent: e2e/live/list-row-action-cel.spec.ts opens the first task row's menu and asserts only that at most one Mark Done renders (not both sides of acceptance[3], nor its fail-closed half), and e2e/live/action-modal.spec.ts only that the host's row Edit opens and closes a modal (one dispatch kind of acceptance[2], on no declared action). Tier 1 run #24598 scored every clause not-run on them. Re-add `automated` only with a pin that asserts a full clause.", - "[CLOSED by #22030 (PR #22036, 60ccda5a24), lifted by #22039 — the gap text is rewritten to say where each location now lives] a stock showcase boot hosts all six locations on showcase_task, including the three this gap used to block. record_header and record_more: Task Detail (showcase_task_detail, the record page the console opens for any task), whose first node is a page:header. That header renders the action ids it lists, each placed by its own locations, followed by the host's Edit / Share / Delete. Inline (record_header) on a desktop viewport, where the header's default inline budget is 3 (1 on mobile; a record_header action past the budget folds into ⋯): showcase_mark_done (script, shown only while the task is not done), showcase_log_time (form) and showcase_archive_task (script, disabled until the task is done). Under the ⋯ overflow (record_more without record_header): showcase_open_docs (url) and showcase_recalc_selection (api). The Task Detail quick-actions bar (record_section) names the task's record_section set, showcase_recalc_estimate (api), in examples/app-showcase/src/ui/pages/task-detail.page.ts; no action the header draws is also in the bar, so each action renders once on the page (#27520 row 9). record_related: Project Detail (showcase_project_detail, the record page for any project) → the Related tab (?tab=related), which holds the Tasks related list, a record:related_list for showcase_task through its project FK; open a project that has tasks. It is an authored node, not the synthesizer's strip: the page's tabs override still replaces that strip, and this tab puts the list back with no actions key, so its rows carry showcase_log_time beside the task's list_item actions, and its header renders the list_toolbar action (Reassign…), as in 18.1 (run #25817): that list's own toolbar placement, not an extra one. The Tasks tab beside it is the record:line_items grid, which hosts no record_related action. An expected action missing from one of these hosts is a missing placement, never blocked(fixture). The hosts were read from objectui source at pin a58626c88dc8 and from the served metadata, not from a browser render, so the first run against them is their first browser evidence", + "[CLOSED by #22030 (PR #22036, 60ccda5a24), lifted by #22039 — the gap text is rewritten to say where each location now lives] a stock showcase boot hosts all six locations on showcase_task, including the three this gap used to block (the record header, its ⋯ overflow and the related list). record_page, as buttons and folded: Task Detail (showcase_task_detail, the record page the console opens for any task), whose first node is a page:header. That header renders the action ids it lists, each placed by its own locations and component (showcase_task declares no actionLayout, so no pin or more list rearranges them), followed by the host's Edit / Share / Delete. As buttons (record_page or record, with no component 'action:menu') on a desktop viewport, where the header's default inline budget is 3 (1 on mobile; a button past the budget folds into ⋯): showcase_mark_done (record; shown only while the task is not done), showcase_log_time (form) and showcase_archive_task (script, disabled until the task is done). Under the ⋯ overflow (record_page folded with component 'action:menu', the fold the retired word record_more carried until protocol 19): showcase_open_docs (url) and showcase_recalc_selection (api). showcase_recalc_estimate declares that fold too, but the header's id list leaves it out (examples/app-showcase/test/record-action-location-hosts.test.ts holds the list equal to the task's record / record_page set less the bar's actions), so on the desktop Task Detail it draws only in the bar. The Task Detail quick-actions bar (record_section) names the task's record_section set, showcase_recalc_estimate (api), in examples/app-showcase/src/ui/pages/task-detail.page.ts; no action the header draws is also in the bar, so each action renders once on the page (#27520 row 9). record_related: Project Detail (showcase_project_detail, the record page for any project) → the Related tab (?tab=related), which holds the Tasks related list, a record:related_list for showcase_task through its project FK; open a project that has tasks. It is an authored node, not the synthesizer's strip: the page's tabs override still replaces that strip, and this tab puts the list back with no actions key, so its rows carry showcase_log_time beside the task's row actions (record_row, and record, which covers record_row: Mark Done), and its header renders the task's list action (Reassign…), as in 18.1 (run #25817): that list's own toolbar placement, not an extra one. The Tasks tab beside it is the record:line_items grid, which hosts no record_related action. An expected action missing from one of these hosts is a missing placement, never blocked(fixture). The hosts were read from objectui source at pin a58626c88dc8 and from the served metadata, not from a browser render, so the first run against them is their first browser evidence", "CLOSED by the qaact-placement-specimen recipe (#26625) for acceptance[4] half (a) and acceptance[3]'s fail-closed half. A runtime-authored action is still not joined into the served object's actions[] (QA run #23163 A4: its positive control, the same probe with a location, rendered nowhere), and authoring refuses a throwing `visible` (QA run #26456), so ⛔ do not author either probe at runtime. The recipe installs both specimens through the package loader, whose actions the served object does carry. Score half (a) on qaact_no_locations and the fail-closed half on qaact_visible_throws, each only on a surface where the recipe's qaact_control renders: the list row menu and the Project Detail Related-tab row menus. Task Detail's header, ⋯ overflow and quick-actions bar list their action ids, so the control is absent there and they are no evidence for either half (the recipe's knownGaps[0]). Half (b) stays on showcase_new_task as before." ] }, "variants": [ - "list_toolbar — showcase_bulk_reassign on the task list header", - "list_item — showcase_quick_view / showcase_mark_done in the row menu", - "record_header — showcase_mark_done / showcase_log_time in the detail title bar", - "record_more — showcase_open_docs / showcase_recalc_selection under the ⋯ overflow", + "list — showcase_bulk_reassign on the task list header", + "record — showcase_mark_done on BOTH surfaces the word covers: the row menu and the Task Detail title bar", + "record_page — showcase_log_time / showcase_archive_task as buttons in the Task Detail title bar, and showcase_open_docs / showcase_recalc_selection (component 'action:menu') under its ⋯ overflow, never as buttons", + "record_row — showcase_quick_view / showcase_reopen_task / showcase_bulk_reassign in the row menu, and on no record page", "record_related — showcase_log_time on each row of the related-list section inside a record (the Tasks related list on a showcase_project record), and on no row of the showcase_task list view", "record_section — showcase_recalc_estimate in the Task Detail quick-actions bar (record:quick_actions resolves through the location filter)", - "empty-locations semantics probe — an action with NO locations key renders on NO surface, and `locations: []` likewise (objectui#3142 collapsed the renderers onto one membership predicate, `actionRendersAt`; placement is a declaration, which is why recalc_selection has to name record_more)" + "selection — showcase_mark_done and showcase_recalc_estimate on the multi-select bar of every showcase_task grid view once two rows are selected (objectstack#36496: the actions are placed at selection; no view lists them), and in no list toolbar or row menu by that placement", + "empty-locations semantics probe — an action with NO locations key renders on NO surface, and `locations: []` likewise (objectui#3142 collapsed the renderers onto one membership predicate, `actionRendersAt`; placement is a declaration, which is why recalc_selection has to name record_page)" ], "steps": [ "boot the showcase on its own port and DB; sign in as admin; open the showcase_task list view", @@ -2262,19 +2268,19 @@ ], "acceptance": [ { - "clause": "Per variant, every location the fixture actually HOSTS renders ≥1 action declared for it; record_header/record_more require a showcase_task page that composes a record header and record_related a parent record page that renders the Tasks related list (fixture must provide both).", + "clause": "Per variant, every location the fixture actually HOSTS renders ≥1 action declared for it; record_page (buttons and ⋯) requires a showcase_task page that composes a record header and record_related a parent record page that renders the Tasks related list (fixture must provide both).", "oracle": "dom", - "verify": "after each hosted surface's screenshot confirms render, the DOM read lists the expected action names in that slot; matrix compiled per variant. The stock fixture hosts all six (fixtures.knownGaps names the page and tab for record_header, record_more and record_related): an expected action absent from its host is a missing placement, never blocked(fixture)", + "verify": "after each hosted surface's screenshot confirms render, the DOM read lists the expected action names in that slot; matrix compiled per variant. The stock fixture hosts all six (fixtures.knownGaps names the page and tab for record_page and record_related): an expected action absent from its host is a missing placement, never blocked(fixture)", "evidence": "per-location screenshots + the placement matrix" }, { - "clause": "placement is EXCLUSIVE, not additive: the matrix has zero extra placements — record_more-only actions (open_docs, recalc_selection) never render in record_header or list_toolbar; the engine location-filters even explicitly-named actions (the record:quick_actions bar note in the fixture source)", + "clause": "placement is EXCLUSIVE, not additive: the matrix has zero extra placements — the folded record_page-only actions (open_docs, recalc_selection; component 'action:menu') never render as title-bar buttons or on the list toolbar, and the record_row-only ones (quick_view, reopen_task) never render on the Task Detail page; the engine location-filters even explicitly-named actions (the record:quick_actions bar note in the fixture source)", "oracle": "dom", "verify": "the placement matrix's extra-placement cells are all empty, checked against every captured surface", "evidence": "the same matrix, extra-placement columns" }, { - "clause": "each HOSTED location's sampled action DISPATCHES for real — flow wizard opens and resumes, modal opens, script executes, form opens the declared edit form view, url navigates, api POSTs — and state-changing ones round-trip server-side (mark_done flips done; recalc updates the estimate). The url (open_docs) and api (recalc_selection) legs live on record_more, under the ⋯ overflow of the Task Detail title bar", + "clause": "each HOSTED location's sampled action DISPATCHES for real — flow wizard opens and resumes, modal opens, script executes, form opens the declared edit form view, url navigates, api POSTs — and state-changing ones round-trip server-side (mark_done flips done; recalc updates the estimate). The url (open_docs) and api (recalc_selection) legs live on the folded record_page (component 'action:menu'), under the ⋯ overflow of the Task Detail title bar", "oracle": "network", "verify": "one captured dispatch per location + API re-reads for the two state changes", "evidence": "the six traces + the two re-reads" @@ -2286,7 +2292,7 @@ "evidence": "the four reads + screenshots" }, { - "clause": "empty/missing locations means NO location — the probe action with no `locations` key renders on none of the six surfaces, and the headless `locations: []` declaration (showcase_new_task) renders on none either. Placement is a declaration, not a default: objectui#3142 collapsed four disagreeing renderers onto the single `actionRendersAt` predicate, a plain membership test, so an undeclared or empty list matches nothing. recalc_selection names record_more for that reason — an explicit single-record placement that also keeps it off the toolbar, where a dispatch would carry no selection and the endpoint would reject it — NOT to opt out of an everywhere-default", + "clause": "empty/missing locations means NO location — the probe action with no `locations` key renders on none of the six surfaces, and the headless `locations: []` declaration (showcase_new_task) renders on none either. Placement is a declaration, not a default: objectui#3142 collapsed four disagreeing renderers onto the single `actionRendersAt` predicate, a plain membership test, so an undeclared or empty list matches nothing. recalc_selection names record_page (folded with component 'action:menu') for that reason — an explicit single-record placement that also keeps it off the toolbar, where a dispatch would carry no selection and the endpoint would reject it — NOT to opt out of an everywhere-default", "oracle": "dom", "verify": "both six-surface DOM sweeps (the qaact-placement-specimen recipe's packaged locations-less qaact_no_locations, and showcase_new_task) come back with an empty placement list, half (a) counted only on the surfaces where the recipe's qaact_control renders; recalc_selection is present under ⋯ and absent from the toolbar. Without the recipe half (a) scores blocked(fixture) (knownGaps) and the clause is judged on half (b) plus the recalc_selection read; a runtime-authored probe's empty sweep is never evidence for half (a)", "evidence": "the two empty placement lists + the toolbar DOM read" @@ -2417,12 +2423,24 @@ "date": "2026-11-01", "change": "The Task Detail page draws each task action once (#27520 row 9: the walkthrough saw Mark Done, Log Time and Archive both in the header and as a button row in the body). The quick-actions bar now carries the task's record_section set alone, showcase_recalc_estimate, which declares record_section only, and Mark Done, Log Time and Archive drop record_section. fixtures.requires[0], the record_section variant and knownGaps[1] re-pointed: record_section is still hosted on showcase_task, by Recalculate Estimate in the bar, and the ⋯ overflow keeps open_docs (url) and recalc_selection (api). Read from the examples source at this branch, not a browser run; no clause changed", "ref": "#27520" + }, + { + "revision": 19, + "date": "2026-11-29", + "change": "Re-derived for protocol 19's location words (#36495; ACTION_LOCATIONS in packages/spec/src/ui/action.zod.ts), read off the showcase fleet as it now declares them and off objectui's placement predicate (ui/packages/types/src/ui-action.ts actionRendersAt: record answers both record_page and record_row; a folded action is component 'action:menu'). The variants matrix is the six new words: list (bulk_reassign), record (mark_done, on the row menu and the title bar), record_page (log_time and archive_task as buttons; open_docs and recalc_selection folded under ⋯), record_row (quick_view, reopen_task, bulk_reassign), record_related and record_section unchanged. The title, fixtures.requires[0], knownGaps[1], the probe variant and acceptance[0], [1], [2], [4] say the same. Corrections the re-read found: showcase_recalc_estimate declares a folded record_page beside record_section (the authored header's id list leaves it out, so the desktop page draws it in the bar only); archive_task joins the fleet list; showcase_task declares no actionLayout. Until 19 the words were list_toolbar, list_item, record_header and record_more. No clause's assertion changed beyond the vocabulary", + "ref": "#38046" + }, + { + "revision": 20, + "date": "2026-11-29", + "change": "ACTION_LOCATIONS gains its seventh word, selection (#36496): an action placed there is drawn on the multi-select bar of every grid view of its object, in the order the object's actionLayout.selection gives, and a list view's bulkActions is retired. The variants matrix adds the selection leg (showcase_mark_done and showcase_recalc_estimate, which the showcase now places at selection instead of listing them on the task bulk_actions view), the title names it, and enumSource.expect is 7. No other clause changed; the selection leg is not yet browser-run", + "ref": "#36496" } ], "enumSource": { "file": "packages/spec/src/ui/action.zod.ts", "export": "ACTION_LOCATIONS", - "expect": 6 + "expect": 7 } }, { @@ -6316,7 +6334,7 @@ "title": "A script action whose server-side hook refuses the write with a user-facing sentence answers a 4xx, the console shows exactly one error toast carrying that sentence, and the record is left unchanged", "since": "v17.5", "status": "active", - "revision": 5, + "revision": 6, "priority": "P2", "surface": "browser", "personas": [ @@ -6325,7 +6343,7 @@ "fixtures": { "app": "showcase", "requires": [ - "the refusal pair on showcase_task: the hook showcase_guard_task_reopen (examples/app-showcase/src/data/hooks/index.ts — beforeUpdate, condition previous.done == true && record.done != true, sandboxed body throws new Error(TASK_REOPEN_REFUSAL), onError:'abort') and the action showcase_reopen_task (examples/app-showcase/src/ui/actions/index.ts — a declared record write: operation 'update' with patch { done: false } and no body, which the action route performs as the caller, execution perRecord, visible 'has(record.done) && record.done == true', locations list_item only — the Task Detail page is kind:'full' and renders no record_header bar)", + "the refusal pair on showcase_task: the hook showcase_guard_task_reopen (examples/app-showcase/src/data/hooks/index.ts — beforeUpdate, condition previous.done == true && record.done != true, sandboxed body throws new Error(TASK_REOPEN_REFUSAL), onError:'abort') and the action showcase_reopen_task (examples/app-showcase/src/ui/actions/index.ts — a declared record write: operation 'update' with patch { done: false } and no body, which the action route performs as the caller, execution perRecord, visible 'has(record.done) && record.done == true', locations record_row only — so the task list's row menu offers it, and the Task Detail title bar, whose page:header lists its action ids and leaves this one out, does not)", "the refusal sentence, verbatim: 'A finished task cannot be reopened. Create a follow-up task instead.' (TASK_REOPEN_REFUSAL in the hooks file — re-read it there before the run, never from this line)", "a seeded FINISHED task (done: true) — 'Audit current IA' or 'App wireframes' (examples/app-showcase/src/data/seed/index.ts) — which is the only kind of record the action is offered on", "a console built from this checkout's ui/ tree (pnpm console:build, which copies ui/apps/console's build into packages/console/dist), served by the same boot the run drives", @@ -6424,6 +6442,12 @@ "date": "2026-10-26", "change": "fixtures.knownGaps[0] said the console-half pin lives in the objectui repo and is not runnable from this checkout; it is at ui/packages/app-shell/src/utils/__tests__/consoleServerAction.errorToast.test.ts and runs from ui/ with that package's vitest, so the note says where it is and how it runs, and still says it stubs fetch and the toast sink and is not this item's evidence (devx seat 2 REVISE on #26125). Re-read on main cc378e93. No clause changed", "ref": "#25846" + }, + { + "revision": 6, + "date": "2026-11-29", + "change": "fixtures.requires[0] names showcase_reopen_task's protocol-19 location, record_row (it said list_item, a word protocol 19 retired, #36495), and drops the stale reason beside it: the Task Detail page (kind 'full') does compose a page:header now, which lists its action ids and leaves Reopen out (examples/app-showcase/src/ui/pages/task-detail.page.ts), so the row menu is still the one place it is offered. No clause changed", + "ref": "#38046" } ] }, @@ -7260,7 +7284,7 @@ "title": "An action's param dialog runs its declared preflight read: the panel moves from loading to ready with the declared fields, a seeded param is drawn read-only from the answer and submitted as it, and a failed read draws the error panel, leaves the seed empty and holds Confirm", "since": "v18.4", "status": "active", - "revision": 4, + "revision": 5, "priority": "P1", "surface": "browser", "personas": [ @@ -7270,13 +7294,13 @@ "app": "showcase", "requires": [ "a fresh boot of the showcase: `pnpm dev -- --fresh -p PORT --seed-admin`", - "two scratch actions on showcase_task, saved before the browser leg. qa_pf_probe: PUT /api/v1/meta/action/qa_pf_probe with { name: 'qa_pf_probe', label: 'QA preflight probe', objectName: 'showcase_task', operation: 'update', execution: 'perRecord', locations: ['record_header'], params: [{ name: 'estimate_hours', label: 'Estimate (h)', type: 'number', required: true }, { name: 'notes', label: 'Notes', type: 'textarea', required: true }], preflight: { read: { url: '/api/v1/data/showcase_task/${ctx.recordId}' }, path: 'record', fields: [{ path: 'title', label: 'Title' }, { path: 'status', label: 'Status' }], seed: [{ param: 'notes', path: 'title' }] } }. qa_pf_fail: the same body named qa_pf_fail, labelled 'QA preflight fail', with read.url '/api/v1/data/showcase_task/qa-missing-${ctx.recordId}' (a record that does not exist, so the read answers 404)", + "two scratch actions on showcase_task, saved before the browser leg. qa_pf_probe: PUT /api/v1/meta/action/qa_pf_probe with { name: 'qa_pf_probe', label: 'QA preflight probe', objectName: 'showcase_task', operation: 'update', execution: 'perRecord', locations: ['record_page'], params: [{ name: 'estimate_hours', label: 'Estimate (h)', type: 'number', required: true }, { name: 'notes', label: 'Notes', type: 'textarea', required: true }], preflight: { read: { url: '/api/v1/data/showcase_task/${ctx.recordId}' }, path: 'record', fields: [{ path: 'title', label: 'Title' }, { path: 'status', label: 'Status' }], seed: [{ param: 'notes', path: 'title' }] } }. qa_pf_fail: the same body named qa_pf_fail, labelled 'QA preflight fail', with read.url '/api/v1/data/showcase_task/qa-missing-${ctx.recordId}' (a record that does not exist, so the read answers 404)", "`path` selects the record in the read's answer: run `GET /api/v1/data/showcase_task/ID` once with curl. GetDataResponseSchema answers `{ object, id, record }`; if the door wraps it in `{ success, data }`, save both actions with path 'data.record' instead of 'record' (packages/spec/src/api/protocol.zod.ts#GetDataResponseSchema)", "one seeded showcase_task with a title; record its id, title and estimate_hours" ], "knownGaps": [ "the panel's `waiting` state (a URL hole on a param not yet filled), a stale answer dropped after the URL moved on, and the seed cleared on a URL change have no live leg here: a `${param.X}` hole needs a query parameter the record read accepts, and GET /api/v1/data/OBJECT/ID refuses every parameter but select and expand (packages/rest/src/rest-server.ts#DATA_RECORD_READ_PARAMS). acceptance[4] scores them from the pins", - "the two scratch actions draw NO button on a showcase_task record page as stock ships it: that object's default record page is a custom page (examples/app-showcase/src/ui/pages/task-detail.page.ts, isDefault) whose page:header lists its header actions BY ID, so a runtime action declaring location record_header is not drawn there (QA run #32940; #33094 comment 6852480973). The fixture needs the actions on a record page that draws them: an object served by the synthesized default record page (no isDefault page in examples/app-showcase/src/ui/pages), with the read URL, path and fields re-pointed to it, or the task page's header list extended by a metadata overlay for the run and reverted afterwards (the shape the 18.4.0 round 2 run passed on). Record which one the verdict rests on" + "the two scratch actions draw NO button on a showcase_task record page as stock ships it: that object's default record page is a custom page (examples/app-showcase/src/ui/pages/task-detail.page.ts, isDefault) whose page:header lists its header actions BY ID, so a runtime action declaring location record_page is not drawn there (QA run #32940; #33094 comment 6852480973). The fixture needs the actions on a record page that draws them: an object served by the synthesized default record page (no isDefault page in examples/app-showcase/src/ui/pages), with the read URL, path and fields re-pointed to it, or the task page's header list extended by a metadata overlay for the run and reverted afterwards (the shape the 18.4.0 round 2 run passed on). Record which one the verdict rests on" ] }, "steps": [ @@ -7363,6 +7387,12 @@ "date": "2026-11-15", "change": "acceptance[4].verify names `--reporter=tree`, the reporter that prints the one line per pin file this is scored on: in a runner's non-TTY shell vitest's default reporter prints the run's totals only (RUNNER.md's environment facts; QA run #33784's note 10, comment 6893243542). No clause or threshold changed. Card #33969", "ref": "#34068" + }, + { + "revision": 5, + "date": "2026-11-29", + "change": "fixtures.requires[1]'s two scratch bodies (qa_pf_probe, qa_pf_fail) declare locations ['record_page'], and fixtures.knownGaps[1] names that word, where both said record_header. Protocol 19 retired the page-part location words (record_header or record_more became record_page, the 19 conversion action-locations-acted-on), and a body sent to the save door is not converted, so a body that still sends record_header is refused and this item's provisioning fails before the browser leg. Where the actions draw is unchanged. No clause or threshold changed", + "ref": "#38046" } ] }, @@ -7660,7 +7690,7 @@ "title": "An object's list opens a record one way — the name opens the full page, the hover icon beside it the side drawer — and the record's header is two rows: the way through the list (↑ ↓, 「第 N 条,共 M 条 · 视图名」, ✕) over the record (its name, chips and up to three actions), with the tabs right under it", "since": "v18.7", "status": "active", - "revision": 1, + "revision": 2, "priority": "P1", "surface": "browser", "personas": [ @@ -7670,7 +7700,7 @@ "app": "showcase", "requires": [ "a fresh boot of the showcase (the live lane's `ui/e2e/live/ci/start-backend.sh`, or `pnpm dev -- --fresh --seed-admin`)", - "the showcase_account list (14 seeded accounts, a synthesized record page with a tab row) and the showcase_task list (its showcase_task_detail page authors three record_header actions: Mark Done, Log Time, Archive)" + "the showcase_account list (14 seeded accounts, a synthesized record page with a tab row) and the showcase_task list (its showcase_task_detail page's header draws three record-page buttons: Mark Done at record, Log Time and Archive at record_page; Open Docs and Recalculate Selection are folded under ⋯)" ] }, "steps": [ @@ -7762,6 +7792,12 @@ "date": "2026-11-20", "change": "initial — the one open path (#35854, maintainer ruling 「废弃」 on the open preference and navigation.mode) and the two-row record header (#35853, with the gap above the tabs of #35745), read from the PR branch and driven live against the showcase", "ref": "#35854" + }, + { + "revision": 2, + "date": "2026-11-29", + "change": "fixtures.requires[1] names the task page's header actions in protocol 19's words (#36495): Mark Done is placed at record, Log Time and Archive at record_page, and the two folded record_page actions sit under ⋯ (it said three record_header actions, a retired word). Read from examples/app-showcase/src/ui/pages/task-detail.page.ts and src/ui/actions/index.ts. No clause changed", + "ref": "#38046" } ] } diff --git a/docs/qa/platform-checklist/areas/studio-authoring.json b/docs/qa/platform-checklist/areas/studio-authoring.json index 0dba0e9d50d..e18693b1ebc 100644 --- a/docs/qa/platform-checklist/areas/studio-authoring.json +++ b/docs/qa/platform-checklist/areas/studio-authoring.json @@ -9,7 +9,7 @@ "title": "The first-run authoring loop closes: package → object → record → app → publish → end-user, zero code, zero restarts", "since": "v16", "status": "active", - "revision": 16, + "revision": 17, "priority": "P0", "surface": "mixed", "personas": ["admin (seeded admin@objectos.ai)", "end user (same account driving the published app)"], @@ -19,20 +19,20 @@ "a fresh boot of the showcase example — objectstack dev --ui --seed-admin -p -d file:/tmp//data.db (the audit's environment: a console built from this tree with `pnpm console:build`, seeded admin admin@objectos.ai/admin123). Run the loop TWICE, one leg per locale, each on its own fresh boot and DB so every name the steps use stays the same: an en leg and a zh-CN leg, the admin's locale set through the avatar-menu language switcher right after sign-in (it writes the user's locale; seeding browser storage alone is not a switch, i18n.studio-follows-app-locale steps[0]). Name both legs in the run record" ], "knownGaps": [ - "SUPERSEDED (QA run #24571): publish is no longer one click with no confirmation. Publish opens the 'Pending changes' review sheet — every pending draft listed as New or Update, each expanding into the keys it changes, and a separate 'Publish all' confirm (objectui app-shell preview/DraftChangesPanel.tsx, mounted by StudioDesignSurface.tsx; the audit's finding 3 / ADR-0016 §3.6 step 4). A review step now exists; do not score its presence or absence here — this item scores the loop", - "SUPERSEDED (QA run #21056): a new app no longer scaffolds zero nav items — the Create-app dialog seeds the app's navigation from the package's objects behind a checkbox that defaults ON (objectui StudioDesignSurface appAddObjects, objectui#2262). With it on, step 5's nav item already exists; with it unticked, the entry is wired by hand in the running app's design mode (the menu editor), since Studio's Interfaces pillar, where it was wired before, retired with #36502. Do not expect zero items", + "SUPERSEDED AGAIN (QA run #38417, at ff69bcab): on this loop's path there is no review sheet at all, since the object dialog's Create and the page's Save each publish the item they write (steps[2], steps[3]). The earlier reading, kept for the record: SUPERSEDED (QA run #24571): publish is no longer one click with no confirmation. Publish opens the 'Pending changes' review sheet — every pending draft listed as New or Update, each expanding into the keys it changes, and a separate 'Publish all' confirm (objectui app-shell preview/DraftChangesPanel.tsx, mounted by StudioDesignSurface.tsx; the audit's finding 3 / ADR-0016 §3.6 step 4). A review step now exists; do not score its presence or absence here — this item scores the loop", + "SUPERSEDED AGAIN (QA run #38417, at ff69bcab): Studio's Application → New is the generic metadata form and carries no objects-as-menu-items checkbox, so the new app starts with an empty navigation (advisory app-navigation-empty) until steps[5] wires the entry by hand in its Preview → Add nav item. The earlier reading, kept for the record: SUPERSEDED (QA run #21056): a new app no longer scaffolds zero nav items — the Create-app dialog seeds the app's navigation from the package's objects behind a checkbox that defaults ON (objectui StudioDesignSurface appAddObjects, objectui#2262). With it on, step 5's nav item already exists; with it unticked, the entry is wired by hand in the running app's design mode (the menu editor), since Studio's Interfaces pillar, where it was wired before, retired with #36502. Do not expect zero items", "mixed-language Studio chrome (audit finding 4) is asserted by i18n.studio-follows-app-locale — locale consistency is that item's business, not this one's", "FIXED, regression row, expected PASS on the zh-CN leg (#29673, closed by PR #29790, merged as 589049b0; pins packages/metadata-protocol/src/protocol-translated-echo.test.ts and packages/qa/dogfood/test/studio-zh-cn-echo-publish.dogfood.test.ts): an object saved back from a translated /meta read now stores its source labels, so an object first published from Studio in zh-CN reaches the data plane. QA run #29877 (W5-P0, at 589049b0) read the zh-CN leg passing acceptance[2] and [3]: publish answered published, the list served, the overlay carried no queue / owner_id, and an en read showed Owner / Queue. Score both legs normally; a zh-CN publish that answers published while the data read answers 404 OBJECT_NOT_FOUND is a regression of #29673. The failure as it was: The draft read serves the injected queue column with its translated label (队列), the autosave echoes it, the registry judges the echo byte for byte against the platform's definition (isInjectedColumnDefinition, packages/spec/src/data/injected-system-column-provenance.ts) and refuses it as an author's field named queue, and the failed registration is only a console.warn (the registerObject catch in packages/metadata-protocol/src/protocol.ts). Publish answers published while GET /api/v1/data/repairs_repair_ticket answers 404 OBJECT_NOT_FOUND. Re-read unchanged at base 339f63da30, before the fix" ] }, "steps": [ "boot the showcase example (objectstack dev --ui --seed-admin -p -d file:/tmp//data.db), sign in as admin@objectos.ai/admin123, and note the boot timestamp in the server log (the zero-restart clause reads it later). Run steps[0] to [8] once per locale leg (fixtures.requires[0]): the en leg, then the zh-CN leg, each switched with the avatar-menu language switcher right after sign-in", - "Home → the build chip → create a NEW writable package (维修中心 / com.example.repairs, namespace repairs) via the new-package wizard. Type the identifier yourself: since #29734 a Chinese display name derives its id through pinyin (维修中心 gives com.ORG.weixiu-zhongxin, deriveCreatePackageId in ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.tsx), which is not the id the later steps name, and the namespace derives from the id you type. The build chip has two forms (ui/packages/app-shell/src/console/home/HomePage.tsx): where the agent catalog serves the build agent it reads 'Build an app' (data-testid home-build-app) and opens Studio on the last package you worked in, or Setup → Packages when there is none, where New package opens the wizard; otherwise it reads 'New blank app' (home-build-in-studio) and opens Setup → Packages with the New package dialog already open (the form QA run #27481 met on the stock showcase, then labelled 'New in Studio'). A sign-in without Setup access (setup.access + manage_platform_settings) is sent to Studio's All metadata area instead, which creates no package; use the dev admin. Either way the create lands in Studio on the new package. Record which", - "Data pillar → new object 'Repair Ticket' (the identifier auto-suggests repair_ticket from the display name, and the dialog PREFIXES it with the package namespace, so the object is named repairs_repair_ticket — the name every later step and clause uses (framework#2694, objectui StudioDesignSurface prefixObjectName). The dialog also carries an OWD (sharing model) choice, pre-selected to the platform's recommended baseline: confirm or change it, then click 'Save as draft', the dialog's confirm button (engine.studio.createDraft; no Studio create dialog has a button named Create)) → add a picklist field Status with 3 values. After a navigation the object surface opens on its Records tab (the Data pillar's default view, ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx); Add field is the Field layout tab's (字段布局, formerly Form) button (where QA run #28545 found it; the Records grid's add-column header carries it too). Each option's stored value derives from its label as you type it — 'In Repair' stores in_repair (ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx OptionsEditor) — so overwrite the value wherever the run wants a different one (a short code such as wip), and note the three stored values: acceptance[1] and acceptance[2] read them. There is no Save draft button: the designer autosaves, and a picklist field is held unsaved until it has at least one option (the status line reads 'Not saved yet: the field “Status” needs at least one option'), so add the field and fill its options, and the draft save fires", - "open the Changes panel and Publish, then confirm with 'Publish all' in the review sheet; the toast names the count — 'Published N items in this package' (N = the drafts promoted), 'Published 1 item in this package' for one (engine.studio.publishedAllCount / publishedAllCountOne, objectui#11807; 'Published all drafts in this package' is the fallback when the count is unknown) — and, because the publish puts an object live, it adds 'Members can use it once a permission set grants them access.' with an 'Open Access' action (StudioDesignSurface.tsx)", + "the app switcher (the sidebar's app menu) → Add app → 'New blank app' (新建空白应用) opens Setup → Packages with the New package dialog already open (ui/packages/app-shell/src/hooks/useAddAppEntries.ts and useNewPackageDoorPath.ts). There is no Home build chip on this path: the platform home page is retired from 768 px up (objectstack#36732), and objectstack#36908 took 'Build with AI' off that menu. Create a NEW writable package there (维修中心 / com.example.repairs, namespace repairs), leaving 'Also create an app' unticked: steps[5] creates the app. Type the identifier yourself: since #29734 a Chinese display name derives its id through pinyin (维修中心 gives com.ORG.weixiu-zhongxin, deriveCreatePackageId in ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.tsx), which is not the id the later steps name, and the namespace derives from the id you type. A sign-in without Setup access (setup.access + manage_platform_settings) is sent to Studio's All metadata area instead, which creates no package; use the dev admin. The create lands in Studio on the new package (/_console/studio/com.example.repairs/metadata/object, QA run #38417, at ff69bcab)", + "in App Studio's left menu, New object 'Repair Ticket' (the identifier auto-suggests repair_ticket from the display name, and the dialog PREFIXES it with the package namespace, so the object is named repairs_repair_ticket — the name every later step and clause uses, framework#2694). The dialog also carries an OWD (sharing model) choice, pre-selected to the platform's recommended baseline: confirm or change it, then click 'Create' (创建), the dialog's confirm (engine.studio.createLive), which writes the object as a draft and publishes it at once, a PUT …?mode=draft followed by POST …/publish (ui/packages/app-shell/src/views/metadata-admin/MetadataListCreateDialog.tsx, publishSavedItem); the dialog has no 'Save as draft' confirm any more. Then add a picklist field Status with 3 values. The object opens on its own tabs, Records / Field layout (字段布局) / Advanced / … (engine.studio.data.tab.*; there is no menu entry named Data pillar); Add field is the Field layout tab's button (the Records grid's add-column header carries it too). Each option's stored value derives from its label as you type it — 'In Repair' stores in_repair (ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx OptionsEditor) — so overwrite the value wherever the run wants a different one (a short code such as wip), and note the three stored values: acceptance[1] and acceptance[2] read them. The designer does not autosave: the page's Save, drawn in the item header while an edit is unsaved, writes each edited item's draft and then that item's own publish (ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx), and it refuses, naming what is missing, while a picklist field has no option; so add the field, fill its options, then press Save", + "confirm what is live. On this path nothing is left to publish: the object dialog's Create and the page's Save each publish the item they write, so there is no Changes panel and no 'Publish all' review sheet to drive (QA run #38417, at ff69bcab, met neither). Read the publish from the server, never from a toast: steps[7]'s GET /api/v1/meta/object/repairs_repair_ticket serves the object with its Status options", "create a record in the runtime-faithful Records grid with a Status value chosen", - "Create app 'Repair Center' (identifier auto-suggested), leaving 'Add this package's objects as menu items' on, so the app's navigation holds an entry bound to repairs_repair_ticket; the dialog stays on the Data pillar → Publish", - "return to the console Home (/_console/home — the Studio header's house icon goes to the Studio landing, 'Studio home', and from the landing the console Home is its top bar's product mark, the link named 'PRODUCT home' (e.g. 'ObjectOS home'; data-testid app-bar-product-home, ui/packages/app-shell/src/layout/AppHeader.tsx ProductHomeMark), which goes to the deployment's home path, /_console/home on stock; no control on that bar is named plain 'Home'): the launcher must show Repair Center; open it and drive the end-user list", + "create the app 'Repair Center': App Studio's Application → New opens the generic metadata form (Name / Label / Description / Active / Is Default), which has no 'Add this package's objects as menu items' option, so the app is born with an empty navigation and its save answers the advisory app-navigation-empty. Switch Active on (QA run #38417, at ff69bcab, found it off by default) and save; then wire the entry by hand in the app's Preview → 'Add nav item' (engine.inspector.add.nav), type Object → Repair Ticket, and save again: that publish carries a navigation entry bound to repairs_repair_ticket", + "open the app switcher (the sidebar's app menu): it must list Repair Center beside Showcase and Setup (on a desktop the platform home page and its launcher are retired, objectstack#36732, so the switcher is where a new app shows); open it and drive the end-user list (/_console/apps/com.example.repairs/repairs_repair_ticket)", "verify server truth after each publish: GET /api/v1/meta/object/repairs_repair_ticket, GET /api/v1/data/repairs_repair_ticket, GET /api/v1/meta/app?id= — ?id= matches the App document name, NOT the package id com.example.repairs; fetch /api/v1/meta/app with no query first to read the name the wizard actually minted", "negative probe: on the READ-ONLY com.example.showcase package there is no gesture to drive — the console HIDES New object and Add field there (objectui StudioDesignSurface gates them on !readOnly) — so the probe is a FORGED request: send the authoring write the gesture would have made straight to the metadata write door against that package, and capture the server response (QA run #21056 read 422 WRITABLE_PACKAGE_REQUIRED and 403 ITEM_LOCKED)" ], @@ -56,9 +56,9 @@ "evidence": "the data read" }, { - "clause": "the published app is live in the Home launcher and the end-user list renders the record with the picklist LABEL chip (label resolution, not the raw value)", + "clause": "the published app is live in the app switcher and the end-user list renders the record with the picklist LABEL chip (label resolution, not the raw value)", "oracle": "screenshot", - "verify": "launcher screenshot shows Repair Center; end-user list screenshot shows the record row with the label chip; GET /api/v1/meta/app?id= carries the nav item bound to the object", + "verify": "the app-switcher screenshot shows Repair Center; end-user list screenshot shows the record row with the label chip; GET /api/v1/meta/app?id= carries the nav item bound to the object", "evidence": "the two screenshots + the app meta read" }, { @@ -76,7 +76,7 @@ ], "negative": [ "silent acceptance of an authoring write into a read-only package is a FAIL (ADR-0124 D1 — the server is the authoritative gate; the client lock is courtesy)", - "a 'published' app absent from the Home launcher, or an end-user list rendering raw picklist values instead of labels, is a FAIL", + "a 'published' app absent from the app switcher, or an end-user list rendering raw picklist values instead of labels, is a FAIL", "a clause that holds on the en leg and fails on the zh-CN leg is a FAIL of that clause, never a pass with a note: each clause holds only when it holds on both legs (fixtures.requires[0])" ], "traps": ["stale-console-bundle", "automation-input", "hydration-race"], @@ -102,7 +102,8 @@ { "revision": 13, "date": "2026-11-04", "change": "fixtures.knownGaps[3] corrected from QA run #29877 (W5-P0, at 589049b0; the list of record is comment 6600018008 on #27377): the zh-CN leg's acceptance[2] failure is fixed by PR #29790 (#29673 closed), and the run read that leg passing acceptance[2] and [3], so the instruction to score it FAIL citing #29673 is withdrawn and the row is a regression row. Read at base f68b47ca", "ref": "#29906" }, { "revision": 14, "date": "2026-11-24", "change": "steps[5] and knownGaps[1] no longer route through Studio's Interfaces pillar, retired by #36502: the Create-app scaffold (box on) is the nav item, the dialog stays on the Data pillar, and a hand-wired entry is the running app's design-mode menu editor. No clause changed", "ref": "#36502" }, { "revision": 15, "date": "2026-11-24", "change": "steps name the object page tab by its new name, Field layout (字段布局, formerly Form; card #36505).", "ref": "#36505" }, - { "revision": 16, "date": "2026-11-25", "change": "steps[1]: the Studio home is removed (#36908). 'Build an app' opens Studio on the last package, or Setup → Packages when there is none; the other chip reads 'New blank app' and opens Setup → Packages with New package open. There is no Studio landing. Read from source at PR head (HomePage.tsx, useNewPackageDoorPath, studioEntryPermissions.ts). No clause changed", "ref": "#36908" } + { "revision": 16, "date": "2026-11-25", "change": "steps[1]: the Studio home is removed (#36908). 'Build an app' opens Studio on the last package, or Setup → Packages when there is none; the other chip reads 'New blank app' and opens Setup → Packages with New package open. There is no Studio landing. Read from source at PR head (HomePage.tsx, useNewPackageDoorPath, studioEntryPermissions.ts). No clause changed", "ref": "#36908" }, + { "revision": 17, "date": "2026-11-29", "change": "steps[1], [2], [3], [5] and [6], acceptance[3] (clause and verify), negative[1] and fixtures.knownGaps[0] and [1] re-pointed (stale steps in five places, card #38426; QA run #38417, at ff69bcab, its en leg). (1) No Home build chip: the entry is the app switcher's Add app → New blank app (useAddAppEntries.ts). (2) The New object dialog's confirm reads Create and drafts and publishes at once (MetadataListCreateDialog.tsx). (3) The page's Save drafts and publishes (studioSaveBar.tsx); there is no Publish all review sheet on this path. (4) Application → New is the generic metadata form with no objects-as-menu-items option; the nav entry is wired by hand in Preview → Add nav item. (5) The Data pillar terms gave way to App Studio's left menu and the object's Records / Field layout / Advanced tabs; the new app shows in the app switcher, the home launcher being retired (objectstack#36732). No clause weakened: the launcher clause now reads the app switcher, where a published app shows. The zh-CN leg was not run in that round, so these steps are measured on the en leg and from source. Read from source at base 0c1b2ffe; no product change", "ref": "#38426" } ] }, { @@ -4478,7 +4479,7 @@ "title": "Authorable keys Studio has no control for still work when another door writes them: per metadata type, each key written into a package draft through the metadata API is stored, served after publish and takes its runtime effect", "since": "v18", "status": "active", - "revision": 11, + "revision": 12, "priority": "P2", "surface": "mixed", "personas": [ @@ -4494,7 +4495,7 @@ "the showcase's external datasource showcase_external (examples/app-showcase/src/system/datasources/showcase-external.datasource.ts) for the datasource / external rows" ], "knownGaps": [ - "ROWS THAT FAIL TODAY (QA run #26715, at 3fcafcd3) — score each fail citing its record: the form-view keys subforms and modalSize, which no surface reads from a form view since #36425 (PR #36543; a source read at base 5dbcc02b, no run yet: the named-form page FormPage.tsx names neither key, recordFormSubforms in ui/packages/app-shell/src/utils/recordFormNavigation.ts takes child collections from the object alone, and modalSize's liveness re-audit is #36544). The form-view key defaults left this list with the same change: the record form, where it did not apply, no longer loads a form view, and the named-form page applies it on a create. Out of the matrix since QA run #29672 (at 3482f3d8d2, re-read at 339f63da30): drawerSide and drawerWidth are refused at parse, so they are no longer a stored-and-inert row (their retiredKey tombstones in packages/spec/src/ui/view.zod.ts, and form-view-drawer-keys-removed in packages/spec/src/conversions/registry.ts); layout, defaultTab and tabPosition have a Studio control, since the form-view inspector renders the form variant's spec schema through SchemaForm (ui/packages/app-shell/src/views/metadata-admin/inspectors/ViewVariantInspector.tsx), so step 4 moves them out. layout:'horizontal' not drawn on the Studio canvas was #29676, fixed by #29759 (7ba8b11f52). Fixed since the run, so no longer fails: a list view locked by sharing.lockedBy alone, which now shows its lock indicator (#29312, merged 2026-11-02); field deleteBehavior 'restrict' under a master_detail parent (#26718; since out of the matrix: the field inspector offers a deleteBehavior control on lookup, user and master_detail fields, offeredDeleteBehaviors in ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx, so step 4 moved it out, QA run #33861), an object bound to an unknown datasource (#26912), a chart list view on another object's dataset (#26719). Measured rendering by QA run #27441 at c4c515ad, so no longer a failing row: the form-view `buttons` key (the authored submit label shown, cancel hidden; ObjectForm folds buttons.submit and buttons.cancel onto its flat renderer props, ui/packages/plugin-form/src/ObjectForm.tsx)", + "ROWS THAT FAIL TODAY (QA run #26715, at 3fcafcd3) — score each fail citing its record: the form-view key subforms, which no surface reads from a form view since #36425 (PR #36543; a source read at base 5dbcc02b, no run yet: the named-form page FormPage.tsx does not name it, and recordFormSubforms in ui/packages/app-shell/src/utils/recordFormNavigation.ts takes child collections from the object alone). Out of the matrix since PR #38168 (a source read at base eec2bc3e, no run yet): modalSize is refused at parse, retired in @objectstack/spec 19.0.0 (its retiredKey tombstone in packages/spec/src/ui/view.zod.ts, and form-view-modal-size-removed in packages/spec/src/conversions/registry.ts), so it is no longer a stored-and-inert row. The form-view key defaults left this list with the same change: the record form, where it did not apply, no longer loads a form view, and the named-form page applies it on a create. Out of the matrix since QA run #29672 (at 3482f3d8d2, re-read at 339f63da30): drawerSide and drawerWidth are refused at parse, so they are no longer a stored-and-inert row (their retiredKey tombstones in packages/spec/src/ui/view.zod.ts, and form-view-drawer-keys-removed in packages/spec/src/conversions/registry.ts); layout, defaultTab and tabPosition have a Studio control, since the form-view inspector renders the form variant's spec schema through SchemaForm (ui/packages/app-shell/src/views/metadata-admin/inspectors/ViewVariantInspector.tsx), so step 4 moves them out. layout:'horizontal' not drawn on the Studio canvas was #29676, fixed by #29759 (7ba8b11f52). Fixed since the run, so no longer fails: a list view locked by sharing.lockedBy alone, which now shows its lock indicator (#29312, merged 2026-11-02); field deleteBehavior 'restrict' under a master_detail parent (#26718; since out of the matrix: the field inspector offers a deleteBehavior control on lookup, user and master_detail fields, offeredDeleteBehaviors in ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx, so step 4 moved it out, QA run #33861), an object bound to an unknown datasource (#26912), a chart list view on another object's dataset (#26719). Measured rendering by QA run #27441 at c4c515ad, so no longer a failing row: the form-view `buttons` key (the authored submit label shown, cancel hidden; ObjectForm folds buttons.submit and buttons.cancel onto its flat renderer props, ui/packages/plugin-form/src/ObjectForm.tsx)", "NOT JUDGEABLE HERE: mailAssociation (needs a mailbox with inbound ingest), ackPlaintextMasking (its only reader is a build-time warning), lifecycle.ttl (the sweep is hourly — drive it only with time to wait for the next sweep), dimensions (inconclusive at 3fcafcd3). Record them not-run with this line cited", "app / menu-entry keys are studio-authoring.app-and-nav-properties, page slots and variables studio-authoring.authored-page-slots-and-variables, the widget types studio-authoring.dashboard-widget-and-filter-types — not repeated here", "one runner's budget does not reach the matrix: QA run #31486 (owed:weekly, at 0647dabb) drove 9 rows (managedBy, ownership, systemFields, autonumber format, storage notNull, internal, maskingRule, flow successMessage, flow requiredPermissions) and reached no other, so acceptance[0]–[2] scored partial. The item needs a runner of its own, or a split of the matrix into items; the split is owed and not made here" @@ -4562,7 +4563,7 @@ "flow.errorHandling { strategy, maxRetries } → maxRetries 2 yields three failed attempts, each its own failed run in GET /api/v1/automation/NAME/runs (retryExecution in packages/services/service-automation/src/engine.ts starts each attempt as a new run), not three attempts inside one run", "flow.nodes[].inputSchema → stored and served", "view.list: searchableFields, userFilters, resizable, compactToolbar, selection, pagination, rowHeight, grouping, rowColor, hiddenFields, fieldOrder, rowActions, bulkActions, conditionalFormatting, inlineEdit, exportOptions (needs an export grant), appearance, addRecord, showRecordCount, allowPrinting, emptyState → each renders as its key describes; probe compactToolbar, showRecordCount and resizable at the value opposite to what the list does with the key unset, since at that default a stored key renders exactly like no key and proves nothing (gap-view card, 3fcafcd3)", - "view.form (read on the named-form page: publish the scratch form view and open /forms/NAME, adding ?recordId=ID for an edit; since #36425 the record create and edit surfaces load no form view, so nothing drawn there is this row's observable): submitBehavior, allowSkip, showStepIndicator, buttons → render as described (ui/apps/console/src/components/FormPage.tsx reads each; buttons measured rendering, knownGaps[0]); defaults → prefills a create and never an edit (FormPage.tsx readPrefill); groups → the legacy alias of sections, folded onto `sections` at parse (packages/spec/src/ui/view.zod.ts#FormViewSchema), so the draft read carries the sections, which counts as written, and the page draws them; subforms and modalSize → stored and served, with no reader on a form view since #36425: the named-form page reads neither, and the record form takes its child collections from the object's field groups and sizes its own dialog, so each is a FAIL of acceptance[1] and [2] scored against knownGaps[0] (modalSize's ledger re-audit is #36544), never a tick on the stored value; splitDirection / splitSize / splitResizable → refused at parse (retired in @objectstack/spec 18.3.0 with the split form, ADR-0050); drawerSide / drawerWidth → refused at parse (retired in @objectstack/spec 18.3.0, ADR-0049: no form view opens in a drawer). layout, defaultTab and tabPosition are not rows: Studio offers a control for each (step 4, knownGaps[0])", + "view.form (read on the named-form page: publish the scratch form view and open /forms/NAME, adding ?recordId=ID for an edit; since #36425 the record create and edit surfaces load no form view, so nothing drawn there is this row's observable): submitBehavior, allowSkip, showStepIndicator, buttons → render as described (ui/apps/console/src/components/FormPage.tsx reads each; buttons measured rendering, knownGaps[0]); defaults → prefills a create and never an edit (FormPage.tsx readPrefill); groups → the legacy alias of sections, folded onto `sections` at parse (packages/spec/src/ui/view.zod.ts#FormViewSchema), so the draft read carries the sections, which counts as written, and the page draws them; subforms → stored and served, with no reader on a form view since #36425: the named-form page does not read it, and the record form takes its child collections from the object's field groups, so it is a FAIL of acceptance[1] and [2] scored against knownGaps[0], never a tick on the stored value; splitDirection / splitSize / splitResizable → refused at parse (retired in @objectstack/spec 18.3.0 with the split form, ADR-0050); drawerSide / drawerWidth → refused at parse (retired in @objectstack/spec 18.3.0, ADR-0049: no form view opens in a drawer); modalSize → refused at parse (retired in @objectstack/spec 19.0.0, ADR-0049: no form view opens in a dialog). layout, defaultTab and tabPosition are not rows: Studio offers a control for each (step 4, knownGaps[0])", "dashboard.requiredPermissions → a viewer without the capability is refused the dashboard. Its steps[0] stored-check runs as a holder of the capability: an admin who does not hold it is refused the draft and the live read alike (403)", "dataset (Studio's New dataset, ui/packages/app-shell/src/views/studio-design/datasetCreate.tsx DatasetCreateEntry, writes only a name, an object, the seed's count measure, group-by dimensions and sum measures, so it offers no control for the keys below): include, dimensions with nullLabel, measures count / sum / avg / filtered / ratio, currency format → a report bound to it shows the null bucket labelled and each measure's value", "permission.description / isDefault / allowExport / rowLevelSecurity[].positions → the Setup list shows the description; isDefault raises a suggestion; allowExport → export 200 with it, 403 EXPORT_NOT_PERMITTED without; positions limit the policy to holders of the position" @@ -4636,6 +4637,12 @@ "date": "2026-11-26", "change": "the view.form row is re-audited after #36425 (PR #36543) and its STALE marker of PR #36793 removed. Its observable is the named-form page (/forms/NAME), the one console surface that still loads a form view: submitBehavior, allowSkip, showStepIndicator, buttons and defaults are read there, groups is folded onto sections at parse, and subforms and modalSize have no form-view reader left, so they move into fixtures.knownGaps[0] as failing rows and defaults moves out of it. A source read, not a run: FormPage.tsx, recordFormNavigation.ts, MetadataProvider.tsx, view.zod.ts and packages/spec/liveness/view.json, at base 5dbcc02b. The clauses are unchanged", "ref": "#36798" + }, + { + "revision": 12, + "date": "2026-11-29", + "change": "the view.form row and fixtures.knownGaps[0] no longer name modalSize as a failing row: PR #38168 retired it, so it is refused at parse (retired in @objectstack/spec 19.0.0, ADR-0049; its retiredKey tombstone in packages/spec/src/ui/view.zod.ts, and form-view-modal-size-removed in packages/spec/src/conversions/registry.ts), the convention drawerSide and drawerWidth already follow. subforms stays a failing row. A source read at base eec2bc3e, no run yet", + "ref": "#38191" } ] }, @@ -5359,7 +5366,7 @@ "title": "The action save door refuses a contradictory `preflight` at its located path: no params, beside execution 'aggregate', a hole outside the closed set (its own sentence for `${result.*}`), an undeclared param, an unclosed hole, a URL off this origin, a non-GET method, and each seed contradiction", "since": "v18.4", "status": "active", - "revision": 1, + "revision": 2, "priority": "P1", "surface": "api", "personas": [ @@ -5369,7 +5376,7 @@ "app": "showcase", "requires": [ "a fresh boot of the showcase: `pnpm dev -- --fresh -p PORT --seed-admin` (ephemeral DB; the seeded admin is printed)", - "the base body every variant edits: { name: 'qa_pf_base', label: 'QA preflight base', objectName: 'showcase_task', operation: 'update', execution: 'perRecord', locations: ['record_header'], params: [{ name: 'estimate_hours', label: 'Estimate (h)', type: 'number', required: true }, { name: 'notes', label: 'Notes', type: 'textarea', required: true }], preflight: { read: { url: '/api/v1/data/showcase_task/${ctx.recordId}' }, path: 'record', fields: [{ path: 'title', label: 'Title' }, { path: 'status', label: 'Status' }], seed: [{ param: 'notes', path: 'title' }] } }. Scratch names only (qa_pf_*), so nothing shipped is touched" + "the base body every variant edits: { name: 'qa_pf_base', label: 'QA preflight base', objectName: 'showcase_task', operation: 'update', execution: 'perRecord', locations: ['record_page'], params: [{ name: 'estimate_hours', label: 'Estimate (h)', type: 'number', required: true }, { name: 'notes', label: 'Notes', type: 'textarea', required: true }], preflight: { read: { url: '/api/v1/data/showcase_task/${ctx.recordId}' }, path: 'record', fields: [{ path: 'title', label: 'Title' }, { path: 'status', label: 'Status' }], seed: [{ param: 'notes', path: 'title' }] } }. Scratch names only (qa_pf_*), so nothing shipped is touched" ] }, "steps": [ @@ -5431,6 +5438,12 @@ "date": "2026-11-10", "change": "initial — the spec half of an action's `preflight` read, refused at the save door (#31840). Scoped sweep #32269 (epic #32022 M3, theme 6: action preflight and page bindings), read from source at 9091955b; no live run made", "ref": "#32269" + }, + { + "revision": 2, + "date": "2026-11-29", + "change": "fixtures.requires[1]'s base body qa_pf_base declares locations ['record_page'] where it said record_header. Protocol 19 retired the page-part location words (record_header or record_more became record_page, the 19 conversion action-locations-acted-on), and a body sent to the save door is not converted, so every variant built on the old base body would read a location refusal instead of its own preflight refusal. No clause or threshold changed", + "ref": "#38046" } ] }, diff --git a/docs/qa/platform-checklist/areas/ux-conventions.json b/docs/qa/platform-checklist/areas/ux-conventions.json index 1d351029d3c..ce3936ad804 100644 --- a/docs/qa/platform-checklist/areas/ux-conventions.json +++ b/docs/qa/platform-checklist/areas/ux-conventions.json @@ -216,7 +216,7 @@ "title": "Every disabled control explains itself — the reason shows on hover and on keyboard focus, and is exposed as an accessible description", "since": "v17.7", "status": "active", - "revision": 7, + "revision": 8, "priority": "P1", "surface": "browser", "personas": [ @@ -230,7 +230,7 @@ "the read-only showcase package in Studio (stock)" ], "knownGaps": [ - "FIXED, now the calibration reference (objectui#11811): the task record's Archive button (examples/app-showcase/src/ui/actions/index.ts#ArchiveTaskAction, disabled while has(record.done) && record.done != true) carries its reason as a tooltip AND an aria-describedby on a focusable wrapper, in its one placement, record_header (it declares locations: ['record_header'] only; objectui DeclaredActionsBar.tsx; pin DeclaredActionsBar.disabledReason-11811.test.tsx). It declares its own reason, disabledReason: 'Mark the task done first.' (the action spec's disabledReason, #26619), so the text is the author's, not the generic platform fallback — record it as specific under clause 3. Check this control first to calibrate both the hover and the keyboard oracle", + "FIXED, now the calibration reference (objectui#11811): the task record's Archive button (examples/app-showcase/src/ui/actions/index.ts#ArchiveTaskAction, disabled while has(record.done) && record.done != true) carries its reason as a tooltip AND an aria-describedby on a focusable wrapper, in its one placement, a button in the Task Detail title bar (it declares locations: ['record_page'] only; objectui DeclaredActionsBar.tsx; pin DeclaredActionsBar.disabledReason-11811.test.tsx). It declares its own reason, disabledReason: 'Mark the task done first.' (the action spec's disabledReason, #26619), so the text is the author's, not the generic platform fallback — record it as specific under clause 3. Check this control first to calibrate both the hover and the keyboard oracle", "Studio's Publish button on the read-only showcase package and the import wizard's disabled Next are FIXED for the keyboard (QA run #23953 at objectui daeb77fc84dd): each carries its reason on a focusable wrapper with an aria-describedby, so both now calibrate hover AND keyboard, expected PASS; the field inspector's Remove passes the same way (the automation Enabled switch is not a row: it stays enabled on a read-only package, variants[2]). Regression rows, expected PASS since QA run #24570 (objectui 4016370a, two fresh loads each): the field inspector's read-only Label / API name / Type / Required / Move up-down sit in a focusable panel wrapper described by the read-only reason, with the tooltip on focus (objectstack-ai/objectui#12303, closed by objectui PR #12324, b64fda3f — the rail body described by fieldRailReasonId, StudioDesignSurface.tsx); and the Studio validation editor's body on a read-only package is a role=group tab stop described by the reason, with the tooltip on hover and focus (objectstack-ai/objectui#12691, closed by objectui PR #12833, d0a00d79, ObjectValidationsPanel.tsx). Both fixes are in the console pin 4016370a and on objectui main" ] }, @@ -322,6 +322,12 @@ "date": "2026-11-15", "change": "variants[5]: 'Reassign…' renders disabled for the admin and is not rendered for a plain member, so the member leg records it not offered (QA run #33861, comment 6894395705; ledger 6896511848 of #33761 row 180). The clauses are unchanged. Read at base 895783a1", "ref": "#33981" + }, + { + "revision": 8, + "date": "2026-11-29", + "change": "fixtures.knownGaps (the Archive calibration control) names Archive's protocol-19 location, record_page, which examples/app-showcase/src/ui/actions/index.ts#ArchiveTaskAction declares (it said record_header, which protocol 19 retired, #36495). It is still drawn once, as a title-bar button. No clause changed", + "ref": "#38046" } ] }, diff --git a/docs/qa/studio-benchmark/SCENARIO.md b/docs/qa/studio-benchmark/SCENARIO.md index c710b67ae3a..a85e8f7c15c 100644 --- a/docs/qa/studio-benchmark/SCENARIO.md +++ b/docs/qa/studio-benchmark/SCENARIO.md @@ -12,7 +12,7 @@ Scoring rules live in [SCORING.md](./SCORING.md); the sheet a run fills in is | what | value | |---|---| | app | `examples/app-showcase`, a **fresh** boot — empty database, nothing left from an earlier run | -| boot | `OS_PORT=PORT pnpm -C ABS/examples/app-showcase exec objectstack dev --ui --seed-admin -p PORT -d file:/tmp/RUN/data.db` (the dogfood-verification §0 line; `OS_PORT` exported, not only `-p`) | +| boot | `pnpm -C ABS/examples/app-showcase exec objectstack dev --ui --seed-admin -p PORT -d file:/tmp/RUN/data.db` (the dogfood-verification §0 line; `-p` alone reaches the compile, `os dev` exports it as `OS_PORT`) | | console | the build of the same tree's `ui/apps/console` (`pnpm console:build`, into `packages/console/dist`), served at `/_console/` — **never** a console dev server: the benchmark measures what users get | | author | the seeded platform admin `admin@objectos.ai` / `admin123`, signed in through the form | | end user | a second identity minted by admin create (`POST /api/v1/auth/admin/create-user`, then `change-password`), or by invite + sign-up — a stock showcase refuses self-registration | diff --git a/examples/app-showcase/src/data/objects/account.object.ts b/examples/app-showcase/src/data/objects/account.object.ts index 8c02c73a842..40b95f9f5f5 100644 --- a/examples/app-showcase/src/data/objects/account.object.ts +++ b/examples/app-showcase/src/data/objects/account.object.ts @@ -181,7 +181,7 @@ export const Account = ObjectSchema.create({ label: 'Support Config Shape', description: 'Support config must declare a known tier and a positive seat count.', field: 'support_config', - message: 'Support Config must be { tier: standard|premium|enterprise, seats?: >=1 }.', + message: 'Support Config must name a tier (standard, premium or enterprise) and, if it sets seats, at least 1 seat.', schema: { type: 'object', properties: { diff --git a/examples/app-showcase/src/system/translations/index.ts b/examples/app-showcase/src/system/translations/index.ts index 184a7ea7493..915dd453d5c 100644 --- a/examples/app-showcase/src/system/translations/index.ts +++ b/examples/app-showcase/src/system/translations/index.ts @@ -162,7 +162,7 @@ export const ShowcaseTranslationBundle = { message: 'Billing Email must be a valid email address.', }, support_config_shape: { - message: 'Support Config must be { tier: standard|premium|enterprise, seats?: >=1 }.', + message: 'Support Config must name a tier (standard, premium or enterprise) and, if it sets seats, at least 1 seat.', }, churn_reason_consistency: { message: 'Churn reason consistency.', @@ -644,13 +644,15 @@ export const ShowcaseTranslationBundle = { // there. Vocabulary is the one this bundle already established: // 生命周期 / 税号 / 账单邮箱 / 支持配置 / 流失原因 are the field labels // right above, so a refusal names the field with the same word the form - // does. The `support_config_shape` shape stays in its source spelling — - // it is a machine contract the author must type back, not prose. + // does. The `support_config_shape` sentence keeps the machine words + // `tier` / `seats` and the tier values in their source spelling — they + // are what the author types back — but no braces: a rule message is a + // `{{ }}` template, and a single-brace token there is refused. _validations: { account_lifecycle: { message: '客户生命周期的状态流转无效。' }, tax_id_format: { message: '税号格式应为 12-3456789。' }, billing_email_format: { message: '账单邮箱必须是有效的邮箱地址。' }, - support_config_shape: { message: '支持配置必须为 { tier: standard|premium|enterprise, seats?: >=1 }。' }, + support_config_shape: { message: '支持配置必须指定 tier(standard、premium 或 enterprise);如填写 seats,至少为 1。' }, churn_reason_consistency: { message: '流失原因一致性。' }, churn_reason_present: { message: '客户标记为流失时必须填写流失原因。' }, churn_reason_absent: { message: '只有客户已流失时才能填写流失原因。' }, diff --git a/examples/app-showcase/src/ui/actions/index.ts b/examples/app-showcase/src/ui/actions/index.ts index 5f75f191a1e..709a74b0df5 100644 --- a/examples/app-showcase/src/ui/actions/index.ts +++ b/examples/app-showcase/src/ui/actions/index.ts @@ -92,7 +92,8 @@ export const MarkDoneAction = defineAction({ visible: 'has(record.done) && record.done != true', // No `record_section`: the Task Detail header already draws it, and its // quick-actions bar carries only what the header does not (one action row). - locations: ['record'], + // `selection`: the selection bar of every task grid (objectstack#36496). + locations: ['record', 'selection'], refreshAfter: true, }); @@ -197,8 +198,9 @@ export const RecalcEstimateAction = defineAction({ // takes the standard page, which draws no `record_section` action — the // ⋯ overflow is where the action is found there. The authored header lists // its action ids and leaves this one out, so the full page still draws it - // once, in the bar. - locations: ['record_section', 'record_page'], component: 'action:menu', + // once, in the bar. `selection`: the selection bar of every task grid + // (objectstack#36496), one POST per selected record. + locations: ['record_section', 'record_page', 'selection'], component: 'action:menu', // The endpoint is record-scoped and rejects a body without an id. On a // record surface the page supplies it; invoked from a LIST ROW (see the // `legacy_row_actions` view) nothing else can, so name the body key the @@ -212,7 +214,7 @@ export const RecalcEstimateAction = defineAction({ * (objectui#3139). Since #17319 the ACTION declares the contract its body is * written for (`execution: 'aggregate'`, below) and the VIEW performs the * dispatch through a `bulkActionDefs` entry naming it with the same key and - * value (see `task.view.ts` → `bulk_actions`); a bare-string wiring of it is + * value (see `task.view.ts` → `bulk_actions`); a `selection` placement of it is * now refused at authoring time instead of quietly recalculating one row. The * renderer then dispatches it ONCE for the whole selection, with every * selected id in `params._selectedIds` — the recalc endpoint's flow runs the @@ -250,7 +252,7 @@ export const RecalcSelectionAction = defineAction({ // #17319 — ONE dispatch for the whole selection, every id in // `params._selectedIds`. The view's `bulkActionDefs` entry still performs // the dispatch; this declares what the body was written to receive, so a - // bare-string `bulkActions` wiring of it is refused rather than silently + // `selection` placement of it is refused rather than silently // recalculating one row out of ten. execution: 'aggregate', // This toast shows only at the single-record placement below: the selection diff --git a/examples/app-showcase/src/ui/actions/predicate-matrix.action.ts b/examples/app-showcase/src/ui/actions/predicate-matrix.action.ts index 746a4debd12..76658fba0ab 100644 --- a/examples/app-showcase/src/ui/actions/predicate-matrix.action.ts +++ b/examples/app-showcase/src/ui/actions/predicate-matrix.action.ts @@ -23,7 +23,7 @@ * | list toolbar | above the list — no record in scope | * | row kebab (`record_row`) | the `⋮` menu on each row | * | record header (`record` / `record_page`) | the detail page | - * | selection bar | after ticking rows, from the view's `bulkActions` | + * | selection bar (`selection`) | after ticking rows, on every grid of the object | * * They have drifted before, in both directions: the selection bar ignored * `requiredPermissions` entirely, so an action the row kebab hid from an @@ -96,7 +96,7 @@ * all evaluate on the record header and in its `⋯` overflow. Where the same * action is also declared elsewhere it agrees: the row `⋮` menu matches the * header on both specimens, and so does the selection bar for the six - * specimens the view names in `bulkActions`. `record` / `record_page` + * specimens placed at `selection`. `record` / `record_page` * hand the predicate to `evalRowPredicate` WHOLE, so the * `{ dialect: 'cel' }` envelope `defineAction` normalizes to is routed to * the canonical engine rather than flattened onto a dialect guess. @@ -153,6 +153,13 @@ const echo = { */ const RECORD_SURFACES = ['record'] as const; +/** + * The record surfaces plus the selection bar (`selection`, objectstack#36496): + * the ten gates compared across all four surfaces, drawn on the bar of every + * grid of the object once rows are ticked. + */ +const SELECTION_SURFACES = [...RECORD_SURFACES, 'selection'] as const; + // ─────────────────────────────────────────────────────────────────────────── // 1 — Surface parity: ONE predicate over a relation field, on every surface // ─────────────────────────────────────────────────────────────────────────── @@ -171,8 +178,8 @@ const RECORD_SURFACES = ['record'] as const; * COLUMNS, so `gated_columns` (which shows `f_lookup` and not `f_lookups`) * expands exactly one side of this comparison while the default list expands * neither. Same records, same predicate, and before objectui#3501 two different - * answers. Declared on all three record surfaces and named in both views' - * `bulkActions`, so a disagreement shows up as a button in one place and not + * answers. Declared on all three record surfaces and placed at `selection`, + * so a disagreement shows up as a button in one place and not * another. * * Neither field is a column on the default list, which also puts the `$select` @@ -190,7 +197,7 @@ export const ZooRelationGateAction = defineAction({ visible: 'has(record.f_lookup) && has(record.f_lookups) && record.f_lookups != null' + ' && record.f_lookups.size() > 0 && record.f_lookup == record.f_lookups[0]', - locations: [...RECORD_SURFACES], + locations: [...SELECTION_SURFACES], refreshAfter: false, }); @@ -219,7 +226,7 @@ export const ZooOwnerGateAction = defineAction({ body: echo, successMessage: 'You own this specimen.', visible: 'has(record.owner_id) && record.owner_id == os.user.id', - locations: [...RECORD_SURFACES], + locations: [...SELECTION_SURFACES], refreshAfter: false, }); @@ -240,7 +247,7 @@ export const ZooUserIdentityGateAction = defineAction({ body: echo, successMessage: 'You are the assigned user on this specimen.', visible: 'has(record.f_user) && record.f_user == os.user.id', - locations: [...RECORD_SURFACES], + locations: [...SELECTION_SURFACES], refreshAfter: false, }); @@ -259,7 +266,7 @@ export const ZooUserIdentityGateAction = defineAction({ * | row `⋮` menu (`record`) | OFFERED | absent | * * ⚠️ The selection bar is deliberately NOT a row of that table: this action is - * not named in either view's `bulkActions` (`field-zoo.view.ts`), so it never + * not placed at `selection`, so it never * reaches that surface at all — an absence of DECLARATION, which would read as * an absence of dialect support if tabulated beside the other two. The * three-surface agreement is pinned instead by the neighbours that ARE declared @@ -333,7 +340,7 @@ export const ZooVisibleStringAction = defineAction({ type: 'script', body: echo, visible: 'has(record.f_boolean) && record.f_boolean == true', - locations: [...RECORD_SURFACES], + locations: [...SELECTION_SURFACES], refreshAfter: false, }); @@ -346,7 +353,7 @@ export const ZooVisibleTaggedAction = defineAction({ type: 'script', body: echo, visible: P`has(record.f_boolean) && record.f_boolean == true`, - locations: [...RECORD_SURFACES], + locations: [...SELECTION_SURFACES], refreshAfter: false, }); @@ -359,7 +366,7 @@ export const ZooVisibleEnvelopeAction = defineAction({ type: 'script', body: echo, visible: { dialect: 'cel', source: 'has(record.f_boolean) && record.f_boolean == true' }, - locations: [...RECORD_SURFACES], + locations: [...SELECTION_SURFACES], refreshAfter: false, }); @@ -397,7 +404,7 @@ export const ZooPermHeldAction = defineAction({ type: 'script', body: echo, requiredPermissions: ['showcase.export_data'], - locations: [...RECORD_SURFACES], + locations: [...SELECTION_SURFACES], refreshAfter: false, }); @@ -416,7 +423,7 @@ export const ZooPermMissingAction = defineAction({ type: 'script', body: echo, requiredPermissions: ['showcase.restricted_ops'], - locations: [...RECORD_SURFACES], + locations: [...SELECTION_SURFACES], refreshAfter: false, }); @@ -433,7 +440,7 @@ export const ZooPermAndAction = defineAction({ type: 'script', body: echo, requiredPermissions: ['showcase.export_data', 'showcase.restricted_ops'], - locations: [...RECORD_SURFACES], + locations: [...SELECTION_SURFACES], refreshAfter: false, }); @@ -451,7 +458,7 @@ export const ZooPermEmptyAction = defineAction({ type: 'script', body: echo, requiredPermissions: [], - locations: [...RECORD_SURFACES], + locations: [...SELECTION_SURFACES], refreshAfter: false, }); diff --git a/examples/app-showcase/src/ui/views/field-zoo.view.ts b/examples/app-showcase/src/ui/views/field-zoo.view.ts index 645955d179d..acaf757d2cb 100644 --- a/examples/app-showcase/src/ui/views/field-zoo.view.ts +++ b/examples/app-showcase/src/ui/views/field-zoo.view.ts @@ -65,9 +65,11 @@ export const FieldZooViews = defineView({ }, ], - /** - * The selection-bar half of the matrix. Each name resolves against the - * object's declared actions and is promoted into a selection-bar button + /* + * The selection-bar half of the matrix: the ten gate actions are placed at + * `selection` (`predicate-matrix.action.ts`), so this view and every other + * grid of the object draw them once rows are ticked (objectstack#36496). + * Each is promoted into a selection-bar button * carrying that action's label, icon, `visible` AND `requiredPermissions` — * the last of which the bar used to drop on the floor (objectui#3492), so * an action hidden in the row kebab reappeared here the moment a row was @@ -95,18 +97,6 @@ export const FieldZooViews = defineView({ * • `showcase_zoo_perm_empty` — always present; an empty declaration * passes. */ - bulkActions: [ - 'showcase_zoo_relation_gate', - 'showcase_zoo_owner_gate', - 'showcase_zoo_user_gate', - 'showcase_zoo_visible_string', - 'showcase_zoo_visible_tagged', - 'showcase_zoo_visible_envelope', - 'showcase_zoo_perm_held', - 'showcase_zoo_perm_missing', - 'showcase_zoo_perm_and', - 'showcase_zoo_perm_empty', - ], }, listViews: { @@ -131,18 +121,6 @@ export const FieldZooViews = defineView({ { field: 'f_boolean' }, { field: 'f_rating' }, ], - bulkActions: [ - 'showcase_zoo_relation_gate', - 'showcase_zoo_owner_gate', - 'showcase_zoo_user_gate', - 'showcase_zoo_visible_string', - 'showcase_zoo_visible_tagged', - 'showcase_zoo_visible_envelope', - 'showcase_zoo_perm_held', - 'showcase_zoo_perm_missing', - 'showcase_zoo_perm_and', - 'showcase_zoo_perm_empty', - ], }, /** @@ -152,9 +130,9 @@ export const FieldZooViews = defineView({ * specimens it acts on Full and reports Minimal as skipped, rather than * quietly including it. * - * #17319 — `showcase_zoo_visible_string` is wired BOTH ways in this file: as a - * bare string in the two `bulkActions` lists above (per-record) and here as an - * aggregate def. That is deliberate and it stays UNDECLARED: its body + * #17319 — `showcase_zoo_visible_string` is wired BOTH ways: placed at + * `selection` (per-record, on every grid of the object) and here as an + * aggregate def, which claims its name on this view's bar. That is deliberate and it stays UNDECLARED: its body * (`predicate-matrix.action.ts`) reads `ctx.recordId` AND `input._selectedIds` * and copes with either, which is the one honest reason to omit `action.execution`. * ⛔ Declaring either contract on it would make the OTHER wiring a lint error diff --git a/examples/app-showcase/src/ui/views/task.view.ts b/examples/app-showcase/src/ui/views/task.view.ts index 9690d9bad2f..f87b554bf20 100644 --- a/examples/app-showcase/src/ui/views/task.view.ts +++ b/examples/app-showcase/src/ui/views/task.view.ts @@ -152,10 +152,10 @@ export const TaskViews = defineView({ // ── Bulk actions — one declared action over the SELECTED records ────── // The selection-bar twin of `legacy_row_actions` above, and — unlike that - // fixture — the CANONICAL authoring form, not a legacy one. `bulkActions` - // is the only way to declare a bulk action: `action.bulkEnabled` was - // retired in spec 17 (#3896 close-out) precisely because nothing ever - // consumed it, and its tombstone prescribes this key instead. + // fixture — the CANONICAL authoring form, not a legacy one. An action + // placed at `selection` is a per-record bulk action (objectstack#36496; + // until protocol 19 a view's `bulkActions` list named it), drawn on the + // selection bar of EVERY grid view of the object, this one included. // // Complements `project.view.ts`'s `bulkActionDefs`, which is the OTHER // bulk vocabulary: inline defs that mass-EDIT records through the data @@ -180,7 +180,7 @@ export const TaskViews = defineView({ // dispatch shape; results are all-or-nothing, no per-row retry. // // None declares `list`: a bulk action is not a toolbar action, - // it needs a selection. Naming it here is the whole declaration. + // it needs a selection. `selection` in its `locations` is the whole declaration. bulk_actions: { label: 'Bulk Actions', type: 'grid', @@ -192,7 +192,6 @@ export const TaskViews = defineView({ { field: 'progress' }, { field: 'done' }, ], - bulkActions: ['showcase_mark_done', 'showcase_recalc_estimate'], bulkActionDefs: [ { name: 'showcase_recalc_selection', operation: 'custom', execution: 'aggregate' }, ], diff --git a/examples/app-starter/README.md b/examples/app-starter/README.md index ad36a91eb97..6a7e9046dc7 100644 --- a/examples/app-starter/README.md +++ b/examples/app-starter/README.md @@ -1,23 +1,29 @@ # @objectstack/example-starter — Starter app A small, complete app an organization installs and then makes its own: -companies, the people at them, and the platform's tasks and notes in one menu. +companies, the people at them, help articles, and the platform's tasks and +notes in one menu. -- `src/objects/` — `starter_company` (name, type, industry, website, phone, - address) and `starter_contact` (name, company, job title, influence, email, +- `src/objects/` — `biz_company` (name, type, industry, website, phone, + address) and `biz_contact` (name, company, job title, influence, email, phone). A contact is a person outside the organization, never a user. -- `src/views/` — a grid and a board for each object. The create and edit form - is each object's `fieldGroups`; the company's record page lists its contacts. -- `src/apps/` — the menu: companies, contacts, tasks (`sys_task`), notes + `biz_article` (title, Markdown body, category, status) holds help articles: + how-tos, common questions and reference pages. +- `src/views/` — a grid and a board for companies and for contacts, a grid of + articles. The create and edit form is each object's `fieldGroups`; the + company's record page lists its contacts. +- `src/apps/` — the menu: companies, contacts, articles, tasks (`sys_task`), notes (`sys_note`), and the overview dashboard. Tasks and notes are platform objects every environment carries; this package declares no copy of them. - `src/datasets/`, `src/dashboards/` — one overview dashboard. -- `src/data/` — five sample companies and six sample contacts. +- `src/data/` — five sample companies, six sample contacts, and four help + articles (setting up a laptop, a Wi-Fi and printing FAQ, a meeting rooms + reference, and a draft on sharing files). - `src/translations/` — English and Simplified Chinese. -The API names carry the `starter_` namespace, so a tenant can install this +The API names carry the `biz_` namespace, so a tenant can install this starter beside a CRM package without a name clash. Uninstalling the package -removes companies and contacts; tasks and notes stay. +removes companies, contacts and articles; tasks and notes stay. ## How to run diff --git a/examples/app-starter/objectstack.config.ts b/examples/app-starter/objectstack.config.ts index a9f53fd9b0e..10718aa1362 100644 --- a/examples/app-starter/objectstack.config.ts +++ b/examples/app-starter/objectstack.config.ts @@ -11,23 +11,24 @@ import * as translations from './src/translations/index.js'; import { StarterSeedData } from './src/data/index.js'; /** - * Starter app — companies and the people at them, with the platform's tasks - * and notes in the same menu. + * Starter app — companies and the people at them, and help articles, with the + * platform's tasks and notes in the same menu. * - * A small, complete app an organization installs and then makes its own: two - * objects (`starter_company`, `starter_contact`), a grid and a board for each, - * the company's contacts on its record page, sample rows, and one dashboard. + * A small, complete app an organization installs and then makes its own: + * companies and contacts (`biz_company`, `biz_contact`) with a grid and a + * board for each and the company's contacts on its record page, help articles + * (`biz_article`) with a grid, sample rows, and one dashboard. * Tasks and notes are not part of the package: the menu points at the * platform's `sys_task` and `sys_note`, so they stay when the package goes. */ export default defineStack({ manifest: { id: 'com.example.starter', - namespace: 'starter', + namespace: 'biz', version: '0.1.0', type: 'app', name: 'Starter', - description: 'Companies and contacts, with the platform\'s tasks and notes in the menu.', + description: 'Companies, contacts and help articles, with the platform\'s tasks and notes in the menu.', // Protocol major this package is authored against (ADR-0087). engines: { protocol: '^19' }, // A starter is taken over by the organization that installs it: an diff --git a/examples/app-starter/package.json b/examples/app-starter/package.json index abc31f02b34..a2f32b952f5 100644 --- a/examples/app-starter/package.json +++ b/examples/app-starter/package.json @@ -1,7 +1,7 @@ { "name": "@objectstack/example-starter", "version": "0.1.1-next.2", - "description": "Starter app: companies and their contacts, with the platform's tasks and notes in the menu", + "description": "Starter app: companies, contacts and help articles, with the platform's tasks and notes in the menu", "license": "Apache-2.0", "private": true, "main": "./objectstack.config.ts", diff --git a/examples/app-starter/src/apps/starter.app.ts b/examples/app-starter/src/apps/starter.app.ts index 767c9f15e9b..ff8c9fbac86 100644 --- a/examples/app-starter/src/apps/starter.app.ts +++ b/examples/app-starter/src/apps/starter.app.ts @@ -3,8 +3,8 @@ import { App } from '@objectstack/spec/ui'; /** - * The starter's menu: the package's companies and contacts, then the - * platform's tasks and notes, then the overview dashboard. + * The starter's menu: the package's companies, contacts and help articles, + * then the platform's tasks and notes, then the overview dashboard. * * Tasks and notes are the platform objects `sys_task` and `sys_note`, which * every environment carries; the package declares no copy of them, so @@ -12,7 +12,7 @@ import { App } from '@objectstack/spec/ui'; * label: each shows the current, localized label of what it opens. */ export const StarterApp = App.create({ - name: 'starter_app', + name: 'biz_app', label: 'Starter', icon: 'rocket', branding: { @@ -20,13 +20,14 @@ export const StarterApp = App.create({ }, navigation: [ - { id: 'nav_companies', type: 'object', objectName: 'starter_company', icon: 'building-2' }, - { id: 'nav_contacts', type: 'object', objectName: 'starter_contact', icon: 'contact' }, + { id: 'nav_companies', type: 'object', objectName: 'biz_company', icon: 'building-2' }, + { id: 'nav_contacts', type: 'object', objectName: 'biz_contact', icon: 'contact' }, + { id: 'nav_articles', type: 'object', objectName: 'biz_article', icon: 'book-open' }, // `requiresObject` names the object again because `defineStack` refuses a // menu entry for an object the stack does not declare unless the entry // says the object comes from elsewhere — here, the platform. { id: 'nav_tasks', type: 'object', objectName: 'sys_task', requiresObject: 'sys_task', icon: 'square-check' }, { id: 'nav_notes', type: 'object', objectName: 'sys_note', requiresObject: 'sys_note', icon: 'notebook-pen' }, - { id: 'nav_overview', type: 'dashboard', dashboardName: 'starter_overview_dashboard', icon: 'layout-dashboard' }, + { id: 'nav_overview', type: 'dashboard', dashboardName: 'biz_overview_dashboard', icon: 'layout-dashboard' }, ], }); diff --git a/examples/app-starter/src/dashboards/overview.dashboard.ts b/examples/app-starter/src/dashboards/overview.dashboard.ts index 504fa4aa1d8..7bba4d03bdf 100644 --- a/examples/app-starter/src/dashboards/overview.dashboard.ts +++ b/examples/app-starter/src/dashboards/overview.dashboard.ts @@ -7,7 +7,7 @@ import { Dashboard } from '@objectstack/spec/ui'; * Every widget binds to one of the two datasets (ADR-0021). */ export const OverviewDashboard = Dashboard.create({ - name: 'starter_overview_dashboard', + name: 'biz_overview_dashboard', label: 'Overview', description: 'Companies and contacts at a glance.', columns: 12, @@ -17,7 +17,7 @@ export const OverviewDashboard = Dashboard.create({ type: 'metric', title: 'Companies', description: 'Every company, whatever its type.', - dataset: 'starter_company_metrics', + dataset: 'biz_company_metrics', values: ['company_count'], layout: { x: 0, y: 0, w: 4, h: 2 }, }, @@ -27,7 +27,7 @@ export const OverviewDashboard = Dashboard.create({ title: 'Customers', description: 'Companies whose type is Customer.', filter: { type: 'customer' }, - dataset: 'starter_company_metrics', + dataset: 'biz_company_metrics', values: ['company_count'], layout: { x: 4, y: 0, w: 4, h: 2 }, }, @@ -36,7 +36,7 @@ export const OverviewDashboard = Dashboard.create({ type: 'metric', title: 'Contacts', description: 'Every contact.', - dataset: 'starter_contact_metrics', + dataset: 'biz_contact_metrics', values: ['contact_count'], layout: { x: 8, y: 0, w: 4, h: 2 }, }, @@ -45,7 +45,7 @@ export const OverviewDashboard = Dashboard.create({ type: 'bar', title: 'Companies by Type', description: 'How many companies there are of each type.', - dataset: 'starter_company_metrics', + dataset: 'biz_company_metrics', dimensions: ['type'], values: ['company_count'], layout: { x: 0, y: 2, w: 6, h: 4 }, @@ -55,7 +55,7 @@ export const OverviewDashboard = Dashboard.create({ type: 'pie', title: 'Companies by Industry', description: 'How the companies split across industries.', - dataset: 'starter_company_metrics', + dataset: 'biz_company_metrics', dimensions: ['industry'], values: ['company_count'], layout: { x: 6, y: 2, w: 6, h: 4 }, @@ -65,7 +65,7 @@ export const OverviewDashboard = Dashboard.create({ type: 'bar', title: 'Contacts by Company', description: 'How many contacts each company has.', - dataset: 'starter_contact_metrics', + dataset: 'biz_contact_metrics', dimensions: ['company'], values: ['contact_count'], layout: { x: 0, y: 6, w: 12, h: 4 }, diff --git a/examples/app-starter/src/data/articles.ts b/examples/app-starter/src/data/articles.ts new file mode 100644 index 00000000000..6574e42d3ca --- /dev/null +++ b/examples/app-starter/src/data/articles.ts @@ -0,0 +1,125 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// Sample help articles, generic office help rather than policy text. Business +// data like the companies and contacts (`index.ts`): no `mode`, so a replay +// inserts a missing article and leaves an existing one as the organization +// left it. +// +// Each `body` is Markdown in one shape, readable section by section: the +// title as a `#` heading, then 3 to 6 `##` sections, each with its own text +// and under 800 characters with its heading; the reference article carries a +// table followed by a one-line note. `test/help-articles-38372.test.ts` holds +// every article to that shape, and the blank template in create-objectstack +// carries the same seed (its parity test compares the two). + +import { defineSeed } from '@objectstack/spec/data'; +import { Article } from '../objects/article.object.js'; + +export const articles = defineSeed(Article, { + externalId: 'title', + records: [ + { + title: 'Set up your new laptop', + category: 'how_to', + status: 'published', + body: `# Set up your new laptop + +## Before you start + +Have your work email address and the temporary password from your welcome message at hand. Plug the laptop into power: the first start installs updates and can take up to half an hour. + +## Sign in for the first time + +Choose your language and keyboard, join the office Wi-Fi, then sign in with your work email and the temporary password. You are asked to choose a new password straight away; pick one you have not used anywhere else. + +## Install the apps you need + +Open the company app store from the start menu. Email, calendar, chat and the office suite install on their own; anything your team uses on top of that is listed under your department. Ask your manager if an app you need is missing. + +## Turn on backup + +Sign in to the file storage app and let it back up your Desktop and Documents folders. Files saved there follow you to a new laptop and can be restored if this one is lost. + +## Get help + +If something does not work, write to the IT help desk with the laptop's name, which is on the sticker underneath, and a screenshot of any error.`, + }, + { + title: 'Wi-Fi and printing FAQ', + category: 'faq', + status: 'published', + body: `# Wi-Fi and printing FAQ + +## How do I join the office Wi-Fi? + +Pick the network named Office and sign in with your work email and password. Guests use the Office-Guest network; its password is on the card at reception and changes every Monday. + +## Why does the Wi-Fi keep dropping? + +Most drops happen when a laptop moves between floors. Turn Wi-Fi off and on again, and forget any old office network your laptop still remembers. If it keeps happening at one desk, tell the help desk which desk it is. + +## How do I add a printer? + +Open the printer settings, choose Add printer and pick the one whose name matches the label on the machine. Printers are named by floor, so the second-floor printer starts with F2. + +## Why is my print job stuck? + +A job usually waits because the printer is out of paper or needs a release at the machine. Tap your badge on the printer to release your jobs. Jobs that are not released within a day are deleted. + +## Can I print from my phone? + +Yes. Email the file from your work account to the print address shown on the printer's screen, then release it with your badge as usual.`, + }, + { + title: 'Meeting rooms reference', + category: 'reference', + status: 'published', + body: `# Meeting rooms reference + +## Rooms at a glance + +| Room | Floor | Seats | Equipment | +| --- | --- | --- | --- | +| Harbor | 1 | 4 | Screen | +| Summit | 2 | 8 | Screen, video bar, whiteboard | +| Grove | 2 | 12 | Projector, video bar | +| Atrium | 3 | 20 | Projector, microphones | + +Seat counts are for seated meetings; a short stand-up fits a few more people. + +## Booking a room + +Book rooms from your calendar by adding the room as a guest. A booking longer than two hours, or one that repeats every week, needs a reason in the invitation so others know whether to ask for the room. + +## Video calls + +Rooms with a video bar join a call from the calendar invitation: press Join on the room's touch panel. In other rooms, connect your laptop to the screen with the cable on the table. + +## Leaving the room + +End the meeting on time, wipe the whiteboard, and take your cups with you. If you finish early, release the room from your calendar so someone else can use it.`, + }, + { + title: 'Share files with your team', + category: 'how_to', + status: 'draft', + body: `# Share files with your team + +## Pick the right place + +Keep files your whole team works on in the team's shared folder, not in your own. A file in a shared folder stays with the team when someone leaves or changes roles. + +## Share a file or folder + +Right-click the file in the file storage app, choose Share, and add people by name or add the whole team. Each person gets an email with a link. + +## Choose who can edit + +Give edit access to the people who will change the file and view access to everyone else. Links that anyone can open are turned off for files that hold customer details. + +## Stop sharing + +Open Share again and remove a person, or change their access to view only. Review who has access to a folder when a project ends.`, + }, + ], +}); diff --git a/examples/app-starter/src/data/index.ts b/examples/app-starter/src/data/index.ts index 189da3c435b..a380b985335 100644 --- a/examples/app-starter/src/data/index.ts +++ b/examples/app-starter/src/data/index.ts @@ -3,11 +3,12 @@ import { defineSeed } from '@objectstack/spec/data'; import { Company } from '../objects/company.object.js'; import { Contact } from '../objects/contact.object.js'; +import { articles } from './articles.js'; // Sample data, so the menu, the boards and the dashboard have something to -// show on first open. Business data: no `mode`, so a replay (each boot, an -// install or upgrade) inserts a missing row and leaves an existing one as the -// organization left it. Delete the rows, or the whole package, when they are +// show on first open; the help articles are in `articles.ts`. Business data: +// no `mode`, so a replay (each boot, an install or upgrade) inserts a missing +// row and leaves an existing one as the organization left it. Delete the rows, or the whole package, when they are // no longer wanted. const companies = defineSeed(Company, { @@ -33,4 +34,4 @@ const contacts = defineSeed(Contact, { ], }); -export const StarterSeedData = [companies, contacts]; +export const StarterSeedData = [companies, contacts, articles]; diff --git a/examples/app-starter/src/datasets/company.dataset.ts b/examples/app-starter/src/datasets/company.dataset.ts index 57e490ea8c1..cbe63a27e1e 100644 --- a/examples/app-starter/src/datasets/company.dataset.ts +++ b/examples/app-starter/src/datasets/company.dataset.ts @@ -7,10 +7,10 @@ import { defineDataset } from '@objectstack/spec/ui'; * select the dimension and measure by name. */ export const CompanyDataset = defineDataset({ - name: 'starter_company_metrics', + name: 'biz_company_metrics', label: 'Company Metrics', description: 'How many companies there are, by type and by industry', - object: 'starter_company', + object: 'biz_company', dimensions: [ { diff --git a/examples/app-starter/src/datasets/contact.dataset.ts b/examples/app-starter/src/datasets/contact.dataset.ts index bc149ba406d..d443afccf33 100644 --- a/examples/app-starter/src/datasets/contact.dataset.ts +++ b/examples/app-starter/src/datasets/contact.dataset.ts @@ -6,10 +6,10 @@ import { defineDataset } from '@objectstack/spec/ui'; * Contact counts (ADR-0021): the dashboard's contact tiles bind here. */ export const ContactDataset = defineDataset({ - name: 'starter_contact_metrics', + name: 'biz_contact_metrics', label: 'Contact Metrics', description: 'How many contacts there are, by company and by influence', - object: 'starter_contact', + object: 'biz_contact', dimensions: [ { diff --git a/examples/app-starter/src/objects/article.object.ts b/examples/app-starter/src/objects/article.object.ts new file mode 100644 index 00000000000..b437702af27 --- /dev/null +++ b/examples/app-starter/src/objects/article.object.ts @@ -0,0 +1,57 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { ObjectSchema, Field } from '@objectstack/spec/data'; + +/** + * A help article — a how-to guide, an answer to a common question, or a + * reference page — written in Markdown. + * + * `body` opens with the article's title as a `#` heading, then one `##` + * section per topic, each with its own text: the seed articles in + * `src/data/articles.ts` are written that way. A draft stays a draft until + * someone sets it to Published. + */ +export const Article = ObjectSchema.create({ + name: 'biz_article', + // Shared inside the organization, as the companies and contacts are. + sharingModel: 'public_read_write', + label: 'Article', + pluralLabel: 'Articles', + icon: 'book-open', + color: 'amber', + description: 'A help article: a how-to guide, a common question, or a reference page.', + nameField: 'title', + highlightFields: ['category', 'status', 'owner_id'], + + fields: { + title: Field.text({ + label: 'Title', + required: true, + searchable: true, + maxLength: 200, + }), + body: Field.markdown({ + label: 'Body', + }), + category: Field.select({ + label: 'Category', + options: [ + { label: 'How-to', value: 'how_to', color: '#3B82F6' }, + { label: 'FAQ', value: 'faq', color: '#10B981' }, + { label: 'Reference', value: 'reference', color: '#8B5CF6' }, + ], + }), + status: Field.select({ + label: 'Status', + options: [ + { label: 'Draft', value: 'draft', color: '#6B7280', default: true }, + { label: 'Published', value: 'published', color: '#10B981' }, + ], + }), + }, + + // The one Details section of the record page and of the create and edit form. + fieldGroups: [ + { key: 'basic', label: 'Article', fields: ['title', 'category', 'status', 'body'] }, + ], +}); diff --git a/examples/app-starter/src/objects/company.object.ts b/examples/app-starter/src/objects/company.object.ts index 2796c0c3d45..f3cdf217d35 100644 --- a/examples/app-starter/src/objects/company.object.ts +++ b/examples/app-starter/src/objects/company.object.ts @@ -6,7 +6,7 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; * A company the organization works with — a customer, a prospect, a supplier * or a partner. * - * The API names carry the package namespace (`starter_`), so a tenant that + * The API names carry the package namespace (`biz_`), so a tenant that * installs this starter beside a CRM package keeps both: the CRM's own account * and contact objects use other names. * @@ -14,7 +14,7 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; * `owner_id` column, set to the creator on insert. */ export const Company = ObjectSchema.create({ - name: 'starter_company', + name: 'biz_company', // Shared inside the organization: a starter workspace where everyone sees // every company. An organization that wants owner-only records changes this // after it installs the starter. @@ -78,6 +78,6 @@ export const Company = ObjectSchema.create({ // The company's record page lists its contacts. relatedLists: [ - { list: 'starter_contact', columns: ['name', 'title', 'email', 'phone'] }, + { list: 'biz_contact', columns: ['name', 'title', 'email', 'phone'] }, ], }); diff --git a/examples/app-starter/src/objects/contact.object.ts b/examples/app-starter/src/objects/contact.object.ts index a4ddb36a1fb..eb675fd266d 100644 --- a/examples/app-starter/src/objects/contact.object.ts +++ b/examples/app-starter/src/objects/contact.object.ts @@ -10,7 +10,7 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; * company (`company`), and the company's record page lists its contacts. */ export const Contact = ObjectSchema.create({ - name: 'starter_contact', + name: 'biz_contact', // Shared inside the organization, as the companies are. sharingModel: 'public_read_write', label: 'Contact', @@ -28,7 +28,7 @@ export const Contact = ObjectSchema.create({ searchable: true, maxLength: 120, }), - company: Field.lookup('starter_company', { + company: Field.lookup('biz_company', { label: 'Company', }), title: Field.text({ diff --git a/examples/app-starter/src/objects/index.ts b/examples/app-starter/src/objects/index.ts index 89a3487dfe4..a031b5d2a57 100644 --- a/examples/app-starter/src/objects/index.ts +++ b/examples/app-starter/src/objects/index.ts @@ -1,4 +1,5 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +export { Article } from './article.object.js'; export { Company } from './company.object.js'; export { Contact } from './contact.object.js'; diff --git a/examples/app-starter/src/translations/starter.translation.ts b/examples/app-starter/src/translations/starter.translation.ts index 562da8ca235..097cf689bb2 100644 --- a/examples/app-starter/src/translations/starter.translation.ts +++ b/examples/app-starter/src/translations/starter.translation.ts @@ -11,7 +11,7 @@ import { defineTranslationBundle } from '@objectstack/spec/system'; export const StarterTranslationBundle = defineTranslationBundle({ en: { objects: { - starter_company: { + biz_company: { label: 'Company', pluralLabel: 'Companies', fields: { @@ -25,7 +25,7 @@ export const StarterTranslationBundle = defineTranslationBundle({ owner_id: { label: 'Owner' }, }, }, - starter_contact: { + biz_contact: { label: 'Contact', pluralLabel: 'Contacts', fields: { @@ -39,11 +39,22 @@ export const StarterTranslationBundle = defineTranslationBundle({ owner_id: { label: 'Owner' }, }, }, + biz_article: { + label: 'Article', + pluralLabel: 'Articles', + fields: { + title: { label: 'Title' }, + body: { label: 'Body' }, + category: { label: 'Category' }, + status: { label: 'Status' }, + owner_id: { label: 'Owner' }, + }, + }, }, apps: { - starter_app: { + biz_app: { label: 'Starter', - description: 'Companies and contacts, with tasks and notes', + description: 'Companies, contacts and help articles, with tasks and notes', }, }, }, @@ -51,10 +62,10 @@ export const StarterTranslationBundle = defineTranslationBundle({ 'zh-CN': { // The package's own name, keyed by its manifest id (objectstack#35513). packages: { - 'com.example.starter': { name: '入门示例', description: '公司与联系人,菜单中附带平台的任务和备注。' }, + 'com.example.starter': { name: '入门示例', description: '公司、联系人与知识文章,菜单中附带平台的任务和备注。' }, }, objects: { - starter_company: { + biz_company: { label: '公司', pluralLabel: '公司', description: '与本组织往来的公司。', @@ -98,7 +109,7 @@ export const StarterTranslationBundle = defineTranslationBundle({ more: { label: '更多' }, }, }, - starter_contact: { + biz_contact: { label: '联系人', pluralLabel: '联系人', description: '往来公司里的人,不是本组织的员工。', @@ -130,15 +141,46 @@ export const StarterTranslationBundle = defineTranslationBundle({ more: { label: '更多' }, }, }, + biz_article: { + label: '知识文章', + pluralLabel: '知识文章', + description: '帮助文章:操作指南、常见问题或参考资料。', + fields: { + title: { label: '标题' }, + body: { label: '正文' }, + category: { + label: '分类', + options: { + how_to: '操作指南', + faq: '常见问题', + reference: '参考资料', + }, + }, + status: { + label: '状态', + options: { + draft: '草稿', + published: '已发布', + }, + }, + owner_id: { label: '负责人' }, + }, + _views: { + all: { label: '全部文章' }, + }, + _sections: { + basic: { label: '文章' }, + }, + }, }, apps: { - starter_app: { + biz_app: { label: '起步应用', - description: '公司和联系人,以及任务和备忘', + description: '公司、联系人与知识文章,菜单中附带平台的任务和备注。', }, }, datasets: { - starter_company_metrics: { + biz_company_metrics: { label: '公司统计', description: '公司有多少家,按类型和行业分', dimensions: { @@ -152,7 +194,7 @@ export const StarterTranslationBundle = defineTranslationBundle({ company_count: { label: '公司数', description: '公司有多少家,不论类型。' }, }, }, - starter_contact_metrics: { + biz_contact_metrics: { label: '联系人统计', description: '联系人有多少位,按公司和影响力分', dimensions: { @@ -165,7 +207,7 @@ export const StarterTranslationBundle = defineTranslationBundle({ }, }, dashboards: { - starter_overview_dashboard: { + biz_overview_dashboard: { label: '概览', description: '公司和联系人一览。', widgets: { diff --git a/examples/app-starter/src/views/article.view.ts b/examples/app-starter/src/views/article.view.ts new file mode 100644 index 00000000000..dad86bb44ac --- /dev/null +++ b/examples/app-starter/src/views/article.view.ts @@ -0,0 +1,36 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { defineView } from '@objectstack/spec'; + +/** + * Article list view: a grid of every help article with its category and + * status. + * + * No `form` here: the Console's create and edit form lays a record out by the + * object's `fieldGroups` (`article.object.ts`), and a declared default form is + * not loaded there. + */ +export const ArticleViews = defineView({ + list: { + label: 'All Articles', + type: 'grid', + data: { provider: 'object', object: 'biz_article' }, + columns: [ + { field: 'title' }, + { field: 'category' }, + { field: 'status' }, + ], + }, + listViews: { + all: { + label: 'All Articles', + type: 'grid', + data: { provider: 'object', object: 'biz_article' }, + columns: [ + { field: 'title' }, + { field: 'category' }, + { field: 'status' }, + ], + }, + }, +}); diff --git a/examples/app-starter/src/views/company.view.ts b/examples/app-starter/src/views/company.view.ts index 99c232f978c..529538825e3 100644 --- a/examples/app-starter/src/views/company.view.ts +++ b/examples/app-starter/src/views/company.view.ts @@ -13,7 +13,7 @@ export const CompanyViews = defineView({ list: { label: 'All Companies', type: 'grid', - data: { provider: 'object', object: 'starter_company' }, + data: { provider: 'object', object: 'biz_company' }, columns: [ { field: 'name' }, { field: 'type' }, @@ -27,7 +27,7 @@ export const CompanyViews = defineView({ all: { label: 'All Companies', type: 'grid', - data: { provider: 'object', object: 'starter_company' }, + data: { provider: 'object', object: 'biz_company' }, columns: [ { field: 'name' }, { field: 'type' }, @@ -40,7 +40,7 @@ export const CompanyViews = defineView({ by_type: { label: 'Companies by Type', type: 'kanban', - data: { provider: 'object', object: 'starter_company' }, + data: { provider: 'object', object: 'biz_company' }, columns: ['name', 'industry', 'phone'], kanban: { groupByField: 'type', diff --git a/examples/app-starter/src/views/contact.view.ts b/examples/app-starter/src/views/contact.view.ts index 41bf1f839ed..71b06d8e5ae 100644 --- a/examples/app-starter/src/views/contact.view.ts +++ b/examples/app-starter/src/views/contact.view.ts @@ -12,7 +12,7 @@ export const ContactViews = defineView({ list: { label: 'All Contacts', type: 'grid', - data: { provider: 'object', object: 'starter_contact' }, + data: { provider: 'object', object: 'biz_contact' }, columns: [ { field: 'name' }, { field: 'company' }, @@ -26,7 +26,7 @@ export const ContactViews = defineView({ all: { label: 'All Contacts', type: 'grid', - data: { provider: 'object', object: 'starter_contact' }, + data: { provider: 'object', object: 'biz_contact' }, columns: [ { field: 'name' }, { field: 'company' }, @@ -39,7 +39,7 @@ export const ContactViews = defineView({ by_influence: { label: 'Contacts by Influence', type: 'kanban', - data: { provider: 'object', object: 'starter_contact' }, + data: { provider: 'object', object: 'biz_contact' }, columns: ['name', 'company', 'title'], kanban: { groupByField: 'influence', diff --git a/examples/app-starter/src/views/index.ts b/examples/app-starter/src/views/index.ts index 540da647017..b037abce0db 100644 --- a/examples/app-starter/src/views/index.ts +++ b/examples/app-starter/src/views/index.ts @@ -1,4 +1,5 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +export { ArticleViews } from './article.view.js'; export { CompanyViews } from './company.view.js'; export { ContactViews } from './contact.view.js'; diff --git a/examples/app-starter/test/boot.test.ts b/examples/app-starter/test/boot.test.ts index c9c41ef6971..258910795be 100644 --- a/examples/app-starter/test/boot.test.ts +++ b/examples/app-starter/test/boot.test.ts @@ -3,9 +3,9 @@ /** * The starter, installed for real: the package goes in through the * marketplace install door as an unmanaged copy with its sample data (the - * starter path), its menu carries the four object entries (companies, - * contacts, and the platform's tasks and notes), and uninstalling it removes - * companies and contacts while every task and note stays. + * starter path), its menu carries the five object entries (companies, + * contacts, articles, and the platform's tasks and notes), and uninstalling it + * removes companies, contacts and articles while every task and note stays. * * One boot of a host with nothing of its own, every phase in `beforeAll`; the * `it`s only read what the phases recorded. The task and the note are written @@ -78,6 +78,7 @@ describe('app-starter — installed as a starter, menu, uninstall', () => { let app: Answer; let companies: Answer; let contacts: Answer; + let articles: Answer; let task: Answer; let note: Answer; let uninstall: Answer; @@ -95,18 +96,20 @@ describe('app-starter — installed as a starter, menu, uninstall', () => { // The copy is a writable package of its own, beside the package id. base = install.body?.data?.targetPackageId; - app = await call('GET', '/meta/app/starter_app'); - companies = await call('GET', '/data/starter_company'); - contacts = await call('GET', '/data/starter_contact'); + app = await call('GET', '/meta/app/biz_app'); + companies = await call('GET', '/data/biz_company'); + contacts = await call('GET', '/data/biz_contact'); + articles = await call('GET', '/data/biz_article'); task = await call('POST', '/data/sys_task', { title: 'Call Northwind about the renewal' }); note = await call('POST', '/data/sys_note', { title: 'Northwind visit', body: 'Met the purchasing team.' }); uninstall = await call('DELETE', `/packages/${base}`); - after.company = await call('GET', '/meta/object/starter_company'); - after.contact = await call('GET', '/meta/object/starter_contact'); - after.app = await call('GET', '/meta/app/starter_app'); + after.company = await call('GET', '/meta/object/biz_company'); + after.contact = await call('GET', '/meta/object/biz_contact'); + after.article = await call('GET', '/meta/object/biz_article'); + after.app = await call('GET', '/meta/app/biz_app'); after.task = await call('GET', `/data/sys_task/${unwrap(task)?.id}`); after.note = await call('GET', `/data/sys_note/${unwrap(note)?.id}`); }, 180_000); @@ -127,13 +130,24 @@ describe('app-starter — installed as a starter, menu, uninstall', () => { expect(olivia?.company).toBe(northwind?.id); }); - it('the menu carries companies, contacts, tasks and notes — tasks and notes are the platform objects', () => { + it('installs its sample help articles, one of them a draft', () => { + expect(articles.status, JSON.stringify(articles.body)).toBe(200); + expect(rows(articles).map((a) => a.title).sort()).toEqual([ + 'Meeting rooms reference', + 'Set up your new laptop', + 'Share files with your team', + 'Wi-Fi and printing FAQ', + ]); + expect(rows(articles).filter((a) => a.status === 'draft').map((a) => a.title)).toEqual(['Share files with your team']); + }); + + it('the menu carries companies, contacts, articles, tasks and notes — tasks and notes are the platform objects', () => { expect(app.status, JSON.stringify(app.body)).toBe(200); const objectEntries = (unwrap(app)?.navigation ?? []) .filter((n: any) => n.type === 'object') .map((n: any) => n.objectName); - expect(objectEntries).toEqual(['starter_company', 'starter_contact', 'sys_task', 'sys_note']); - expect((stack.objects ?? []).map((o) => o.name).sort()).toEqual(['starter_company', 'starter_contact']); + expect(objectEntries).toEqual(['biz_company', 'biz_contact', 'biz_article', 'sys_task', 'sys_note']); + expect((stack.objects ?? []).map((o) => o.name).sort()).toEqual(['biz_article', 'biz_company', 'biz_contact']); }); it('precondition: a task and a note were written before the uninstall', () => { @@ -143,10 +157,11 @@ describe('app-starter — installed as a starter, menu, uninstall', () => { expect(unwrap(note)?.id).toBeTruthy(); }); - it('uninstall removes companies, contacts and the app', () => { + it('uninstall removes companies, contacts, articles and the app', () => { expect(uninstall.status, JSON.stringify(uninstall.body)).toBe(200); expect(after.company.status, JSON.stringify(after.company.body)).toBe(404); expect(after.contact.status, JSON.stringify(after.contact.body)).toBe(404); + expect(after.article.status, JSON.stringify(after.article.body)).toBe(404); expect(after.app.status, JSON.stringify(after.app.body)).toBe(404); }); diff --git a/examples/app-starter/test/help-articles-38372.test.ts b/examples/app-starter/test/help-articles-38372.test.ts new file mode 100644 index 00000000000..e4dcc9d9de2 --- /dev/null +++ b/examples/app-starter/test/help-articles-38372.test.ts @@ -0,0 +1,116 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The seed help articles hold one Markdown shape, so each section reads on + * its own: the body opens with `# TITLE` (the record's own title), then 3 to 6 + * `##` sections, every section with text under its heading and, heading + * included, under 800 characters. One reference article carries a table + * followed by a one-line note, and one article is left a draft. + * + * Read off the seed definition itself, the rows the install door inserts. The + * blank template in create-objectstack carries the same seed; its parity test + * holds the two equal, so this shape holds there too. + */ + +import { describe, it, expect } from 'vitest'; +import { articles } from '../src/data/articles.js'; + +interface SeedArticle { title: string; body: string; category: string; status: string } + +const SECTION_LIMIT = 800; + +/** The body's `##` sections: each heading line with the text under it. */ +function sections(body: string): { heading: string; text: string; raw: string }[] { + const lines = body.split('\n'); + const out: { heading: string; text: string; raw: string }[] = []; + for (const line of lines) { + if (line.startsWith('## ')) out.push({ heading: line, text: '', raw: line }); + else if (out.length > 0) { + const last = out[out.length - 1]; + last.text += `${line}\n`; + last.raw += `\n${line}`; + } + } + return out.map((s) => ({ ...s, text: s.text.trim(), raw: s.raw.trimEnd() })); +} + +/** Every way an article breaks the shape, as readable sentences; empty when it holds. */ +function shapeProblems(article: SeedArticle): string[] { + const problems: string[] = []; + const lines = article.body.split('\n'); + if (lines[0] !== `# ${article.title}`) problems.push(`first line is not "# ${article.title}"`); + const firstSection = lines.findIndex((l) => l.startsWith('## ')); + const preamble = lines.slice(1, firstSection < 0 ? lines.length : firstSection).join('\n').trim(); + if (preamble) problems.push('text stands between the title and the first section'); + if (lines.slice(1).some((l) => /^# /.test(l))) problems.push('a second "# " heading'); + const found = sections(article.body); + if (found.length < 3 || found.length > 6) problems.push(`${found.length} sections, not 3 to 6`); + for (const s of found) { + if (!s.text) problems.push(`"${s.heading}" has no text`); + if (s.raw.length >= SECTION_LIMIT) problems.push(`"${s.heading}" is ${s.raw.length} characters`); + } + return problems; +} + +/** A Markdown table (header, separator, rows) followed by exactly one line of text, ending the section. */ +function hasTableThenOneLineNote(text: string): boolean { + const lines = text.split('\n'); + const start = lines.findIndex((l) => l.startsWith('|')); + if (start < 0 || !/^\|(\s*-+\s*\|)+$/.test(lines[start + 1] ?? '')) return false; + let end = start; + while (lines[end + 1]?.startsWith('|')) end++; + if (end - start < 2) return false; + const after = lines.slice(end + 1).filter((l) => l.trim() !== ''); + return after.length === 1 && !after[0].startsWith('|'); +} + +const records: SeedArticle[] = articles.records.map((r) => ({ + title: String(r.title), + body: String(r.body), + category: String(r.category), + status: String(r.status), +})); + +describe('seed help articles — one Markdown shape', () => { + it('reads the seed (vacuity guard): three to four articles, keyed by title', () => { + expect(articles.externalId).toBe('title'); + expect(records.length).toBeGreaterThanOrEqual(3); + expect(records.length).toBeLessThanOrEqual(4); + }); + + it.each(records.map((r) => [r.title, r] as const))('"%s" holds the shape', (_title, article) => { + expect(shapeProblems(article)).toEqual([]); + }); + + it('covers every category, and leaves exactly one article a draft', () => { + expect(new Set(records.map((r) => r.category))).toEqual(new Set(['how_to', 'faq', 'reference'])); + expect(records.filter((r) => r.status === 'draft')).toHaveLength(1); + expect(records.filter((r) => r.status === 'published').length).toBe(records.length - 1); + }); + + it('a reference article carries a table followed by a one-line note', () => { + const withTable = records + .filter((r) => r.category === 'reference') + .filter((r) => sections(r.body).some((s) => hasTableThenOneLineNote(s.text))); + expect(withTable.map((r) => r.title)).toHaveLength(1); + }); + + it('CONTROL: each break of the shape is caught', () => { + const good = records.find((r) => r.category === 'faq')!; + expect(shapeProblems(good)).toEqual([]); + const firstSection = good.body.indexOf('\n## '); + const cases: Record = { + 'wrong title': good.body.replace(`# ${good.title}`, '# Something else'), + 'empty section': good.body.replace('\n## ', '\n## A heading alone\n\n## '), + 'long section': `${good.body}\n\n## Long\n\n${'x'.repeat(SECTION_LIMIT)}`, + 'too few sections': good.body.slice(0, good.body.indexOf('\n## ', firstSection + 1)), + 'text before the first section': good.body.replace(`# ${good.title}\n`, `# ${good.title}\n\nIntro.\n`), + }; + for (const [name, body] of Object.entries(cases)) { + expect(shapeProblems({ ...good, body }), name).not.toEqual([]); + } + expect(hasTableThenOneLineNote('| a | b |\n| --- | --- |\n| 1 | 2 |\n\nOne note.')).toBe(true); + expect(hasTableThenOneLineNote('| a | b |\n| --- | --- |\n| 1 | 2 |\n\nOne note.\n\nA second.')).toBe(false); + expect(hasTableThenOneLineNote('| a | b |\n| --- | --- |\n| 1 | 2 |')).toBe(false); + }); +}); diff --git a/packages/apps/studio/src/index.ts b/packages/apps/studio/src/index.ts index 5b097f95976..5853f728bd3 100644 --- a/packages/apps/studio/src/index.ts +++ b/packages/apps/studio/src/index.ts @@ -21,7 +21,7 @@ * `@objectstack/setup` and `@objectstack/account`, and `plugin-auth`'s * manifest no longer registers Studio either (ADR-0048; see that plugin's own * header note). All three carry the same reason: the console ships a - * dedicated Studio surface at `/_console/studio//`, so Studio no + * dedicated Studio surface at `/_console/studio/`, so Studio no * longer needs to exist as a navigable app tile in a stock boot. */ diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 30bddac70ca..37426eeb5fd 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -237,7 +237,7 @@ **Check your permission sets in one step.** A permission set is affected when one of its `objects` entries, the `'*'` entry included, has `viewAllRecords: true` or `modifyAllRecords: true` and does not have `viewAllFields: true`. For each such entry, add `viewAllFields: true` to it if the set should still read every field of that object. Beside View All that is all the read needs: with the bit, the set reads what View All read before. Beside Modify All it is not: the set's own `readable: false` rows now bind (before, Modify All overrode them), so a field such a row hides stays hidden from the set's holders until you delete the row. For the edit, Modify All no longer grants one: where its holders must still edit a field another set locks, or a field the set's own field row names without `editable: true`, add an explicit `editable: true` row in the set that should edit it. - Sets in your source: `os migrate meta --from 18 --write` adds `viewAllFields: true` beside every such bit (ADR-0087 conversion `permission-view-all-fields-beside-record-bypass`). - - Sets saved in a running deployment (Studio-saved, stored in `sys_metadata`): they are **not** rewritten on upgrade, and from 19 they are read with the new meaning. Studio's permission matrix has no control for `viewAllFields` today (it keeps the key when it saves a set that already carries it), so add it to the set's entry through the metadata API. No command lists the affected stored sets yet; a review list is follow-up #37375. + - Sets saved in a running deployment (Studio-saved, stored in `sys_metadata`): they are **not** rewritten on upgrade, and from 19 they are read with the new meaning. Studio's permission matrix has no control for `viewAllFields` today (it keeps the key when it saves a set that already carries it), so add it to the set's entry through the metadata API. To find them, run `os migrate meta --stored`: it lists each affected entry of a stored set under `viewAllFieldsReview` (read-only), and you fix each listed entry by adding `viewAllFields: true` to it through the metadata API. The protocol-19 upgrade guide carries the same check as the semantic entry `permission-view-all-modify-all-cast-no-field-vote`. diff --git a/packages/cli/src/commands/migrate/meta.stored-actor.test.ts b/packages/cli/src/commands/migrate/meta.stored-actor.test.ts index f093bd22ed9..cbbfd0390cf 100644 --- a/packages/cli/src/commands/migrate/meta.stored-actor.test.ts +++ b/packages/cli/src/commands/migrate/meta.stored-actor.test.ts @@ -21,6 +21,21 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import MigrateMeta from './meta.js'; +// The packages the command reaches through dynamic imports, loaded at module top so the +// first load is paid during collection, never inside a clocked case (`check:test-source-alias`). +import '@objectstack/cloud-connection'; +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/metadata'; +import '@objectstack/metadata-protocol'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-hono-server'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/service-automation'; +import '@objectstack/service-datasource'; +import '@objectstack/service-settings'; +import '@objectstack/service-storage'; const boot = vi.hoisted(() => vi.fn()); vi.mock('../../utils/schema-migrate.js', () => ({ bootSchemaStack: boot })); @@ -47,6 +62,7 @@ const CLEAN_REPORT = { failed: 0, rows: [], decisionModeReview: [], + viewAllFieldsReview: [], }; const migrateStoredMetadata = vi.fn(); diff --git a/packages/cli/src/commands/migrate/meta.stored-view-all-fields.test.ts b/packages/cli/src/commands/migrate/meta.stored-view-all-fields.test.ts new file mode 100644 index 00000000000..9ace1ae7660 --- /dev/null +++ b/packages/cli/src/commands/migrate/meta.stored-view-all-fields.test.ts @@ -0,0 +1,144 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `os migrate meta --stored` — the review list of stored permission sets whose + * View All / Modify All lost their field reach in protocol 19 (maintainer + * ruling option A on #36055). + * + * A stored set keeps the 19 meaning (the bits widen records only), and the + * upgrade text owes operators a one-step check of which stored sets are + * affected. The pass names each `objects` entry carrying `viewAllRecords` or + * `modifyAllRecords` and no `viewAllFields` under `viewAllFieldsReview`; this + * file pins what the COMMAND prints and emits for it: the list and its fix in + * the terminal, beside the on-protocol verdict, read-only (exit 0), and the + * key on `--json`, including the report the command builds itself when + * `sys_metadata` does not exist yet. + * + * The boot is replaced, so no database is opened; the command's own parse, + * control flow and the real report renderer run. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import MigrateMeta from './meta.js'; +// The packages the command reaches through dynamic imports, loaded at module top so the +// first load is paid during collection, never inside a clocked case (`check:test-source-alias`). +import '@objectstack/cloud-connection'; +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/metadata'; +import '@objectstack/metadata-protocol'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-hono-server'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/service-automation'; +import '@objectstack/service-datasource'; +import '@objectstack/service-settings'; +import '@objectstack/service-storage'; + +const boot = vi.hoisted(() => vi.fn()); +vi.mock('../../utils/schema-migrate.js', () => ({ bootSchemaStack: boot })); +vi.mock('../../utils/migrate-occupancy-gate.js', () => ({ + OCCUPANCY_HINT: 'occupancy hint', + probeMigrationTarget: vi.fn(async () => ({ status: 'free' })), +})); +vi.mock('../../utils/data-migration-plugins.js', () => ({ buildDataMigrationPlugins: vi.fn(async () => []) })); + +const HERE = dirname(fileURLToPath(import.meta.url)); +const CLI_ROOT = resolve(HERE, '..', '..', '..'); +/** oclif builds its whole command table on the first `run()` in a process. */ +const RUN_TIMEOUT = 60_000; + +const SCOPE = { id: 'r_1', name: 'ops_auditor', organizationId: null, packageId: null, state: 'active' as const }; + +/** An on-protocol run that names two entries of one stored set for review. */ +const REPORT = { + apply: false, + protocol: '19.0.0', + scanned: 1, + canonical: 1, + pending: 0, + rewritten: 0, + skipped: 0, + failed: 0, + rows: [], + decisionModeReview: [], + viewAllFieldsReview: [ + { ...SCOPE, object: 'ops_ticket', bits: ['viewAllRecords'] }, + { ...SCOPE, object: '*', bits: ['viewAllRecords', 'modifyAllRecords'] }, + ], +}; + +const migrateStoredMetadata = vi.fn(); +let tableAbsent: (name: string) => boolean; +let written: string[]; +let printed: string[]; +let stdout: ReturnType; +let stderr: ReturnType; +let log: ReturnType; + +beforeEach(() => { + migrateStoredMetadata.mockReset(); + migrateStoredMetadata.mockResolvedValue(REPORT); + tableAbsent = () => false; + boot.mockReset(); + boot.mockResolvedValue({ + kernel: { getService: (name: string) => (name === 'protocol' ? { migrateStoredMetadata } : undefined) }, + dbLabel: 'file:test.db', + tableAbsent: (name: string) => tableAbsent(name), + shutdown: vi.fn(async () => {}), + }); + written = []; + printed = []; + // `emitJson` awaits the write's DRAIN callback, so the double invokes it. + stdout = vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown, enc?: unknown, cb?: unknown) => { + written.push(String(chunk)); + const done = typeof enc === 'function' ? enc : cb; + if (typeof done === 'function') done(); + return true; + }) as typeof process.stdout.write); + stderr = vi.spyOn(process.stderr, 'write').mockImplementation((() => true) as typeof process.stderr.write); + log = vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => { + printed.push(args.map(String).join(' ')); + }); +}); +afterEach(() => { + stdout.mockRestore(); + stderr.mockRestore(); + log.mockRestore(); +}); + +describe('os migrate meta --stored — the stored permission sets View All / Modify All no longer open fields for (ruling A on #36055)', () => { + it('prints each listed entry and the `viewAllFields: true` fix, beside the on-protocol verdict', async () => { + await MigrateMeta.run(['--stored'], { root: CLI_ROOT }); + + const text = printed.join('\n'); + expect(text).toMatch(/2 object entry\(ies\) in 1 stored permission set row\(s\) hold View All or Modify All/); + expect(text).toContain("permission/ops_auditor [env-wide] — objects entry 'ops_ticket' (viewAllRecords)"); + expect(text).toContain("permission/ops_auditor [env-wide] — objects entry '*' (viewAllRecords, modifyAllRecords)"); + expect(text).toContain('add `viewAllFields: true` to the entry through the metadata API'); + expect(text).toMatch(/already on protocol/); + // Read-only: the list asks nothing of the pass, so the preview asks for no write. + expect(migrateStoredMetadata.mock.calls[0][0].apply).toBe(false); + }, RUN_TIMEOUT); + + it('--json carries the list under `viewAllFieldsReview`, and the run stays clean', async () => { + await MigrateMeta.run(['--stored', '--json'], { root: CLI_ROOT }); + + const out = JSON.parse(written.join('')); + expect(out.viewAllFieldsReview.map((r: { object: string }) => r.object)).toEqual(['ops_ticket', '*']); + expect(out.clean).toBe(true); + }, RUN_TIMEOUT); + + it('a database with no `sys_metadata` yet answers an empty list, not a missing key', async () => { + tableAbsent = (name) => name === 'sys_metadata'; + + await MigrateMeta.run(['--stored', '--json'], { root: CLI_ROOT }); + + expect(migrateStoredMetadata).not.toHaveBeenCalled(); + const out = JSON.parse(written.join('')); + expect(out).toMatchObject({ scanned: 0, decisionModeReview: [], viewAllFieldsReview: [] }); + }, RUN_TIMEOUT); +}); diff --git a/packages/cli/src/commands/migrate/meta.ts b/packages/cli/src/commands/migrate/meta.ts index 6da115733f1..10999902e8f 100644 --- a/packages/cli/src/commands/migrate/meta.ts +++ b/packages/cli/src/commands/migrate/meta.ts @@ -686,6 +686,8 @@ function printWriteOutcome(outcome: WriteOutcome, appliedCount: number): void { for (const m of plan.manual) { const a = m.application; console.log(` ${chalk.yellow('•')} ${a.path}: ${a.from} → ${a.to} ${chalk.dim(`(${a.conversionId})`)}`); + // The path names its items by position; the line names them as the author does. + if (m.items) console.log(chalk.dim(` where ${m.items.map((i) => `${i.at} is \`${i.name}\``).join(', ')}`)); console.log(chalk.dim(` not written [${m.refusal.kind}]: ${m.refusal.reason}`)); } console.log(''); @@ -1606,6 +1608,7 @@ export default class MigrateMeta extends Command { failed: 0, rows: [], decisionModeReview: [], + viewAllFieldsReview: [], }; const report: StoredMigrationReport = reads.absent('sys_metadata') ? noStoredRows diff --git a/packages/cli/src/commands/migrate/stored-forms.integration.test.ts b/packages/cli/src/commands/migrate/stored-forms.integration.test.ts new file mode 100644 index 00000000000..39648eaec7d --- /dev/null +++ b/packages/cli/src/commands/migrate/stored-forms.integration.test.ts @@ -0,0 +1,242 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `os migrate stored-forms` against a real SQLite database: the read-only run + * of the stored-form ceremony (ADR-0159 D7, card ⑤a). + * + * ## The fixture + * + * A compiled artifact (`dist/objectstack.json`) whose package ships an object + * and a linked public form in an old shape (`formViews.contact`), over a + * database an older release left behind with, bound to no package: + * + * - a `viewKind: 'form'` row of the package's form that switches it off + * (moves into the package's pair as a declared override); + * - a `viewKind: 'form'` row whose form content cannot be read (holds the + * upgrade). + * + * The command runs in-process through oclif, as the binary runs it. The + * census writes nothing: the stored rows and `sys_packages` read the same + * after it, and no pair is created. + */ + +import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'; +import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { isExitSignal } from '../../utils/format.js'; +import { bootSchemaStack } from '../../utils/schema-migrate.js'; +import MigrateStoredForms from './stored-forms.js'; + +// [#10126] Pay the first transform of these dist-resolved workspace deps at +// MODULE LOAD: the command reaches them through dynamic `import()`s inside +// `run()`, which vitest clocks (`scripts/check-test-source-alias.mjs`). +import '@objectstack/runtime'; +import '@objectstack/metadata-protocol'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/rest'; +import '@objectstack/plugin-security'; +import '@objectstack/service-datasource'; +import '@objectstack/driver-turso'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const CLI_ROOT = resolve(HERE, '..', '..', '..'); +const CASE_TIMEOUT_MS = 180_000; + +const PKG = 'com.example.m37111'; +const PAIR = `${PKG}.custom`; +const OBJECT = 'm37111_inquiry'; +const FORM = `${OBJECT}.contact`; +const BROKEN = `${OBJECT}.broken`; +const SLUG = 'contact-m37111'; +const formBody = (enabled: boolean) => ({ + type: 'simple', + sections: [{ fields: ['name'] }], + data: { provider: 'object', object: OBJECT }, + sharing: { publicLink: `/forms/${SLUG}`, enabled, allowAnonymous: true }, +}); +const ARTIFACT = { + manifest: { id: PKG, name: 'm37111', version: '2.3.0', type: 'app', namespace: 'm37111' }, + objects: [{ + name: OBJECT, + label: 'Inquiry', + sharingModel: 'private', + fields: { name: { name: 'name', label: 'Name', type: 'text' } }, + }], + views: [{ object: OBJECT, list: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } }, formViews: { contact: formBody(true) } }], +}; + +interface SeedRow { type: string; name: string; state: string; body: Record; packageId?: string } +const SEED: SeedRow[] = [ + { type: 'view', name: FORM, state: 'active', body: { name: FORM, object: OBJECT, viewKind: 'form', label: 'Switched off', config: formBody(false) } }, +]; +const BROKEN_SEED: SeedRow = { + type: 'view', name: BROKEN, state: 'active', + body: { name: BROKEN, object: OBJECT, viewKind: 'form', sharing: { publicLink: `/forms/${SLUG}`, enabled: true } }, +}; + +let dir: string; +let emptyDb: string; +let templateDb: string; +let brokenTemplateDb: string; +const savedCwd = process.cwd(); +const ENV_KEYS = ['OS_ARTIFACT_PATH', 'OS_DATABASE_URL', 'DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME', 'NODE_ENV', + 'OS_AUTH_SECRET', 'AUTH_SECRET', 'BETTER_AUTH_SECRET', 'OS_ENVIRONMENT_ID'] as const; +const savedEnv: Record = {}; + +let caseSeq = 0; +function caseDb(template: string): string { + caseSeq += 1; + const file = join(dir, 'cases', `${caseSeq}.db`); + mkdirSync(dirname(file), { recursive: true }); + copyFileSync(template, file); + return file; +} + +/** The rows an older release left, written at the driver the way that release stored them. */ +async function insertRows(dbFile: string, rows: readonly SeedRow[]): Promise { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: dbFile }, useNullAsDefault: true }); + try { + const k = (driver as any).knex; + const now = new Date().toISOString(); + let n = 0; + for (const row of rows) { + n += 1; + await k('sys_metadata').insert({ + id: `seed_${n}`, type: row.type, name: row.name, package_id: row.packageId ?? null, state: row.state, + version: 1, checksum: null, created_at: now, updated_at: now, metadata: JSON.stringify(row.body), + }); + } + } finally { + await driver.disconnect(); + } +} + +/** Every `sys_metadata` row and every `sys_packages` id, read on a connection of our own. */ +async function storeSnapshot(dbFile: string): Promise { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: dbFile }, useNullAsDefault: true }); + try { + const k = (driver as any).knex; + const rows = await k('sys_metadata').select('type', 'name', 'package_id', 'state', 'metadata'); + const packages = await k('sys_packages').select('id').catch(() => []); + return JSON.stringify([ + rows.map((r: any) => `${r.type}/${r.name}@${r.package_id ?? '-'}/${r.state} ${r.metadata}`).sort(), + packages.map((r: any) => String(r.id)).sort(), + ]); + } finally { + await driver.disconnect(); + } +} + +interface RunResult { payload: any; exitCode: number } + +/** Run the command through oclif and capture its one JSON document. */ +async function runJson(argv: string[]): Promise { + const savedExit = process.exitCode; + const swallow = ((_chunk: unknown, ...rest: unknown[]) => { + const cb = rest.find((a) => typeof a === 'function') as (() => void) | undefined; + if (cb) cb(); + return true; + }) as typeof process.stdout.write; + const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(swallow); + vi.spyOn(process.stderr, 'write').mockImplementation(swallow); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); + let thrownExit: number | undefined; + try { + try { + await MigrateStoredForms.run(argv, { root: CLI_ROOT }); + } catch (error) { + if (!isExitSignal(error)) throw error; + thrownExit = (error as { oclif?: { exit?: number } }).oclif?.exit; + } + const out = stdout.mock.calls.map((c) => String(c[0])).join('').trim(); + let payload: any; + try { payload = JSON.parse(out); } catch { payload = { unparsed: out.slice(-400) }; } + return { payload, exitCode: thrownExit ?? (process.exitCode as number | undefined) ?? 0 }; + } finally { + process.exitCode = savedExit; + vi.restoreAllMocks(); + } +} + +beforeAll(async () => { + for (const key of ENV_KEYS) savedEnv[key] = process.env[key]; + for (const key of ENV_KEYS) delete process.env[key]; + process.env.NODE_ENV = 'production'; + dir = mkdtempSync(join(tmpdir(), 'os-37111-')); + mkdirSync(join(dir, 'dist'), { recursive: true }); + process.env.OS_HOME = join(dir, 'home'); + process.env.OS_ARTIFACT_PATH = join(dir, 'dist', 'objectstack.json'); + writeFileSync(process.env.OS_ARTIFACT_PATH, JSON.stringify(ARTIFACT)); + + emptyDb = join(dir, 'empty.db'); + const seed = await bootSchemaStack({ jsonOutput: false, databaseUrl: `file:${emptyDb}`, projectRoot: dir, hydrateMetadata: false }); + await seed.shutdown(); + templateDb = join(dir, 'template.db'); + copyFileSync(emptyDb, templateDb); + await insertRows(templateDb, SEED); + brokenTemplateDb = join(dir, 'broken-template.db'); + copyFileSync(emptyDb, brokenTemplateDb); + await insertRows(brokenTemplateDb, [...SEED, BROKEN_SEED]); +}, CASE_TIMEOUT_MS); + +afterAll(() => { + process.chdir(savedCwd); + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + try { rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ } +}); + +// The command takes `process.cwd()` as the project root, as a real invocation does. +beforeEach(() => { process.chdir(dir); }); +afterEach(() => { process.chdir(savedCwd); }); + +describe('os migrate stored-forms', () => { + it('on a database with no stored form lists nothing, says the upgrade can switch, and exits 0', async () => { + const db = caseDb(emptyDb); + const { payload, exitCode } = await runJson(['--database-url', `file:${db}`, '--json']); + expect(payload.error, JSON.stringify(payload).slice(0, 600)).toBeUndefined(); + expect(exitCode).toBe(0); + expect(payload.canSwitch).toBe(true); + expect(payload.forms).toEqual([]); + expect(payload.holds).toEqual([]); + }, CASE_TIMEOUT_MS); + + it('lists the package-less switch-off row as moving into the pair as a declared override, and writes nothing', async () => { + const db = caseDb(templateDb); + const before = await storeSnapshot(db); + const { payload, exitCode } = await runJson(['--database-url', `file:${db}`, '--json']); + expect(payload.error, JSON.stringify(payload).slice(0, 600)).toBeUndefined(); + expect(exitCode).toBe(0); + const plan = payload.forms.find((f: any) => f.form === FORM); + expect(plan).toMatchObject({ + address: { kind: 'base', packageId: PKG }, + outcome: 'move', + destination: { kind: 'pair_override', base: PKG, pair: PAIR, basedOn: '2.3.0' }, + served: { type: 'view', name: FORM, withdraws: SLUG }, + }); + expect(payload.canSwitch).toBe(true); + expect(await storeSnapshot(db)).toBe(before); + }, CASE_TIMEOUT_MS); + + it('a body the projection cannot read holds the upgrade: canSwitch false, the row named with its action, still exit 0', async () => { + const db = caseDb(brokenTemplateDb); + const before = await storeSnapshot(db); + const { payload, exitCode } = await runJson(['--database-url', `file:${db}`, '--json']); + expect(payload.error, JSON.stringify(payload).slice(0, 600)).toBeUndefined(); + expect(exitCode).toBe(0); + expect(payload.canSwitch).toBe(false); + expect(payload.holds).toEqual([expect.objectContaining({ + cause: 'unreadable', + row: expect.objectContaining({ name: BROKEN }), + action: expect.stringContaining('Save the view again'), + })]); + expect(await storeSnapshot(db)).toBe(before); + }, CASE_TIMEOUT_MS); +}); diff --git a/packages/cli/src/commands/migrate/stored-forms.test.ts b/packages/cli/src/commands/migrate/stored-forms.test.ts new file mode 100644 index 00000000000..ab79859ea88 --- /dev/null +++ b/packages/cli/src/commands/migrate/stored-forms.test.ts @@ -0,0 +1,51 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it, vi } from 'vitest'; +import type { StoredFormAddressPlan, StoredFormCensus } from '@objectstack/metadata-protocol'; +import { storedFormRunRefusal } from './stored-forms.js'; + +// The report's sentence is read alone: no stack is booted here, so nothing the +// command loads to boot one is loaded (each package the boot reaches is mocked). +vi.mock('@objectstack/metadata-protocol', () => ({})); +vi.mock('@objectstack/rest', () => ({})); +vi.mock('@objectstack/runtime', () => ({})); +vi.mock('@objectstack/plugin-security', () => ({})); +vi.mock('@objectstack/platform-objects/plugin', () => ({})); +vi.mock('@objectstack/driver-sql', () => ({})); +vi.mock('@objectstack/driver-turso', () => ({})); +vi.mock('@objectstack/service-datasource', () => ({})); + +const ROW = { type: 'view', name: 'crm_lead.intake', form: 'crm_lead.intake' } as const; +const plan = (outcome: StoredFormAddressPlan['outcome'], extra: Record = {}): StoredFormAddressPlan => ({ + form: 'crm_lead.intake', address: { kind: 'environment' }, served: ROW, behind: [], untouched: [], alsoReadAt: [], outcome, + ...(outcome === 'move' || outcome === 'keep' ? { destination: { kind: 'environment_form' } } : {}), + ...(outcome === 'left_in_place' ? { reason: 'served_by_no_door' } : {}), + ...extra, +} as unknown as StoredFormAddressPlan); +const census = (forms: StoredFormAddressPlan[], canSwitch = true): StoredFormCensus => ({ + forms, unreadable: [], drafts: [], sharedSlugs: [], + precheck: { canSwitch, holds: [], counts: { keep: 0, move: 0, remove: 0, hold: 0, left_in_place: 0 } }, +}); +const engine = (transactions: boolean) => ({ + transaction: async (fn: () => Promise) => fn(), + getDefaultDriverName: () => 'default', + getDriverByName: () => ({ beginTransaction: async () => ({}), supports: { transactionsUnsupported: !transactions } }), +}); + +describe('[ADR-0159 D7] the census report says where the upgrade\'s run will be refused (a database that cannot roll back)', () => { + it('a census that moves a row, on a driver that cannot roll back: the report names the driver and what to do (ablate: the report\'s read of the rollback)', () => { + const text = storedFormRunRefusal(census([plan('move')]), engine(false)); + expect(text).toContain("'default' cannot roll back"); + expect(text).toContain('supports transactions'); + expect(text).toContain('stay on the release'); + }); + + it('CONTROL: the same census on a driver that can roll back says nothing more', () => { + expect(storedFormRunRefusal(census([plan('move')]), engine(true))).toBeUndefined(); + }); + + it('CONTROL: a census that writes and takes nothing, or that holds the upgrade, says nothing more', () => { + expect(storedFormRunRefusal(census([plan('left_in_place'), plan('keep')]), engine(false))).toBeUndefined(); + expect(storedFormRunRefusal(census([plan('move')], false), engine(false))).toBeUndefined(); + }); +}); diff --git a/packages/cli/src/commands/migrate/stored-forms.ts b/packages/cli/src/commands/migrate/stored-forms.ts new file mode 100644 index 00000000000..51a30db2db7 --- /dev/null +++ b/packages/cli/src/commands/migrate/stored-forms.ts @@ -0,0 +1,344 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { Command, Flags } from '@oclif/core'; +import chalk from 'chalk'; +import { STACK_TIER_PRESETS, engineCanRollBack } from '@objectstack/core'; +import { + printHeader, + printSuccess, + printWarning, + printError, + printInfo, + printStep, + createTimer, + emitJson, + errorCodeFields, + isExitSignal, +} from '../../utils/format.js'; +import type { + StoredFormAddress, + StoredFormAddressPlan, + StoredFormCensus, + StoredFormHold, + StoredFormRowRef, +} from '@objectstack/metadata-protocol'; +import { bootSchemaStack } from '../../utils/schema-migrate.js'; +import { describeUnloadableHostConfig } from '../../utils/schema-migration-plugins.js'; +import { absentTableReads } from '../../utils/absent-table-reads.js'; +import { probeMigrationTarget } from '../../utils/migrate-occupancy-gate.js'; +import { describeOccupancy, JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite-occupancy.js'; + + +const EMPTY: StoredFormCensus = { + forms: [], + unreadable: [], + drafts: [], + sharedSlugs: [], + precheck: { canSwitch: true, holds: [], counts: { keep: 0, move: 0, remove: 0, hold: 0, left_in_place: 0 } }, +}; + +/** + * [ADR-0159 D7] The sentence the report adds where the upgrade's run will be + * refused: it writes only on a database that can roll a transaction back, and + * this census plans a write or a removal. `undefined` otherwise. + */ +export function storedFormRunRefusal(census: StoredFormCensus, engine: unknown): string | undefined { + if (!census.precheck.canSwitch) return undefined; + const writes = census.forms.some((plan) => plan.outcome === 'move' || plan.outcome === 'remove' + || (plan.outcome === 'keep' && (plan.carries !== undefined || plan.behind.length > 0))); + if (!writes || engineCanRollBack(engine)) return undefined; + const driver = (engine as { getDefaultDriverName?: () => string | undefined } | null | undefined)?.getDefaultDriverName?.(); + return `The upgrade's run will be refused on this database: the default driver${driver !== undefined ? ` '${driver}'` : ''} cannot roll back a transaction, and the upgrade moves stored forms all or nothing. ` + + 'Run the upgrade against a database whose driver supports transactions, or stay on the release you are running.'; +} + +/** One row as the report names it. */ +export function storedFormRowText(row: StoredFormRowRef): string { + const where = row.packageId !== undefined ? `package '${row.packageId}'` : 'no package'; + const member = row.name !== row.form ? ` (member '${row.form}')` : ''; + return `${row.type} "${row.name}"${member}, ${where}`; +} + +/** An address as the report names it. */ +export function storedFormAddressText(address: StoredFormAddress): string { + switch (address.kind) { + case 'base': return `at read-only package '${address.packageId}'`; + case 'package': return `at package '${address.packageId}'`; + case 'environment': return 'in the environment (no package ships it)'; + } +} + +/** What the ceremony does at one address, in one sentence. */ +export function storedFormPlanText(plan: StoredFormAddressPlan): string { + return storedFormPlanSentence(plan) + + (plan.untouched.length > 0 ? `; ${plan.untouched.length} row(s) behind it that hold no form at the name stay as stored` : '') + + plan.alsoReadAt.map((e) => `; ${storedFormRowText(e.row)} is also read ${storedFormAddressText(e.address)}, where it ${e.served ? 'is served and ' : 'stands behind, and the address '}${OUTCOME_WORD[e.outcome]}`).join(''); +} + +const OUTCOME_WORD: Record = { + keep: 'is kept', + move: 'moves', + remove: 'is removed', + hold: 'holds the upgrade', + left_in_place: 'is left in place', +}; + +/** A held row is folded into no other row (ADR-0159 D7): the report names it apart. */ +function heldApartText(rows: readonly StoredFormRowRef[] | undefined): string { + return rows !== undefined && rows.length > 0 + ? `; not folded into it while it holds the upgrade where it is served, and this line stands only while that hold does: ${rows.map(storedFormRowText).join('; ')}` + : ''; +} + +function storedFormPlanSentence(plan: StoredFormAddressPlan): string { + const folded = plan.behind.length > 0 ? `; ${plan.behind.length} form row(s) behind it fold into it` : ''; + switch (plan.outcome) { + case 'keep': + return `kept: ${storedFormRowText(plan.served)} is already the form row${folded}${heldApartText(plan.heldApart)}` + + (plan.carries ? `; it takes the withdrawal of ${storedFormRowText(plan.carries.from)}` : '') + + (plan.newlyClosed ? ` — NEWLY CLOSED: /forms/${plan.carries?.slug} is open today and answers 404 after the upgrade; switch it on again in Setup if it should stay open` : ''); + case 'move': { + const to = plan.destination.kind === 'pair_override' + ? `the declared override in '${plan.destination.pair}' (overrides '${plan.destination.base}', basedOn ${plan.destination.basedOn})` + : plan.destination.kind === 'pair_form' + ? `a form of '${plan.destination.pair}' of its own, declaring no override ('${plan.destination.base}' ships no form of the name)` + : plan.destination.kind === 'package_form' + ? `a form row of package '${plan.destination.packageId}'` + : 'a form row of the environment'; + return `moves: ${storedFormRowText(plan.served)} → ${to}, its body as written${folded}${heldApartText(plan.heldApart)}` + + (plan.carries ? `; it takes the withdrawal of ${storedFormRowText(plan.carries.from)}` : '') + + (plan.draftsLeftBehind && plan.draftsLeftBehind.length > 0 ? `; its draft is left behind as stored, and cannot be published after the upgrade` : '') + + (plan.newlyClosed ? ` — NEWLY CLOSED: /forms/${plan.carries?.slug} is open today and answers 404 after the upgrade; switch it on again in Setup if it should stay open` : ''); + } + case 'remove': + return `will be removed: ${storedFormRowText(plan.served)} is an internal record form (no public link, no action opens it)` + + (plan.behind.length > 0 ? `, with the ${plan.behind.length} form row(s) behind it` : '') + // A row behind that another address serves is not part of the removal (ADR-0159 D7-e). + + (plan.servedElsewhere !== undefined && plan.servedElsewhere.length > 0 + ? `; not removed with it, because another address serves it: ${plan.servedElsewhere.map(storedFormRowText).join('; ')}` + : '') + + (plan.object !== undefined + ? `. New and Edit of '${plan.object}' follow its field groups, ${plan.objectHasFieldGroups ? 'which it declares' : 'and it declares none'}` + : ''); + case 'hold': + return `HOLDS THE UPGRADE: ${storedFormRowText(plan.served)} — ${plan.refusal} ${plan.action}` + // A row kept as stored at another address under ruling 7249158572 is listed apart, whatever this plan holds for. + + (plan.heldApart !== undefined && plan.heldApart.length > 0 + ? ` Listed apart, kept as stored at another address under ruling 7249158572: ${plan.heldApart.map(storedFormRowText).join('; ')}.` + : ''); + case 'left_in_place': + switch (plan.reason) { + case 'served_no_form': + return `left in place: ${storedFormRowText(plan.served)} carries no form at the name and is the row served for it, so nothing is served for the name today and no row of it moves` + + (plan.behind.length > 0 ? ` (${plan.behind.map(storedFormRowText).join('; ')})` : ''); + case 'internal_ahead_of_linked_row': + return `left in place: ${storedFormRowText(plan.served)} is an internal record form, and it is not removed because ${plan.behind.filter((r) => r.link !== undefined).map(storedFormRowText).join('; ')}, which declares a public link, stands behind it; both rows stay as stored, and the address keeps answering 404`; + case 'served_unreadable': + return `waits: ${storedFormRowText(plan.served)} cannot be read (listed below)`; + case 'served_by_no_door': + return `left in place: ${storedFormRowText(plan.served)} is a form no door serves today, so the upgrade leaves it as stored and no row of it moves`; + } + } +} + +function holdText(hold: StoredFormHold): string { + return `${storedFormRowText(hold.row)}${hold.base !== undefined ? ` over '${hold.base}'` : ''} — ${hold.refusal} ${hold.action}`; +} + +/** + * `os migrate stored-forms` — the read-only run of the stored-form ceremony + * (ADR-0159 D7, card ⑤a): what the upgrade to the next protocol major does with + * every stored row that holds a form in an old shape (a `view` container's + * `form`, a `formViews` entry, a `viewKind: 'form'` item), and the precheck — + * whether that upgrade may switch. + * + * ## Why read-only + * + * The ceremony moves rows between two types, so it is all or nothing with the + * switch to the major: its write is reached only from the major's upgrade + * command, which runs the ceremony and then the precheck, and switches only + * when no row holds it (ruling `7142585849` 2, addendum `7142658348`). This + * command is the administrator's look before upgrading. ⛔ It has no + * `--apply`. + * + * ## What it says + * + * Per form name and package address (the census of `listStoredFormsOf`, + * `@objectstack/metadata-protocol`, whose module header holds the rules): + * kept, moved (and where), removed (an internal record form), left in place, + * or holding the upgrade — a row whose base's pair cannot be ensured, a body + * the projection cannot read, a slot of a pair more than one plan claims, or + * a row several addresses serve that would not all move it or all remove it, + * each with its cause and the action for it. The rows behind the served one + * fold into it, except a row that holds the upgrade, which the report lists + * apart; a withdrawal a folded row + * carries that no layer reads today closes a form that is open today, and the + * report names it newly closed. + * + * The deployment is composed as `os serve` composes it — the host config's + * plugins and the application or the compiled artifact — so the packages that + * ship a form are the ones the server serves. `--preset` and `--dev` are + * `serve`'s two flags that move that composition, with its meaning. The boot + * is read-only (deferred DDL, no seed, no file brought into existence). + * + * Exit status: 0 when the census ran, whatever it found (`precheck.canSwitch` + * in `--json` says whether the upgrade would switch); 1 when the composition + * could not be read or booted. + */ +export default class MigrateStoredForms extends Command { + static override description = + 'List what the upgrade to the next protocol major does with the stored rows that hold a form in an old shape ' + + '(a view container\'s form, a formViews entry, a viewKind: \'form\' item), and whether it can switch: the rows ' + + 'it moves, folds and removes, and the rows that hold it, with the action for each (ADR-0159 D7). Read-only.'; + + static override examples = [ + '$ os migrate stored-forms', + '$ os migrate stored-forms --json', + ]; + + static override flags = { + 'database-url': Flags.string({ + description: 'Database to examine (defaults to $OS_DATABASE_URL / the project DB)', + env: 'OS_DATABASE_URL', + }), + json: Flags.boolean({ description: 'Output the machine-readable result as JSON.' }), + preset: Flags.string({ + description: 'Compose as `os serve --preset` does: the tier preset the stack falls back to when it declares ' + + 'no tiers. Pass what the deployment boots with.', + options: Object.keys(STACK_TIER_PRESETS), + }), + dev: Flags.boolean({ + description: 'Compose as `os serve --dev` does: the config\'s devPlugins and the development .env files. ' + + 'Pass it when the deployment boots with --dev (`os dev`).', + }), + }; + + async run(): Promise { + const { flags } = await this.parse(MigrateStoredForms); + const timer = createTimer(); + if (!flags.json) printHeader('Migrate · stored-forms'); + + const occupancy = await probeMigrationTarget(flags['database-url'], { dev: flags.dev === true }); + if (occupancy.status === 'busy' && !flags.json) { + printWarning(`${describeOccupancy(occupancy)} The census below writes no row or table. ${JOURNAL_MODE_SWITCH_NOTE}`); + } + if (occupancy.status === 'unknown' && !flags.json) { + printWarning(`Could not check whether the database is in use — ${occupancy.detail}`); + } + if (!flags.json) printStep('Composing the deployment (read-only)…'); + + let stack; + try { + stack = await bootSchemaStack({ + jsonOutput: flags.json, + ...(flags['database-url'] ? { databaseUrl: flags['database-url'] } : {}), + composeHostStack: true, + composeAuthGatedSecurity: true, + serveFlags: { dev: flags.dev === true, ...(flags.preset ? { preset: flags.preset } : {}) }, + deferSchemaDdl: true, + readOnlyProbe: true, + }); + } catch (error: any) { + if (flags.json) { await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); this.exit(1); return; } + printError(error.message || String(error)); + this.exit(1); + return; + } + + let exitCode = 0; + try { + exitCode = await this.report(stack, flags.json === true, timer); + } catch (error: any) { + if (isExitSignal(error)) throw error; + exitCode = 1; + if (flags.json) await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); + else printError(error.message || String(error)); + } finally { + await stack.shutdown(); + } + if (exitCode !== 0) this.exit(exitCode); + } + + private async report( + stack: Awaited>, + json: boolean, + timer: { elapsed: () => number; display: () => string }, + ): Promise { + const unloadable = describeUnloadableHostConfig(stack.composition); + if (unloadable !== null) { + if (json) await emitJson({ error: 'host_config_unloadable', message: unloadable }, 0, { compact: true }); + else printError(unloadable); + return 1; + } + const protocol = stack.kernel.getService('protocol') as object | undefined; + // The census reads the protocol instance through its host (`listStoredFormsOf`, + // `@objectstack/metadata-protocol`): a function beside the facade, not a method on it. + const { listStoredFormsOf } = await import('@objectstack/metadata-protocol'); + if (typeof (protocol as { getMetaItems?: unknown } | undefined)?.getMetaItems !== 'function') { + throw new Error( + 'No metadata protocol on this stack, so sys_metadata cannot be read. ' + + 'Run this from the project root whose stack registers the ObjectQL engine.', + ); + } + const reads = absentTableReads(stack); + const census = reads.absent('sys_metadata') ? EMPTY : await listStoredFormsOf(protocol as Parameters[0]); + const { precheck } = census; + const runRefused = storedFormRunRefusal(census, (protocol as { engine?: unknown }).engine); + + if (json) { + reads.notice(true); + await emitJson({ + database: stack.dbLabel, + hostConfig: stack.composition.hostConfigPath, + canSwitch: precheck.canSwitch, + ...(runRefused !== undefined ? { runRefused } : {}), + counts: precheck.counts, + holds: precheck.holds, + forms: census.forms, + unreadable: census.unreadable, + drafts: census.drafts, + sharedSlugs: census.sharedSlugs, + duration: timer.elapsed(), + }); + return 0; + } + + printInfo(`Database: ${chalk.white(stack.dbLabel)}`); + if (stack.composition.hostConfigPath) printInfo(`Host config: ${chalk.white(stack.composition.hostConfigPath)}`); + reads.notice(false); + console.log(''); + if (census.forms.length === 0 && census.unreadable.length === 0 && census.drafts.length === 0) { + printSuccess(`No stored row holds a form in an old shape — nothing for the upgrade to move ${chalk.dim(`(${timer.display()})`)}`); + return 0; + } + if (census.forms.length > 0) { + console.log(chalk.bold(`${census.forms.length} form(s) in stored rows:`)); + for (const plan of census.forms) console.log(` • '${plan.form}' ${storedFormAddressText(plan.address)}: ${storedFormPlanText(plan)}`); + console.log(''); + } + if (census.unreadable.length > 0) { + console.log(chalk.bold(`${census.unreadable.length} stored view(s) whose form content cannot be read (each holds the upgrade):`)); + for (const hold of census.unreadable) console.log(` • ${holdText(hold)}`); + console.log(''); + } + if (census.drafts.length > 0) { + console.log(chalk.bold(`${census.drafts.length} draft view row(s) with form content in an old shape, neither moved nor deleted. After the upgrade an old-shape draft cannot be published: publish the ones you want to keep first.`)); + for (const d of census.drafts) console.log(` • ${d.type} "${d.name}", ${d.packageId !== undefined ? `package '${d.packageId}'` : 'no package'}`); + console.log(''); + } + for (const shared of census.sharedSlugs) { + printInfo(`/forms/${shared.slug} is declared by ${shared.forms.map((f) => `'${f}'`).join(' and ')}.`); + } + const c = precheck.counts; + printInfo(`${c.keep} kept, ${c.move} to move, ${c.remove} to remove, ${c.left_in_place} left in place, ${precheck.holds.length} holding the upgrade.`); + if (runRefused !== undefined) { + printWarning(runRefused); + } else if (precheck.canSwitch) { + printSuccess(`The upgrade can switch: no stored row holds it ${chalk.dim(`(${timer.display()})`)}`); + } else { + // Each hold prints the action for its own cause; not every cause can be removed on this release (ADR-0159 D7-c). + printWarning(`The upgrade would not switch: ${precheck.holds.length} row(s) hold it. Each is listed above with the action for its cause.`); + } + return 0; + } +} diff --git a/packages/cli/src/commands/package/install.ts b/packages/cli/src/commands/package/install.ts index bfb85e2d0d2..a1cb7303653 100644 --- a/packages/cli/src/commands/package/install.ts +++ b/packages/cli/src/commands/package/install.ts @@ -139,6 +139,35 @@ function printWithheldMaps(withheldMaps: unknown): void { console.log(' Re-enter each map where the connector is authored.'); } +/** + * [ADR-0090 D5] The package's `isDefault` permission sets the `everyone` + * position still waits on, as the managed install-local answer names them + * (`pendingSuggestions`): one warning, one line per suggestion — the set and + * the suggesting package — then where it is accepted, each element's own + * `hint` verbatim. Installing never accepts a suggestion, so until a + * `manage_metadata` holder does, a member without a grant of the set is + * refused on what it grants; the operator who installed is told here. + * + * Printed from the answer only: an answer without the list (nothing pending, + * or a runtime that predates the key) prints nothing, and nothing is guessed + * from the artifact the command sent. + */ +function printPendingSuggestions(pendingSuggestions: unknown): void { + const pending: Array<{ permissionSet?: unknown; packageId?: unknown; hint?: unknown }> = + Array.isArray(pendingSuggestions) ? pendingSuggestions : []; + if (pending.length === 0) return; + console.log(''); + printWarning( + `${pending.length} permission set(s) are suggested for every signed-in member (the Everyone position) and NOT ` + + 'accepted: installing never accepts one. Until each is accepted, a member without a grant of the set is refused:', + ); + for (const entry of pending) { + const from = typeof entry.packageId === 'string' ? ` (suggested by ${entry.packageId})` : ''; + console.log(` ${String(entry.permissionSet)}${from}`); + if (typeof entry.hint === 'string' && entry.hint.trim()) console.log(` ${entry.hint.trim()}`); + } +} + export default class PackageInstall extends Command { static override description = 'Install a package into a running ObjectStack runtime (catalog id or local artifact file)'; @@ -634,6 +663,7 @@ export default class PackageInstall extends Command { if (data.installedAt) printKV(' Installed', String(data.installedAt)); if (notHotLoaded && hotLoadError) printKV(' Hot-load error', hotLoadError); printWithheldMaps(data.withheldMaps); + printPendingSuggestions(data.pendingSuggestions); console.log(''); // #6721: the cache directory is quoted from the RESPONSE, never from a // literal or a locally-resolved constant. The directory lives on the diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts index b0da5637d08..93e7c7aa40c 100644 --- a/packages/cli/src/commands/serve.ts +++ b/packages/cli/src/commands/serve.ts @@ -4738,7 +4738,7 @@ export default class Serve extends Command { // plugin-auth's manifest into their own one-app packages. Register // each after AuthPlugin (best-effort; skipped if not installed). // NOTE: @objectstack/studio is intentionally NOT default-loaded — the - // console ships a dedicated Studio surface at /_console/studio//, + // console ships a dedicated Studio surface at /_console/studio/, // so Studio no longer needs to exist as a navigable app tile. for (const [appPkg, factory] of [ ['@objectstack/setup', 'createSetupAppPlugin'], diff --git a/packages/cli/src/commands/test.ts b/packages/cli/src/commands/test.ts index d1733563922..8781d34046e 100644 --- a/packages/cli/src/commands/test.ts +++ b/packages/cli/src/commands/test.ts @@ -224,7 +224,7 @@ export function loadTestSuite(file: string): QA.TestSuite { throw new Error( `${file} is not a valid Quality Protocol suite (TestSuiteSchema):\n${issues}\n` + ` Expected shape: ${SUITE_SHAPE}\n` + - ` Reference: content/docs/references/qa/testing.mdx`, + ` Reference: https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/qa/testing.md`, ); } diff --git a/packages/cli/src/commands/validate-json-strict-exit.e2e.test.ts b/packages/cli/src/commands/validate-json-strict-exit.e2e.test.ts index ac70ddd63f7..c64bedb1ed2 100644 --- a/packages/cli/src/commands/validate-json-strict-exit.e2e.test.ts +++ b/packages/cli/src/commands/validate-json-strict-exit.e2e.test.ts @@ -170,7 +170,15 @@ export default defineStack({ }, { strict: false }); `; -/** The zero-warning control — pins the other end of the matrix. */ +/** + * The zero-warning control — pins the other end of the matrix. + * + * The app opens its object from navigation and the object declares a list + * view: without the entry the app-shell rules raise `app-navigation-empty` and + * `object-unreachable-from-navigation`, and with the entry but no view they + * raise `object-without-view`, each a warning `--strict` promotes. The fixtures + * below copy this object and app, for the same reason. + */ const CLEAN_SOURCE = ` import { defineStack } from '@objectstack/spec'; @@ -181,8 +189,13 @@ export default defineStack({ label: 'Ticket', sharingModel: 'private', fields: { title: { type: 'text', label: 'Title' } }, + listViews: { all: { type: 'grid', columns: ['title'] } }, + }], + apps: [{ + name: 'strictexit_app', + label: 'Strict Exit App', + navigation: [{ id: 'nav_ticket', type: 'object', label: 'Tickets', objectName: 'strictexit_ticket' }], }], - apps: [{ name: 'strictexit_app', label: 'Strict Exit App' }], }, { strict: false }); `; @@ -210,8 +223,13 @@ export default defineStack({ label: 'Ticket', sharingModel: 'private', fields: { title: { type: 'text', label: 'Title' } }, + listViews: { all: { type: 'grid', columns: ['title'] } }, + }], + apps: [{ + name: 'strictexit_app', + label: 'Strict Exit App', + navigation: [{ id: 'nav_ticket', type: 'object', label: 'Tickets', objectName: 'strictexit_ticket' }], }], - apps: [{ name: 'strictexit_app', label: 'Strict Exit App' }], flows: [{ name: 'strictexit_notify', label: 'Notify', @@ -249,8 +267,13 @@ export default defineStack({ label: 'Ticket', sharingModel: 'private', fields: { title: { type: 'text', label: 'Title' } }, + listViews: { all: { type: 'grid', columns: ['title'] } }, + }], + apps: [{ + name: 'strictexit_app', + label: 'Strict Exit App', + navigation: [{ id: 'nav_ticket', type: 'object', label: 'Tickets', objectName: 'strictexit_ticket' }], }], - apps: [{ name: 'strictexit_app', label: 'Strict Exit App' }], ${finding === 'info' ? ` permissions: [{ name: 'strictexit_reader', label: 'Reader', objects: { strictexit_ticket: { allowRead: true } } }],` : ` tools: [{ diff --git a/packages/cli/src/utils/authored-source-codemod.ts b/packages/cli/src/utils/authored-source-codemod.ts index 024c1223835..e85b92aedb5 100644 --- a/packages/cli/src/utils/authored-source-codemod.ts +++ b/packages/cli/src/utils/authored-source-codemod.ts @@ -144,6 +144,20 @@ export interface WrittenSite { export interface ManualSite { application: MigrationApplication; refusal: CodemodRefusal; + /** + * The elements the site's path indexes into, by the name each goes by, + * outermost first: the path names them by position only + * (`packages[6].manifest.permissions[3]…`). Absent when no indexed element + * on the path carries a name. + */ + items?: PathItem[]; +} + +/** An indexed element on a site's path, and the name it goes by. */ +export interface PathItem { + /** The indexed segment as the path spells it, e.g. `permissions[3]`. */ + at: string; + name: string; } /** One file the plan rewrites: its bytes before and after. */ @@ -257,6 +271,40 @@ export function formatPath(path: readonly Segment[]): string { return out; } +/** + * The name an element of a collection goes by: its `name`, else its `id`, else + * — for a composition's package entry, `{ manifest: … }` — its manifest's `id` + * or `name`. + */ +function itemName(element: unknown): string | undefined { + if (!isPlainObject(element)) return undefined; + const own = [element.name, element.id]; + const manifest = element.manifest; + const candidates = isPlainObject(manifest) ? [...own, manifest.id, manifest.name] : own; + return candidates.find((c): c is string => typeof c === 'string' && c !== ''); +} + +/** The named elements `path` (an `applied[].path`) indexes into in `stack`, outermost first. */ +export function pathItems(stack: unknown, path: string): PathItem[] { + const items: PathItem[] = []; + let node = stack; + let at = ''; + for (const seg of parsePath(path)) { + if (typeof seg === 'number') { + if (!Array.isArray(node) || seg >= node.length) break; + node = node[seg]; + at = `${at}[${seg}]`; + const name = itemName(node); + if (name !== undefined) items.push({ at, name }); + } else { + if (!isPlainObject(node)) break; + node = node[seg]; + at = seg; + } + } + return items; +} + /** Parse an `applied[].path` (`a.b[0].c`) into segments. */ export function parsePath(path: string): Segment[] { const out: Segment[] = []; @@ -1152,6 +1200,19 @@ class Locator { return this.graph.resolveExpr(inputs.file, inputs.node.elements[index]!, trail); } + /** + * Why package `seg` of a composition cannot be traced to its input: input + * `j`, before it, could not be read (`reason` is the refusal it raised), so + * the packages before `seg` cannot be counted. + */ + private unknownSource(node: Extract, j: number, seg: number, reason: string): string { + const { inputs } = node; + const element = inputs.k === 'array' ? inputs.node.elements[j] : undefined; + const input = inputs.k === 'array' && element ? `input ${j} (\`${this.graph.snippet(inputs.file, element)}\`)` : `input ${j}`; + return `which input of \`${node.describe}\` built package ${seg} is unknown: ${input}, before it, ` + + `is not read as a stack literal (${reason}), so the packages it contributes cannot be counted`; + } + private step(node: SNode, seg: Segment, trail: Trail, rtParent: unknown, atRoot: boolean): SNode { const g = this.graph; switch (node.k) { @@ -1203,13 +1264,24 @@ class Locator { // literal with a `manifest` and no `packages` list of its own. The // inputs before i are read on a trail of their own — they are not // the site, so their bindings take no part in its shared check. + // + // An input before i that cannot be read leaves the count unknown, so + // which input built package i is unknown too: the refusal names that + // input as the blocker and says so, never passing the reason it gives + // for itself off as the site's (input 0's builder is not package i's). let input: SNode | undefined; for (let j = 0; j <= seg; j++) { - input = this.composedInput(node.inputs, j, j === seg ? trail : new Trail()); + try { + input = this.composedInput(node.inputs, j, j === seg ? trail : new Trail()); + if (input.k === 'object' && j < seg) g.findProp(input, 'manifest'); + } catch (error) { + if (j === seg || !(error instanceof Refusal)) throw error; + refuse(error.refusal.kind, this.unknownSource(node, j, seg, error.refusal.reason)); + } if (input.k !== 'object') { refuse('helper', `input ${j} of \`${node.describe}\` is not written as a stack literal, so the package it contributes cannot be read`); } - g.findProp(input, 'manifest'); + if (j === seg) g.findProp(input, 'manifest'); if (writesKey(g, input, 'packages')) { refuse('helper', `input ${j} of \`${node.describe}\` carries its own \`packages\`, so its packages are not one body each`); } @@ -1903,7 +1975,8 @@ export async function planAuthoredSourceWrite(input: AuthoredSourceWriteInput): ? { rewrite: input.range, status: 'manual', refusal: site.refusal } : { rewrite: input.range, status: 'written', file: site.file, line: site.line }; } else if ('refusal' in site) { - manual.push({ application, refusal: site.refusal }); + const items = pathItems(input.normalized, application.path); + manual.push({ application, refusal: site.refusal, ...(items.length > 0 ? { items } : {}) }); } else { written.push({ application, file: site.file, line: site.line }); } diff --git a/packages/cli/src/utils/console.ts b/packages/cli/src/utils/console.ts index e3b4b99a70e..cbd085f4758 100644 --- a/packages/cli/src/utils/console.ts +++ b/packages/cli/src/utils/console.ts @@ -64,8 +64,8 @@ const PUBLIC_FORM_DOOR = '/api/v1/forms'; /** * The Console's public form page, `/f/` under {@link CONSOLE_PATH}: the - * page the `/forms/:slug` redirect lands on, and the one page the Console's - * public-forms screen offers as an ``; - const formatReact = (slug: string) => - ``; - - /** `label` is the whole translated toast ("Copied URL"). */ - const copy = async (label: string, value: string) => { - try { - await navigator.clipboard.writeText(value); - toast.success(label); - } catch { - toast.error(t('console.developer.publicForms.clipboardUnavailable', { defaultValue: 'Clipboard unavailable' })); - } - }; - - const publish = async () => { - if (!publishView || !publishSlug) return; - const cand = publishable.find((p) => p.name === publishView); - if (!cand) return; - const slug = sanitizeSlug(publishSlug); - if (!slug) { - toast.error(t('console.developer.publicForms.invalidSlug', { defaultValue: 'Invalid slug' })); - return; - } - setPublishing(true); - try { - // The form body is the STORED item's `config` (module header). - const stored = await readStoredFormView(cand.name); - const config = stored.form; - const next = { - ...stored.item, - config: { - ...config, - sharing: { - ...(config.sharing ?? {}), - enabled: true, - allowAnonymous: true, - publicLink: `/forms/${slug}`, - }, - }, - }; - await client.meta.saveItem('view', cand.name, next); - toast.success(t('console.developer.publicForms.published', { defaultValue: 'Published {{name}}', name: cand.name })); - setPublishOpen(false); - setPublishView(''); - setPublishSlug(''); - await load(); - } catch (e: any) { - toast.error(t('console.developer.publicForms.publishFailed', { defaultValue: 'Publish failed: {{message}}', message: formatMetadataError(e) })); - } finally { - setPublishing(false); - } - }; - - const openEditor = async (row: PublicFormRow) => { - // The dialog edits the stored form (module header): its thank-you text is - // prefilled from the stored `submitBehavior`, never the served one. The - // slug is the served rule's, which reads no translated key. - let stored: StoredFormView; - try { - stored = await readStoredFormView(row.name); - } catch (e: any) { - toast.error(t('console.developer.publicForms.saveFailed', { defaultValue: 'Save failed: {{message}}', message: formatMetadataError(e) })); - return; - } - setEditRow({ ...stored, label: row.label }); - setEditSlug(row.slug); - const sb = stored.form.submitBehavior; - const kind = (sb?.kind as any) ?? 'thank-you'; - setEditBehavior(kind); - setEditBehaviorTitle(sb?.title ?? ''); - setEditBehaviorMessage(sb?.message ?? ''); - setEditBehaviorUrl(sb?.url ?? ''); - setEditUrlRefusal(null); - setEditOpen(true); - }; - - const saveEdit = async () => { - if (!editRow) return; - const slug = sanitizeSlug(editSlug); - if (!slug) { - toast.error(t('console.developer.publicForms.invalidSlug', { defaultValue: 'Invalid slug' })); - return; - } - setEditUrlRefusal(null); - let submitBehavior: any; - switch (editBehavior) { - case 'thank-you': - submitBehavior = { kind: 'thank-you' }; - if (editBehaviorTitle) submitBehavior.title = editBehaviorTitle; - if (editBehaviorMessage) submitBehavior.message = editBehaviorMessage; - break; - case 'redirect': { - // The contract's verdict, not this dialog's: empty is one of the seven - // families the spec refuses, so it comes back through here too rather - // than keeping a local `required` message that says less. - const verdict = checkSubmitRedirectUrl(editBehaviorUrl); - if (!verdict.ok) { - setEditUrlRefusal(verdict.refusal); - return; - } - // The value the schema accepted, so a future normalisation in the spec - // is what gets saved — the same read-back the renderer does. - submitBehavior = { kind: 'redirect', url: verdict.url }; - break; - } - case 'continue': - case 'next-record': - submitBehavior = { kind: editBehavior }; - break; - } - // `sharing` and `submitBehavior` both belong to the form, which on a - // ViewItem is its `config`: the stored one the dialog was opened on - // (module header). - const form = editRow.form; - const next = { - ...editRow.item, - config: { - ...form, - sharing: { - ...(form.sharing ?? {}), - enabled: true, - allowAnonymous: true, - publicLink: `/forms/${slug}`, - }, - submitBehavior, - }, - }; - setSaving(true); - try { - await client.meta.saveItem('view', editRow.name, next); - toast.success(t('console.developer.publicForms.saved', { defaultValue: 'Saved {{name}}', name: editRow.name })); - setEditOpen(false); - setEditRow(null); - await load(); - } catch (e: any) { - toast.error(t('console.developer.publicForms.saveFailed', { defaultValue: 'Save failed: {{message}}', message: formatMetadataError(e) })); - } finally { - setSaving(false); - } - }; - - const hasRows = rows.length > 0; - - const behaviorLabels: Record = { - 'thank-you': t('console.developer.publicForms.behaviorThankYou', { defaultValue: 'Show a thank-you panel' }), - redirect: t('console.developer.publicForms.behaviorRedirect', { defaultValue: 'Redirect to a URL' }), - continue: t('console.developer.publicForms.behaviorContinue', { defaultValue: 'Reset for another response' }), - 'next-record': t('console.developer.publicForms.behaviorNextRecord', { defaultValue: 'Advance to next record (internal queues)' }), - }; - const submitBehaviorOptions = SUBMIT_BEHAVIOR_KINDS.map((value) => ({ value, label: behaviorLabels[value] })); - const publishLabel = t('console.developer.publicForms.publishButton', { defaultValue: 'Publish form…' }); - - return ( -
- - -
- - - {t('console.developer.publicForms.title', { defaultValue: 'Public Forms' })} - - - {t('console.developer.publicForms.description', { - defaultValue: - 'Forms anyone can fill out — no login required. Publish a form to get a shareable link; submissions land directly in the bound object.', - })} - -
-
- - -
-
- - {error && ( -
- {error} -
- )} - {!loading && !hasRows && ( -
-

{t('console.developer.publicForms.emptyTitle', { defaultValue: 'No public forms yet' })}

-

- {withSlots( - t('console.developer.publicForms.emptyBody', { - defaultValue: - 'Click {{action}} above to share an existing form, or build a new one in Views & Apps and mark it public.', - action: SLOT[0], - }), - [{publishLabel}], - )} -

-
- )} - {hasRows && ( - - - - {t('console.developer.publicForms.columnName', { defaultValue: 'Name' })} - {t('console.developer.publicForms.columnObject', { defaultValue: 'Object' })} - {t('console.developer.publicForms.columnSlug', { defaultValue: 'Slug' })} - {t('console.developer.publicForms.columnPublicUrl', { defaultValue: 'Public URL' })} - {t('common.actions', { defaultValue: 'Actions' })} - - - - {rows.map((row) => { - const url = formatPublicUrl(row.slug); - return ( - - -
- {row.label ?? row.name} - {row.name} -
-
- - {row.object ? ( - {row.object} - ) : ( - - )} - - - {row.slug} - - - - {url} - - - - -
- - - - -
-
-
- ); - })} -
-
- )} -
-
- - - - - {t('console.developer.publicForms.publishDialogTitle', { defaultValue: 'Publish a FormView' })} - - {withSlots( - t('console.developer.publicForms.publishDialogDescription', { - defaultValue: - 'Pick an existing FormView to open it to anonymous visitors. Publishing sets {{enabled}}, {{allowAnonymous}} and {{publicLink}} in its config: the public form route serves a form only when all three are set.', - enabled: SLOT[0], - allowAnonymous: SLOT[1], - publicLink: SLOT[2], - }), - [ - sharing.enabled, - sharing.allowAnonymous, - sharing.publicLink, - ], - )} - - -
-
- - ({ - value: p.name, - label: `${p.label ?? p.name} (${p.name}) ${p.object ? `· ${p.object}` : ''}`, - })), - ]} - onPick={setPublishView} - /> -
-
- -
- {`${publicFormPath}/`} - setPublishSlug(e.target.value)} - /> -
-

- {t('console.developer.publicForms.slugHint', { defaultValue: 'Lowercase letters, digits, dashes and underscores only.' })} -

-
-
- - - - -
-
- - - - - - {editRow - ? t('console.developer.publicForms.editTitle', { defaultValue: 'Edit {{name}}', name: editRow.label ?? editRow.name }) - : t('console.developer.publicForms.editTitleFallback', { defaultValue: 'Edit form' })} - - - {t('console.developer.publicForms.editDescription', { defaultValue: 'Configure the public URL and what happens after submit.' })} - - -
-
- -
- {`${publicFormPath}/`} - setEditSlug(e.target.value)} - /> -
-
-
- - { - setEditBehavior(kind); - setEditUrlRefusal(null); - }} - /> -
- {editBehavior === 'thank-you' && ( - <> -
- - setEditBehaviorTitle(e.target.value)} - /> -
-
- - setEditBehaviorMessage(e.target.value)} - /> -
- - )} - {editBehavior === 'redirect' && ( -
- - {/* - Not `type="url"`: that type's own notion of valid is an - ABSOLUTE URL, which is the one thing this key refuses, so it - pulled the author the wrong way — as did the former - `https://example.com/thanks` placeholder. - */} - { - setEditBehaviorUrl(e.target.value); - setEditUrlRefusal(null); - }} - aria-invalid={editUrlRefusal ? true : undefined} - aria-describedby={editUrlRefusal ? 'edit-url-refusal' : 'edit-url-hint'} - /> - {editUrlRefusal ? ( - - ) : ( -

- {withSlots( - t('console.developer.publicForms.redirectHint', { - defaultValue: - 'An in-app path, starting with {{slash}} — interpolate a field of the submitted record as {{token}}. To send the browser out of the app, use an app navigation item instead.', - slash: SLOT[0], - token: SLOT[1], - }), - [/, {'{{record.field_name}}'}], - )} -

- )} -
- )} -
- - - - -
-
-
- ); -} diff --git a/ui/apps/console/src/pages/developer/consolePagesLocale-13460.test.tsx b/ui/apps/console/src/pages/developer/consolePagesLocale-13460.test.tsx index cb289741074..19751f2d188 100644 --- a/ui/apps/console/src/pages/developer/consolePagesLocale-13460.test.tsx +++ b/ui/apps/console/src/pages/developer/consolePagesLocale-13460.test.tsx @@ -1,12 +1,17 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectui#13460 — four routed console pages speak the session's language. + * objectui#13460 — three routed console pages speak the session's language. * - * Developer → API Console, Developer → Public Forms, Developer → Integrations & - * APIs and System → AI Approvals imported nothing from `@object-ui/i18n`, so a - * zh / ja / ar operator got an English page. They now read - * `console.developer.*` / `console.system.*` keys. + * Developer → API Console, Developer → Integrations & APIs and System → AI + * Approvals imported nothing from `@object-ui/i18n`, so a zh / ja / ar + * operator got an English page. They now read `console.developer.*` / + * `console.system.*` keys. + * + * The card's fourth page, Developer → Public Forms, is retired with its + * `console.developer.publicForms.*` keys (objectstack#37087): a form is + * designed in Studio's form editor and its public link is switched in Setup → + * Public forms, and both read their own keys. * * What this file pins, through the real pages and a real `I18nProvider`: * - under zh each page draws its heading and a sample of its copy from the @@ -51,7 +56,6 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); // Imported after the mocks so the pages pick them up. import { ApiConsolePage } from './ApiConsolePage'; -import { PublicFormsPage } from './PublicFormsPage'; import { IntegrationsPage } from './IntegrationsPage'; import { AiPendingActionsPage } from '../system/AiPendingActionsPage'; @@ -97,7 +101,6 @@ describe('console pages under zh (objectui#13460)', () => { it('guard: the zh values read below are real zh rows, not English copies', () => { for (const [zhValue, enValue] of [ [zhDev.apiConsole.endpointsTitle, enDev.apiConsole.endpointsTitle], - [zhDev.publicForms.title, enDev.publicForms.title], [zhDev.integrations.title, enDev.integrations.title], [zhSys.aiApprovals.title, en.console.system.aiApprovals.title], ]) { @@ -118,18 +121,6 @@ describe('console pages under zh (objectui#13460)', () => { expect(container.textContent).not.toMatch(LEAK); }); - it('Public Forms: the card, the empty state with its action in place, and the toolbar', async () => { - const { container } = page(, 'zh'); - expect(await screen.findByText(zhDev.publicForms.emptyTitle)).toBeTruthy(); - expect(screen.getByText(zhDev.publicForms.title)).toBeTruthy(); - expect(screen.getByRole('button', { name: zhDev.publicForms.publishButton })).toBeTruthy(); - const strong = screen.getByText(zhDev.publicForms.publishButton, { selector: 'strong' }); - expect(strong.parentElement!.textContent).toBe( - zhDev.publicForms.emptyBody.replace('{{action}}', zhDev.publicForms.publishButton), - ); - expect(container.textContent).not.toMatch(LEAK); - }); - it('Integrations & APIs: the header, the cards, and the auth sentence with its three elements', async () => { const { container } = page(, 'zh'); expect(await screen.findByText(zhDev.integrations.noObjects)).toBeTruthy(); @@ -163,14 +154,6 @@ describe('control: with no provider each page reads its English (objectui#13460) expect(strong.parentElement!.textContent).toBe('Select an endpoint or type a URL and click Send'); }); - it('Public Forms', async () => { - page(, null); - const strong = await screen.findByText('Publish form…', { selector: 'strong' }); - expect(strong.parentElement!.textContent).toBe( - 'Click Publish form… above to share an existing form, or build a new one in Views & Apps and mark it public.', - ); - }); - it('Integrations & APIs', async () => { page(, null); const action = await screen.findByText('Open API Console', { selector: 'strong' }); diff --git a/ui/apps/console/src/pages/developer/developerMetadataEnvelope.contractEnvelope-6917.test.tsx b/ui/apps/console/src/pages/developer/developerMetadataEnvelope.contractEnvelope-6917.test.tsx index 4c2c0778044..708a3696b7e 100644 --- a/ui/apps/console/src/pages/developer/developerMetadataEnvelope.contractEnvelope-6917.test.tsx +++ b/ui/apps/console/src/pages/developer/developerMetadataEnvelope.contractEnvelope-6917.test.tsx @@ -1,8 +1,13 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * The two developer pages read a `client.meta.getItems()` answer as the - * metadata API DECLARES it — and do NOT read `value` (objectui#6917 arm B). + * A developer page reads a `client.meta.getItems()` answer as the metadata API + * DECLARES it — and does NOT read `value` (objectui#6917 arm B). + * + * The card fixed two pages, Flow Runs and Public Forms. Public Forms is + * retired (objectstack#37087: a form is a `form` item, designed in Studio and + * switched in Setup, whose readers have their own tests), so Flow Runs is the + * page pinned here. The census below is the card's, taken over both. * * ── The seam is NOT `DataSource.find()`, and that changed the measurement ── * objectui#6917 filed these two sites as "the same arm objectui#6840 removed", @@ -41,12 +46,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, cleanup, waitFor } from '@testing-library/react'; -// The page asks the router where the anonymous route is served (objectui#11769), -// so it renders inside one, as it does in the app. -import { MemoryRouter } from 'react-router-dom'; /** - * One mutable answer, read by BOTH pages' `meta.getItems`. A stable singleton + * One mutable answer, read by the page's `meta.getItems`. A stable singleton * adapter: a fresh object per render loops the pages' load effects. Its client * is a singleton too, as the real adapter's `getClient()` is: Flow Runs keys its * flow and run loads on the client, so a fresh one per call re-ran them on @@ -73,9 +75,8 @@ vi.mock('@object-ui/app-shell', async (importOriginal) => ({ })); vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); -// Imported AFTER the mocks so the pages pick them up. +// Imported AFTER the mocks so the page picks them up. import { FlowRunsPage } from './FlowRunsPage'; -import { PublicFormsPage } from './PublicFormsPage'; /** A flow definition, as `meta.getItems('flow')` rows carry it: the item IS * the definition, flattened, with no `spec` member (objectui#12829). */ @@ -85,21 +86,6 @@ const FLOW = { variables: [{ name: 'recordId', type: 'text', isInput: true }], }; -/** A published public form, on the `ViewItem` shape `GET /meta/view` serves: - * the form under `config`, opened to anonymous intake by the server's rule - * (`sharing.enabled`, `allowAnonymous` and a `publicLink`; objectui#11545). */ -const FORM = { - name: 'showcase_task.public', - label: 'Log Time', - object: 'showcase_task', - viewKind: 'form', - config: { - type: 'simple', - sections: [{ label: 'Task', fields: ['title'] }], - sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/log-time' }, - }, -}; - beforeEach(() => { state.answer = []; }); @@ -143,30 +129,3 @@ describe('FlowRunsPage — meta.getItems envelope (objectui#6917)', () => { }); }); }); - -describe('PublicFormsPage — meta.getItems envelope (objectui#6917)', () => { - it("still reads the envelope's `items` member", async () => { - state.answer = { items: [FORM] }; - render(, { wrapper: MemoryRouter }); - await waitFor(() => { - expect(screen.getByText('Log Time')).toBeInTheDocument(); - }); - }); - - it('still reads a bare array', async () => { - state.answer = [FORM]; - render(, { wrapper: MemoryRouter }); - await waitFor(() => { - expect(screen.getByText('Log Time')).toBeInTheDocument(); - }); - }); - - it('does NOT read `value` — not a member of this envelope', async () => { - state.answer = { value: [FORM] }; - render(, { wrapper: MemoryRouter }); - await waitFor(() => { - expect(screen.getByText('No public forms yet')).toBeInTheDocument(); - }); - expect(screen.queryByText('Log Time')).not.toBeInTheDocument(); - }); -}); diff --git a/ui/apps/console/src/registerDeveloperComponents.tsx b/ui/apps/console/src/registerDeveloperComponents.tsx index 5d11bc4c630..06f00927fd4 100644 --- a/ui/apps/console/src/registerDeveloperComponents.tsx +++ b/ui/apps/console/src/registerDeveloperComponents.tsx @@ -5,7 +5,7 @@ * * Binds the `developer:*` registry keys to the lazy-loaded console pages * that already host these tools. The framework's Studio app names the first - * three from its Developer navigation group. + * two from its Developer navigation group. * * URL shape resolved by `ComponentNavView`: * developer:api-console → /apps//component/developer/api-console @@ -13,6 +13,13 @@ * developer:public-forms → /apps//component/developer/public-forms * developer:integrations → /apps//component/developer/integrations * + * `developer:public-forms` (objectstack#37087) is no page any more. The + * Public Forms page it opened is retired: a public form is a `form` item + * designed in Studio's form editor and switched on or off in Setup → Public + * forms (ADR-0159 D9). No navigation names the key; it stays registered + * so that a bookmark of its address lands on Studio's list of forms, as the + * standalone `developer/public-forms` route in `AppContent.tsx` does. + * * `developer:integrations` (objectui#10520): the Integrations & APIs page * was linked from exactly one place, a card on the console's Developer Hub * page, and that hub had no in-app link of its own once the System Hub card @@ -30,7 +37,8 @@ */ import { lazy, Suspense } from 'react'; -import { registerAppComponent } from '@object-ui/app-shell'; +import { Navigate } from 'react-router-dom'; +import { SETUP_PACKAGES_PATH, registerAppComponent, setupMetadataStudioPath } from '@object-ui/app-shell'; const ApiConsolePage = lazy(() => import('./pages/developer/ApiConsolePage').then((m) => ({ default: m.ApiConsolePage })), @@ -38,9 +46,6 @@ const ApiConsolePage = lazy(() => const FlowRunsPage = lazy(() => import('./pages/developer/FlowRunsPage').then((m) => ({ default: m.FlowRunsPage })), ); -const PublicFormsPage = lazy(() => - import('./pages/developer/PublicFormsPage').then((m) => ({ default: m.PublicFormsPage })), -); const IntegrationsPage = lazy(() => import('./pages/developer/IntegrationsPage').then((m) => ({ default: m.IntegrationsPage })), ); @@ -71,15 +76,15 @@ registerAppComponent({ ), }); +// objectstack#37087 — the retired Public Forms page. A bookmark of its address +// lands on Studio's list of forms across every package, where each row opens +// the form in its own package. The retired page read no query, so none is +// carried. The standalone route in `AppContent.tsx` lands on the same list. registerAppComponent({ ref: 'developer:public-forms', label: 'Public Forms', source: '@object-ui/console', - component: (props: any) => ( - }> - - - ), + component: () => , }); registerAppComponent({ diff --git a/ui/e2e/studio-left-menu-36899.spec.ts b/ui/e2e/studio-left-menu-36899.spec.ts index aabfa96b913..b8c872fb7d2 100644 --- a/ui/e2e/studio-left-menu-36899.spec.ts +++ b/ui/e2e/studio-left-menu-36899.spec.ts @@ -221,9 +221,12 @@ test.describe('Studio left menu (objectstack#36899)', () => { await fold.click(); await expect(fold).toHaveAttribute('aria-expanded', 'true'); - for (const g of ['automation', 'system', 'security']) { + for (const g of ['system', 'security']) { await expect(page.getByTestId(`studio-menu-advanced-group-${g}`)).toBeVisible(); } + // objectstack#38150 — the fold's Automation group held one row, the organization's own flows; + // it retired with the package-less scope, and a group is drawn only where it holds an entry. + await expect(page.getByTestId('studio-menu-advanced-group-automation')).toHaveCount(0); await expect(page.getByTestId('studio-menu-entry-diagnostics')).toBeVisible(); // Below the 常用 entries, inside the docked panel. const below = await page.getByTestId('studio-menu-entry-diagnostics').evaluate((el) => el.getBoundingClientRect().top); diff --git a/ui/packages/app-shell/README.md b/ui/packages/app-shell/README.md index 16ace9c028c..cdc4ecfb11c 100644 --- a/ui/packages/app-shell/README.md +++ b/ui/packages/app-shell/README.md @@ -793,26 +793,29 @@ On the declared page: rule already switched off has no served projection, so its clone continues in the pre-filled New form, which asks for the criteria. -### Package-less flows (`/studio/~org/metadata/flow`) - -A flow that belongs to no package — a clone of a packaged flow is one, by -ADR-0126 §7.1 — matches no package scope, so Studio gives it one scope of its -own, segment `STUDIO_ORG_SCOPE_SEGMENT` (`~org`): its own leg of the "All -metadata" area. The list is `/studio/~org/metadata/flow?source=runtime` and a -flow opens full-screen in the flow designer at -`/studio/~org/metadata/flow/?source=runtime` (`studioOrgScopePath()`, -`orgScopeFlowOf()`). It is the same `StudioDesignSurface` with no package under -it, reached from the Studio home and the left menu. The list holds every flow -whose served `_packageId` names no package and offers no create; each flow opens -editable and saves package-less drafts. An empty list says how a packaged flow -is changed instead (in its package, with New similar). Publish promotes the -scope's drafts one by one through the single-item publish door, because the -package batch publish cannot reach a draft bound to no package. `~` is outside -every package-id alphabet, so the segment can never name a package. A package's -address naming a package-less flow opens it in this scope; one naming a flow -nowhere held says so and opens no other flow. The retired -`/studio/~org/automations` addresses (with or without `?surface=flow:`) -redirect to the list or the flow (objectstack#36903). +### Items that belong to no package (the "Loose" list) + +A metadata item that belongs to no package — a clone of a packaged flow is one, +by ADR-0126 §7.1 — is in no package's list. A type's list on the "All metadata" +area's cross-package leg holds every package's items and those of none, and its +source filter's "Loose" value narrows it to the latter +(`/studio/~all/metadata/?source=loose`, `looseListPath()`). There a +person who may author metadata selects loose items and moves them into a +package (objectstack#38150). A loose row opens the item's page on the same leg +(`/studio/~all/metadata//`, `packageLessItemPath()`), where its +draft is published or discarded; Home's Publish all publishes it too. A +package's address naming a flow that belongs to no package opens that flow's +page there; one naming a flow nowhere held says so and opens no other flow. The +flow designer opens a package's flows only. + +Studio's package-less scope, which listed the flows among these items at +`/studio/~org/metadata/flow`, is retired. Every `/studio/~org/...` address — +the list, a flow, the old `/studio/~org/automations` deep links, and a +`?package=~org` link — lands on the Loose list of flows, +`/studio/~all/metadata/flow?source=loose`, keeping the address's search (`q`) +and sort (`sort`) (`retiredOrgScopeTarget()`, segment +`RETIRED_ORG_SCOPE_SEGMENT`). `~` is outside every package-id alphabet, so the +segment can never name a package. ### Access matrix (package-scoped) diff --git a/ui/packages/app-shell/src/__tests__/listKanbanEveryRecord-12619.test.tsx b/ui/packages/app-shell/src/__tests__/listKanbanEveryRecord-12619.test.tsx index 94d1c3806e6..cf36ab1af45 100644 --- a/ui/packages/app-shell/src/__tests__/listKanbanEveryRecord-12619.test.tsx +++ b/ui/packages/app-shell/src/__tests__/listKanbanEveryRecord-12619.test.tsx @@ -89,8 +89,8 @@ const ROWS: Row[] = STAGES.flatMap(([stage, , count]) => })), ); -function makeDataSource() { - const store = new ValueDataSource({ items: ROWS }); +function makeDataSource(rows: Row[] = ROWS) { + const store = new ValueDataSource({ items: rows }); return { find: vi.fn(async (object: string, params: any) => store.find(object, params)), findOne: vi.fn(), @@ -165,6 +165,37 @@ describe('a kanban under a list view draws every record of the view in its colum expect(within(card).queryByText('Probability')).not.toBeInTheDocument(); expect(within(card).queryByText('Close Date')).not.toBeInTheDocument(); }); + + /** + * objectstack#38120 — a board laned by the options of a select field draws + * its "Uncategorized" lane with its count when every record with no stage, or + * a stage no option names, sits past the list's first page: that lane is a + * query of its own on this board, as each option's lane is. + */ + it('records with no stage or an unknown one, all past the first page, draw "Uncategorized" with their 10 cards and count', async () => { + const strays: Row[] = Array.from({ length: 10 }, (_, i) => ({ + id: `stray-${i}`, + name: `stray deal ${i}`, + account: `Account stray ${i}`, + stage: i < 6 ? null : 'archived', + amount: 1, + probability: 40, + close_date: '2026-11-01', + })); + const ds = makeDataSource([...ROWS, ...strays]); + mountBoard(ds); + + await waitFor(() => expect(cards()).toHaveLength(55)); + expect(within(lane('Uncategorized')).getAllByRole('listitem')).toHaveLength(10); + expect((within(lane('Uncategorized')).getByRole('heading').parentElement!.querySelector('span')!.textContent ?? '').trim()).toBe('10'); + // RIG SELF-CHECK: the list's own window, its first 25 rows, holds none of them. + const at = ds.find.mock.calls.findIndex((call: any[]) => call[1]?.$top === 25); + expect(at).toBeGreaterThanOrEqual(0); + const answer = (await ds.find.mock.results[at].value) as any; + const page: Row[] = Array.isArray(answer) ? answer : answer.data ?? answer.records ?? []; + expect(page).toHaveLength(25); + expect(page.some((row) => String(row.id).startsWith('stray'))).toBe(false); + }); }); /** @@ -413,6 +444,9 @@ describe('a lookup-laned board under a list view counts and totals each whole la account: i >= 60 ? 'acc-c' : i % 2 === 0 ? 'acc-a' : 'acc-b', // The same split on a text field, for a board laned by a field that is no reference. tier: i >= 60 ? 'bronze' : i % 2 === 0 ? 'gold' : 'silver', + // And on a number field, for a board laned by a field whose aggregate key + // need not be spelled as a `find` row spells the value. + rank: i >= 60 ? 3 : i % 2 === 0 ? 1 : 2, amount: i, })); const ACCOUNTS: Row[] = [ @@ -428,6 +462,7 @@ describe('a lookup-laned board under a list view counts and totals each whole la name: { type: 'text', label: 'Deal Name' }, account: { type: 'lookup', label: 'Account', reference: ACCOUNT }, tier: { type: 'text', label: 'Tier' }, + rank: { type: 'number', label: 'Rank' }, amount: { type: 'number', label: 'Amount' }, }, }, @@ -847,24 +882,127 @@ describe('a lookup-laned board under a list view counts and totals each whole la expect(laneReads(ds)).toHaveLength(0); }); - it('CONTROL: a board laned by a text field offers no "Load more"', async () => { - mountBoard(dealSource(), { ...BOARD_VIEW, kanban: { ...BOARD_VIEW.kanban, groupByField: 'tier' } }); - + /** + * objectstack#38120 — a board laned by a text field draws its "Uncategorized" + * lane from the lane read's count, and offers "Load more" on a lane that + * draws fewer cards than it counts, as a lookup-laned board does. Deals + * 60–64 have no tier and 65–69 an empty one, all past the first page. + */ + const TIER_VIEW = { ...BOARD_VIEW, kanban: { ...BOARD_VIEW.kanban, groupByField: 'tier' } }; + const NO_TIER_PAST_PAGE: Row[] = DEALS.map((d, i) => (i >= 65 ? { ...d, tier: '' } : i >= 60 ? { ...d, tier: null } : d)); + async function tierPageDrawn() { await waitFor(() => expect(cards()).toHaveLength(25)); - await waitFor(() => expect(laneBadge('gold')).toBe('30')); + expect(within(lane('gold')).getAllByRole('listitem')).toHaveLength(13); + expect(within(lane('silver')).getAllByRole('listitem')).toHaveLength(12); + } + + it('a text-laned board draws "Uncategorized" last, counting its 10 records with no tier, all past the page', async () => { + mountBoard(dealSource(true, NO_TIER_PAST_PAGE), TIER_VIEW); + + await tierPageDrawn(); + await waitFor(() => expect(screen.getByRole('group', { name: 'Uncategorized' })).toBeInTheDocument()); + expect(laneBadge('Uncategorized')).toBe('10'); + expect(within(lane('Uncategorized')).queryAllByRole('listitem')).toHaveLength(0); + expect(within(lane('Uncategorized')).getByText('Cards not loaded: 10')).toBeInTheDocument(); + expect(laneNames().slice(-3)).toEqual(['gold', 'silver', 'Uncategorized']); + }); + + it('the text-laned "Uncategorized" lane loads its 10 records, those with no tier and those with an empty one', async () => { + const ds = dealSource(true, NO_TIER_PAST_PAGE); + mountBoard(ds, TIER_VIEW); + + await tierPageDrawn(); + await waitFor(() => expect(loadMore('Uncategorized')).not.toBeNull()); + fireEvent.click(loadMore('Uncategorized')!); + + await waitFor(() => expect(within(lane('Uncategorized')).getAllByRole('listitem')).toHaveLength(10)); + expect(loadMore('Uncategorized')).toBeNull(); + expect(laneBadge('Uncategorized')).toBe('10'); + const read = laneReads(ds)[0]; + expect(read).toMatchObject({ $skip: 0, $top: 50, $count: true }); + expect(JSON.stringify(read.$filter)).toContain('["or",["tier","is_null"],["tier","=",""]]'); + }); + + it('a text lane on the page with 13 of its 30 cards loads the other 17 from its 14th record', async () => { + const ds = dealSource(); + mountBoard(ds, TIER_VIEW); + + await tierPageDrawn(); + await waitFor(() => expect(loadMore('gold')).not.toBeNull()); + expect(loadMore('silver')).not.toBeNull(); + fireEvent.click(loadMore('gold')!); + + await waitFor(() => expect(within(lane('gold')).getAllByRole('listitem')).toHaveLength(30)); + expect(new Set(cardNames('gold')).size).toBe(30); + expect(loadMore('gold')).toBeNull(); + expect(laneBadge('gold')).toBe('30'); + const reads = laneReads(ds); + expect(reads).toHaveLength(1); + expect(reads[0]).toMatchObject({ $skip: 13, $top: 50 }); + expect(JSON.stringify(reads[0].$filter)).toContain('"tier","=","gold"'); + }); + + it.each([ + ['has no grouped door', false], + ['refuses the read', 'refuse'], + ['cuts the read (hasMore)', 'cut'], + ] as const)('CONTROL: when the source %s, a text-laned board draws no "Uncategorized" lane and offers no "Load more"', async (_, door) => { + const ds = dealSource(door, NO_TIER_PAST_PAGE); + mountBoard(ds, TIER_VIEW); + + await tierPageDrawn(); + if (door !== false) await waitFor(() => expect(ds.queryGroupHeaders).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(laneBadge('gold')).toBe('13+')); + expect(screen.queryByRole('group', { name: 'Uncategorized' })).toBeNull(); expect(screen.queryAllByRole('button', { name: 'Load more' })).toHaveLength(0); + expect(laneReads(ds)).toHaveLength(0); + }); + + /** + * objectstack#38506 — a text value whose records all sit past the page gets + * its lane, as a lookup value does: deals 60–69 are `bronze`, none of them on + * the first page. The lane is titled by the value itself, drawn after the + * page's lanes, and offers its records with "Load more". + */ + it('a text value whose records all sit past the page gets its lane: count, "Cards not loaded" and "Load more"', async () => { + const ds = dealSource(); + mountBoard(ds, TIER_VIEW); + + await tierPageDrawn(); + await waitFor(() => expect(screen.getByRole('group', { name: 'bronze' })).toBeInTheDocument()); + expect(laneNames().slice(-3)).toEqual(['gold', 'silver', 'bronze']); + expect(within(lane('bronze')).queryAllByRole('listitem')).toHaveLength(0); + await waitFor(() => expect(laneBadge('bronze')).toBe('10')); + expect(within(lane('bronze')).getByText('Cards not loaded: 10')).toBeInTheDocument(); + // The lane counts add up to every record of the view: 30 + 30 + 10 = 70. + expect(Number(laneBadge('gold')) + Number(laneBadge('silver')) + Number(laneBadge('bronze'))).toBe(DEALS.length); + // Titled by the stored value: no title read on any other object. + expect(ds.find.mock.calls.filter((call: any[]) => call[0] !== DEAL)).toHaveLength(0); + + await waitFor(() => expect(loadMore('bronze')).not.toBeNull()); + fireEvent.click(loadMore('bronze')!); + + await waitFor(() => expect(within(lane('bronze')).getAllByRole('listitem')).toHaveLength(10)); + expect(laneNames().slice(-3)).toEqual(['gold', 'silver', 'bronze']); + expect(loadMore('bronze')).toBeNull(); + expect(laneBadge('bronze')).toBe('10'); + const reads = laneReads(ds); + expect(reads).toHaveLength(1); + expect(reads[0]).toMatchObject({ $skip: 0, $top: 50, $count: true }); + expect(JSON.stringify(reads[0].$filter)).toContain('"tier","=","bronze"'); }); - it('a board laned by a text field counts each whole lane but draws no lane past the page', async () => { + it('CONTROL: a board laned by a number field counts each whole lane but draws no lane past the page', async () => { const ds = dealSource(); - mountBoard(ds, { ...BOARD_VIEW, kanban: { ...BOARD_VIEW.kanban, groupByField: 'tier' } }); + mountBoard(ds, { ...BOARD_VIEW, kanban: { ...BOARD_VIEW.kanban, groupByField: 'rank' } }); await waitFor(() => expect(cards()).toHaveLength(25)); - await waitFor(() => expect(laneBadge('gold')).toBe('30')); - expect(laneBadge('silver')).toBe('30'); - // The read names `bronze`, which sits past the page: a key the aggregate - // spells for a field that is no reference draws no lane. - expect(screen.queryByRole('group', { name: 'bronze' })).toBeNull(); + await waitFor(() => expect(laneBadge('1')).toBe('30')); + expect(laneBadge('2')).toBe('30'); + // The read names 3, which sits past the page: a number's aggregate key + // need not be spelled as a `find` row spells it, so it draws no lane. + expect(ds.queryGroupHeaders).toHaveBeenCalledTimes(1); + expect(screen.queryByRole('group', { name: '3' })).toBeNull(); }); it('a float total reads as the page path prints it, without binary residue', async () => { @@ -884,3 +1022,123 @@ describe('a lookup-laned board under a list view counts and totals each whole la expect(headerTotal('acc-b')).toBe('0.7'); }); }); + +/** + * objectstack#38558 — the footer of a board handed the list's window counts + * what its lanes count: the whole query. Each lane badge of a data-laned + * board counts its whole lane (objectstack#37327), so a footer that counted + * the window ("25 records" plus "Showing first 25 records") read against + * lanes adding up to 70. The footer now states the query's total; the + * "Showing first N" line goes only where the board reaches every record + * itself (a lookup or text lane field, flat lanes, the grouped door), and + * stays where it draws the page's lanes only. + */ +describe('a data-laned board under a list view: the footer counts the whole query, as the lanes do (objectstack#38558)', () => { + const DEAL = 'crm_deal'; + const ACCOUNT = 'crm_account'; + /** 70 deals: 30 + 30 on the first pages, the last 10 in a third lane past page one. */ + const DEALS: Row[] = Array.from({ length: 70 }, (_, i) => ({ + id: `deal-${String(i).padStart(2, '0')}`, + name: `Deal ${String(i).padStart(2, '0')}`, + account: i >= 60 ? 'acc-c' : i % 2 === 0 ? 'acc-a' : 'acc-b', + tier: i >= 60 ? 'bronze' : i % 2 === 0 ? 'gold' : 'silver', + rank: i >= 60 ? 3 : i % 2 === 0 ? 1 : 2, + })); + const DEFS: Record = { + [DEAL]: { + name: DEAL, + label: 'Deal', + fields: { + name: { type: 'text', label: 'Deal Name' }, + account: { type: 'lookup', label: 'Account', reference: ACCOUNT }, + tier: { type: 'text', label: 'Tier' }, + rank: { type: 'number', label: 'Rank' }, + }, + }, + [ACCOUNT]: { name: ACCOUNT, label: 'Account', nameField: 'name', fields: { name: { type: 'text', label: 'Name' } } }, + }; + const ACCOUNTS: Row[] = [ + { id: 'acc-a', name: 'Amber Ltd' }, + { id: 'acc-b', name: 'Birch Inc' }, + { id: 'acc-c', name: 'Cyan Corp' }, + ]; + const boardView = (groupByField: string) => ({ + type: 'list-view', + objectName: DEAL, + viewType: 'kanban', + columns: [{ field: 'name' }, { field: groupByField }], + pagination: { pageSize: 25 }, + kanban: { groupByField, titleField: 'name' }, + }); + + /** A source answering `total`, with (or without) the grouped door counting each group. */ + function countSource(door = true) { + const stores: Record> = { + [DEAL]: new ValueDataSource({ items: DEALS }), + [ACCOUNT]: new ValueDataSource({ items: ACCOUNTS }), + }; + const queryGroupHeaders = vi.fn(async (object: string, query: any) => { + const kept = (await stores[object].find(object, { ...(query.where ? { $filter: query.where } : {}), $top: 100000 } as any)) as any; + const rows: Row[] = Array.isArray(kept) ? kept : kept.data ?? kept.records ?? []; + const key = query.groupBy[0]; + const groups = new Map(); + for (const row of rows) groups.set(row[key] ?? null, (groups.get(row[key] ?? null) ?? 0) + 1); + return [...groups].map(([k, n]) => { + const out: Row = { [key]: k }; + for (const agg of query.aggregations) out[agg.alias] = agg.function === 'count' ? n : null; + return out; + }); + }); + return { + find: vi.fn(async (object: string, params: any) => stores[object].find(object, params)), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn(async (object: string) => DEFS[object]), + ...(door ? { queryGroupHeaders } : {}), + } as any; + } + + const laneBadge = (title: string) => + (within(lane(title)).getByRole('heading').parentElement!.querySelector('span')!.textContent ?? '').trim(); + const footer = () => screen.getByTestId('record-count-bar'); + + it('a text-laned board: the footer reads 70 records, the sum of its lanes 30 + 30 + 10, and no "Showing first 25"', async () => { + mountBoard(countSource(), boardView('tier')); + + await waitFor(() => expect(cards()).toHaveLength(25)); + await waitFor(() => expect(laneBadge('bronze')).toBe('10')); + const laneSum = Number(laneBadge('gold')) + Number(laneBadge('silver')) + Number(laneBadge('bronze')); + expect(laneSum).toBe(DEALS.length); + await waitFor(() => expect(footer()).toHaveTextContent(`${laneSum} records`)); + expect(screen.queryByTestId('data-limit-warning')).not.toBeInTheDocument(); + }); + + it('a lookup-laned board: the footer reads 70 records and no "Showing first 25"', async () => { + mountBoard(countSource(), boardView('account')); + + await waitFor(() => expect(cards()).toHaveLength(25)); + await waitFor(() => expect(screen.getByRole('group', { name: 'Cyan Corp' })).toBeInTheDocument()); + await waitFor(() => expect(footer()).toHaveTextContent('70 records')); + expect(screen.queryByTestId('data-limit-warning')).not.toBeInTheDocument(); + }); + + it('CONTROL: a number-laned board draws the page\'s lanes only, so the footer reads 70 records and keeps "Showing first 25"', async () => { + mountBoard(countSource(), boardView('rank')); + + await waitFor(() => expect(cards()).toHaveLength(25)); + await waitFor(() => expect(laneBadge('1')).toBe('30')); + expect(screen.queryByRole('group', { name: '3' })).toBeNull(); + await waitFor(() => expect(footer()).toHaveTextContent('70 records')); + expect(screen.getByTestId('data-limit-warning')).toHaveTextContent('Showing first 25 records'); + }); + + it('CONTROL: over a source with no grouped door the board reaches no lane past the page, so "Showing first 25" stays', async () => { + mountBoard(countSource(false), boardView('tier')); + + await waitFor(() => expect(cards()).toHaveLength(25)); + await waitFor(() => expect(footer()).toHaveTextContent('70 records')); + expect(screen.getByTestId('data-limit-warning')).toHaveTextContent('Showing first 25 records'); + }); +}); diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.studioScope-11863.test.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.studioScope-11863.test.tsx index 9282aa0b4cf..c56998cacc2 100644 --- a/ui/packages/app-shell/src/chrome/CommandPalette.studioScope-11863.test.tsx +++ b/ui/packages/app-shell/src/chrome/CommandPalette.studioScope-11863.test.tsx @@ -195,11 +195,11 @@ describe('the palette in the `studio` scope lists the Studio, not an app (object expect(shown('studio-flow')).toEqual(['Onboard AccountAcme CRM', 'Nightly Cleanup']); }); - it('opens a package on its Data pillar', async () => { + it('opens a package on its 概览 Overview (objectstack#38392)', async () => { mountStudio(); await studioListed(); pick('studio-package People '); - await waitFor(() => expect(locationNow()).toBe('/studio/com.acme.hr/data')); + await waitFor(() => expect(locationNow()).toBe('/studio/com.acme.hr/overview')); }); it("opens an object in its package's Data pillar, on that object", async () => { @@ -218,11 +218,14 @@ describe('the palette in the `studio` scope lists the Studio, not an app (object ); }); - it('opens a package-less flow in the package-less scope (objectui#11553)', async () => { + // objectstack#38150 — rewritten on purpose: the package-less scope is retired, so the flow opens + // on its item page on the cross-package leg, the page its row of the Loose list opens. It opened + // `/studio/~org/metadata/flow/org_cleanup?source=runtime`. + it('opens a package-less flow on its item page on the cross-package leg (objectui#11553)', async () => { mountStudio(); await studioListed(); pick('studio-flow Nightly Cleanup '); - await waitFor(() => expect(locationNow()).toBe('/studio/~org/metadata/flow/org_cleanup?source=runtime')); + await waitFor(() => expect(locationNow()).toBe('/studio/~all/metadata/flow/org_cleanup')); }); it('matches an entry by its label or its machine name', async () => { diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.tsx index f6ac95f3f48..503cd7b0e53 100644 --- a/ui/packages/app-shell/src/chrome/CommandPalette.tsx +++ b/ui/packages/app-shell/src/chrome/CommandPalette.tsx @@ -83,8 +83,9 @@ import { useNavTargetColor } from '../hooks/useNavTargetIcon.js'; import { useAuth } from '@object-ui/auth'; import { matchesPaletteQuery } from './paletteMatch.js'; import { fetchPackages, type PkgEntry } from '../views/studio-design/packages-io.js'; -import { isPackageLessItem, studioOrgScopePath } from '../views/studio-design/studioScope.js'; -import { studioHomePath, studioItemPath } from '../views/studio-design/studioAddress.js'; +import { isPackageLessItem, packageLessItemPath } from '../views/studio-design/studioScope.js'; +import { studioItemPath } from '../views/studio-design/studioAddress.js'; +import { studioPackageOverviewPath } from '../views/studio-design/studioOverviewAddress.js'; import { flattenNavigation, useAppReportEntries } from '../views/appReportIndex.js'; import { useServedApps } from '../hooks/useLauncherApps.js'; import { servedObjectLabel } from '../hooks/servedObjectLabel.js'; @@ -153,7 +154,7 @@ export interface StudioPaletteSurface { /** * Whether the page is one package's. Its groups then list that package's * items, so the palette does not also list every package's objects and - * flows; the package-less scope and the cross-package leg keep them. + * flows; the cross-package leg keeps them. */ packageScope: boolean; /** The page's groups for the query, drawn above the packages; mounted only while the palette is open. */ @@ -1093,16 +1094,17 @@ const NO_STUDIO_ENTRIES: StudioPaletteEntries = { packages: [], objects: [], flo * * - **Packages** come from `fetchPackages`, the list the Studio landing and its * package switcher read; kernel packages are already left out there. Each - * opens its Data pillar, as a landing card does. + * opens its 概览 Overview, where every door into a package lands + * (objectstack#38392). * - **Objects** come from the metadata cache (`useMetadata().objects`), each * listed under the package it declares (`_packageId`) and opened in that * package's Data pillar. One whose package is not in the list has no Studio * page to open, and is left out. * - **Flows** come from the same cache's `flow` list, the unscoped read that - * carries every package's flows (the read the package-less scope narrows, - * see `loadPackageLessSurfaces`). A packaged flow opens in its package's - * Automations pillar; a flow that belongs to no package opens in the - * package-less scope (objectui#11553). + * carries every package's flows and the flows of none. A packaged flow + * opens in its package's flow designer; a flow that belongs to no package + * opens its item page on the cross-package leg (`packageLessItemPath`, + * objectui#11553, objectstack#38150). * * The published items only: an item that is still a draft is not in either * cache list. Until the package list answers nothing is listed, so no entry @@ -1173,10 +1175,11 @@ function useStudioPaletteEntries(enabled: boolean, crossPackageItems = true): St const label = resolveKeyedI18nLabel(item.label, t) || item.name; if (isPackageLessItem(item)) { flows.push({ - key: `~org:${item.name}`, + // `~` is outside every package-id alphabet, so the key meets no packaged entry's. + key: `~loose:${item.name}`, label, name: item.name, - href: studioOrgScopePath({ type: 'flow', name: item.name }), + href: packageLessItemPath({ type: 'flow', name: item.name }), }); continue; } @@ -1196,7 +1199,7 @@ function useStudioPaletteEntries(enabled: boolean, crossPackageItems = true): St key: pkg.id, label: pkg.name, name: pkg.id, - href: studioHomePath(pkg.id), + href: studioPackageOverviewPath(pkg.id), })), objects, flows, diff --git a/ui/packages/app-shell/src/console/AppContent.tsx b/ui/packages/app-shell/src/console/AppContent.tsx index 804b2bbf59d..f31819acb4b 100644 --- a/ui/packages/app-shell/src/console/AppContent.tsx +++ b/ui/packages/app-shell/src/console/AppContent.tsx @@ -32,6 +32,7 @@ import { useTrackRouteAsRecent } from '../hooks/useTrackRouteAsRecent.js'; import { useHomePath } from '../hooks/useHomePath.js'; import { readItemPreferLocal, useReadItemsByName } from '../hooks/useObjectPresence.js'; import { useLauncherApps } from '../hooks/useLauncherApps.js'; +import { useOpenedOnce } from '../hooks/useOpenedOnce.js'; import { recordFormFieldNames } from '../utils/recordFormFields.js'; import { resolveRecordFormTarget, resolveRecordFormModalLayout, resolveRecordFormChrome, resolveNavigateCreateUrl, resolveNavigateEditUrl, resolvePostCreateTarget, recordFormCreateValues, readRecordFormCreateValues, RECORD_FORM_CREATE_VALUES_STATE } from '../utils/recordFormNavigation.js'; import { deriveRecordSurface, deriveRecordFlowSurface } from '@object-ui/plugin-view/core'; @@ -1056,6 +1057,10 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = isDialogOpen && !!formObjectDef && routeReadsSettled && routeSlotShown, recordDrawersOpening, ); + // objectstack#37444: the record form mounts the first time it opens, not with + // every object page. Closed, it drew nothing, yet its lazy chunk (the whole of + // `@object-ui/plugin-form`) was fetched before a list's first screen. + const recordFormMounted = useOpenedOnce(recordFormShown); // objectstack#27138 — the record the overlay edits may be held by a pending // approval that locks it. The record's field projection leaves that lock out @@ -1763,7 +1768,7 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = - {formObjectDef && ( + {formObjectDef && recordFormMounted && ( // objectstack#35403 — an edit draws the record's owner read-only, // with Change Owner beside it where the caller may transfer it. diff --git a/ui/packages/app-shell/src/console/AppNoAccessEmptyState.tsx b/ui/packages/app-shell/src/console/AppNoAccessEmptyState.tsx index 8d7ac8ca7a6..44896354599 100644 --- a/ui/packages/app-shell/src/console/AppNoAccessEmptyState.tsx +++ b/ui/packages/app-shell/src/console/AppNoAccessEmptyState.tsx @@ -38,7 +38,8 @@ * (the only one who can also fill the menu), the no-navigation answer first * reads the app's stored menu (`/layers`, the read the design mode's menu * editor makes); when it is empty too, the screen says the menu is empty and - * opens the app's package in Studio. Everyone else, and a stored menu that + * opens the app's package in Studio, on its 概览 Overview, where every door + * into a package lands (objectstack#38392). Everyone else, and a stored menu that * holds entries this caller is not shown, keep the access answer. */ @@ -54,7 +55,7 @@ import { Button, DataEmptyState } from '@object-ui/components'; import { useObjectTranslation } from '@object-ui/i18n'; import { useServedAppLabel } from '../hooks/useServedAppLabel.js'; import { useCanAuthorMetadata } from '../hooks/useCanAuthorMetadata.js'; -import { studioHomePath } from '../views/studio-design/studioAddress.js'; +import { studioPackageOverviewPath } from '../views/studio-design/studioOverviewAddress.js'; import { createAuthenticatedFetch } from '@object-ui/auth'; /** The console's authenticated fetch: the stored bearer token beside the session cookie. */ @@ -154,7 +155,7 @@ export function AppNoAccessEmptyState({ app, setupPath, reason = 'no-navigation' })} action={ diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.recordFormMountsOnOpen-37444.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.recordFormMountsOnOpen-37444.test.tsx new file mode 100644 index 00000000000..d936414365f --- /dev/null +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.recordFormMountsOnOpen-37444.test.tsx @@ -0,0 +1,146 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37444 — an object page mounts the record-form modal the first + * time it opens, so a list's first screen loads no form code. + * + * `AppContent` drew a closed `LazyModalForm` on every object page (the route's + * object is always the form's default object), and a lazy component that is + * drawn loads its chunk even closed: the whole of `@object-ui/plugin-form` was + * fetched before every list's first screen. The bundle half is measured on the + * built console and recorded on the PR; this file pins that the form module is + * not evaluated until the form opens, and that it opens as before. + * + * The instrument: a counted `vi.mock` factory, which runs the first time the + * module is imported. The module registry is per FILE, so the case that needs + * it unloaded runs first, and the later case asserts the count it starts from. + */ + +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, afterEach, afterAll } from 'vitest'; +import React from 'react'; +import { render, cleanup, waitFor, screen } from '@testing-library/react'; +import { MemoryRouter, Routes, Route } from 'react-router-dom'; +import { createI18n, I18nProvider } from '@object-ui/i18n'; +// The console layout's draft bar reaches a dynamic `@objectstack/lint` import; +// its first load is paid here, during collection, not inside a case's clock. +import '@objectstack/lint'; + +const { loads, modalOpen } = vi.hoisted(() => ({ loads: { form: 0 }, modalOpen: [] as boolean[] })); + +vi.mock('@object-ui/plugin-form', async (importOriginal) => { + loads.form += 1; + return { + ...(await importOriginal>()), + ModalForm: ({ schema }: { schema: { open?: boolean; objectName?: string } }) => { + modalOpen.push(!!schema.open); + return
; + }, + ObjectForm: () => null, + }; +}); + +vi.mock('@object-ui/plugin-designer', async (importOriginal) => ({ + ...(await importOriginal()), + CreateAppPage: () =>
, + EditAppPage: () =>
, + DashboardDesignPage: () =>
, +})); + +vi.mock('../../layout/ConsoleLayout', () => ({ + ConsoleLayout: ({ children }: { children?: React.ReactNode }) => ( +
{children}
+ ), +})); +vi.mock('../../chrome/CommandPalette', () => ({ CommandPalette: () => null })); +vi.mock('../../chrome/KeyboardShortcutsDialog', () => ({ KeyboardShortcutsDialog: () => null })); +vi.mock('../../chrome/OnboardingWalkthrough', () => ({ OnboardingWalkthrough: () => null })); +vi.mock('../../views/ObjectView', () => ({ ObjectView: () =>
})); +vi.mock('../../views/RecordDetailView', () => ({ RecordDetailView: () =>
})); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ + user: { id: 'u1', name: 'Ada', email: 'ada@example.com', role: 'user' }, + getAuthConfig: async () => ({ features: {} }), + activeOrganization: null, + }), + useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), +})); + +const dataSourceStub = { + onConnectionStateChange: () => () => {}, + getConnectionState: () => 'connected', +}; +vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useAdapter: () => dataSourceStub, +})); + +const METADATA = { + apps: [{ name: 'crm', label: 'CRM', isDefault: true, navigation: [] }], + objects: [{ name: 'showcase_task', label: 'Task', fields: { subject: { type: 'text', label: 'Subject' } } }], + loading: false, + ensureType: undefined, + error: null, + refresh: async () => {}, +}; +vi.mock('../../providers/MetadataProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadata: () => METADATA, +})); + +const ACTION_RUNNER = { execute: vi.fn(), runner: { registerHandler: () => {}, getContext: () => ({}) } }; +vi.mock('@object-ui/react', async (importOriginal) => ({ + ...(await importOriginal>()), + useActionRunner: () => ACTION_RUNNER, + useGlobalUndo: () => {}, + useMutationInvalidationBridge: () => {}, +})); + +// An edit dialog reads the approvals of the record it edits; none runs here. +vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [] }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, +}))); +afterAll(() => vi.unstubAllGlobals()); + +import { AppContent } from '../AppContent'; + +function mountAt(url: string) { + const i18n = createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false }); + render( + + + + } /> + + + , + ); +} + +afterEach(() => cleanup()); + +describe('objectstack#37444 — an object page mounts the record form when it opens', () => { + it('a list with no form open loads no form module and draws no modal', async () => { + expect(loads.form).toBe(0); + mountAt('/apps/crm/showcase_task'); + await screen.findByTestId('console-layout'); + // Long enough for a drawn lazy modal to have asked for its chunk and drawn. + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(screen.queryByTestId('modal-form')).toBeNull(); + expect(loads.form).toBe(0); + }); + + it('opening the create form loads it and draws it open', async () => { + expect(loads.form).toBe(0); + mountAt('/apps/crm/showcase_task?form=new'); + const modal = await screen.findByTestId('modal-form'); + expect(modal).toHaveAttribute('data-object', 'showcase_task'); + await waitFor(() => expect(modal).toHaveAttribute('data-open', 'true')); + expect(loads.form).toBe(1); + // It is never drawn closed first: the opening render is the first one. + expect(modalOpen[0]).toBe(true); + }); +}); diff --git a/ui/packages/app-shell/src/console/__tests__/AppNoAccessEmptyState.emptyMenu-36748.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppNoAccessEmptyState.emptyMenu-36748.test.tsx index 98ce4cc308b..3d2168eddae 100644 --- a/ui/packages/app-shell/src/console/__tests__/AppNoAccessEmptyState.emptyMenu-36748.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/AppNoAccessEmptyState.emptyMenu-36748.test.tsx @@ -66,7 +66,7 @@ describe('an empty stored menu is said as such, not as missing access (objectsta expect(status).toHaveAttribute('data-reason', 'empty-menu'); expect(status).toHaveTextContent('has nothing in its menu yet'); expect(status).not.toHaveTextContent(/grant access/i); - expect(screen.getByTestId('app-empty-menu-open-studio')).toHaveAttribute('href', `/studio/${PKG}/data`); + expect(screen.getByTestId('app-empty-menu-open-studio')).toHaveAttribute('href', `/studio/${PKG}/overview`); expect(screen.queryByTestId('app-no-access-open-setup')).toBeNull(); expect(String(fetchMock.mock.calls[0]?.[0])).toBe(`/api/v1/meta/app/visits/layers?package=${encodeURIComponent(PKG)}`); }); diff --git a/ui/packages/app-shell/src/console/ai/ChatPane.tsx b/ui/packages/app-shell/src/console/ai/ChatPane.tsx index 48e14be9558..1f842bbaaf6 100644 --- a/ui/packages/app-shell/src/console/ai/ChatPane.tsx +++ b/ui/packages/app-shell/src/console/ai/ChatPane.tsx @@ -352,6 +352,7 @@ export function ChatPane({ sendMessage, stop, reload, + resumeTurn, clear, setMessages, } = useObjectChat({ @@ -856,6 +857,14 @@ export function ChatPane({ messages={shownMessages} // Keys the question card's skip marks to this conversation. conversationId={conversationId} + // objectstack#31865 — the member rates each answer of their own + // conversation, on the same AI service the conversation is read from. + rateAnswers + answerFeedbackApiBase={apiBase} + // objectstack#31889 — save an answer as a question, the member's view, + // or a report / dashboard widget draft; the Saved questions panel. + saveAnswers + answerSaveApiBase={apiBase} placeholder={ activeAgent ? agentRouteName(activeAgent) === 'ask' @@ -918,6 +927,8 @@ export function ChatPane({ hideClearBar onStop={isLoading ? stop : undefined} onReload={reload} + // The Continue control under an answer the server says may be carried on. + onResumeTurn={resumeTurn} // objectstack#34462 — busy while a turn's attachments are still being // read, too: a message typed then queues behind that turn. isLoading={isLoading || preparingTurn} diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.hydration.test.ts b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.hydration.test.ts index 3db432b2a67..35ff65b74fc 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.hydration.test.ts +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.hydration.test.ts @@ -322,3 +322,16 @@ describe('AiChatPage hydration — the data tools\' source block (objectstack#31 expect(msg.toolInvocations?.[0].answerSource).toEqual(source); }); }); + +describe('AiChatPage hydration — the turn a reloaded message was stored under (objectstack#31865)', () => { + it('hands the chat each message\'s turnId, which the answer\'s rating addresses', () => { + const chat = hydratedMessagesToChatMessages([ + { id: 'row-1', role: 'user', parts: [{ type: 'text', text: 'How many open deals?' }], turnId: 'turn-9' }, + { id: 'row-2', role: 'assistant', parts: [{ type: 'text', text: 'There are 12 open deals.' }], turnId: 'turn-9' }, + { id: 'row-3', role: 'assistant', parts: [{ type: 'text', text: 'Stored with no turn.' }], turnId: null }, + { id: 'row-4', role: 'assistant', parts: [{ type: 'text', text: 'From the cache.' }] }, + ]); + expect(chat.map((m) => m.turnId)).toEqual(['turn-9', 'turn-9', null, undefined]); + expect('turnId' in chat[3]).toBe(false); + }); +}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.turnEndReload-38609.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.turnEndReload-38609.test.tsx new file mode 100644 index 00000000000..fa6fb254bbb --- /dev/null +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.turnEndReload-38609.test.tsx @@ -0,0 +1,77 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38609 — the Continue control under an answer whose turn may be + * resumed survives a reload, from either place a reload restores from: + * + * - Server history: the conversation routes return the turn end as the last + * message's `turnEnd` field (`AiConversationMessageSchema.turnEnd`); + * `toUIMessages` writes it back as the `data-turn-end` part, and + * `hydratedMessagesToChatMessages` reads it through the contract. + * - Cache fallback: the live map → `sanitizeChatMessagesForCache` → JSON → + * `hydratedMessagesToChatMessages`. + * + * CONTROL: a stored turn end the contract refuses offers no Continue. The + * API-mode store rebuild and the resume itself are pinned in plugin-chatbot's + * `continueTurn-38609.test.tsx`. + */ +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, screen } from '@testing-library/react'; +import { TURN_END_PART_TYPE } from '@objectstack/spec/ai'; +import { ChatbotEnhanced, uiMessageToChatMessage } from '@object-ui/plugin-chatbot'; +import { hydratedMessagesToChatMessages } from '../aiChatHydration'; +import { sanitizeChatMessagesForCache, toUIMessages } from '../../../hooks/useChatConversation'; + +afterEach(cleanup); + +const QUESTION = 'What do the policies say about contractors?'; +const TEXT = 'Partial answer: three of the five policies are read so far.'; +const END = { reason: 'token_budget', wrapUp: true, resumable: true, resumesLeft: 1, turnId: 'turn_1' }; + +/** The stored turn as the conversation routes return it: the turn end on the turn's last row. */ +const serverHistory = (turnEnd: unknown) => + toUIMessages([ + { id: 'u1', role: 'user', content: QUESTION, turnId: 'turn_1' }, + { id: 'a1', role: 'assistant', content: TEXT, turnId: 'turn_1', turnEnd }, + ] as never); + +function drawsContinue(messages: unknown[]): boolean { + render(); + const drawn = screen.queryByTestId('continue-turn-button') !== null; + cleanup(); + return drawn; +} + +describe('a reloaded answer offers Continue again (objectstack#38609)', () => { + it('server history: the stored turn end comes back on the answer and draws Continue', () => { + const messages = hydratedMessagesToChatMessages(serverHistory(END)); + expect(messages[1].content).toBe(TEXT); + expect(messages[1].turnEnd).toEqual(END); + expect(messages[0].turnEnd).toBeUndefined(); + expect(drawsContinue(messages)).toBe(true); + }); + + it('server history CONTROL: a refused or absent turn end offers nothing', () => { + for (const turnEnd of [{ ...END, extra: true }, null, undefined]) { + const messages = hydratedMessagesToChatMessages(serverHistory(turnEnd)); + expect(messages[1].content).toBe(TEXT); + expect(messages[1].turnEnd).toBeUndefined(); + expect(drawsContinue(messages)).toBe(false); + } + }); + + it('cache fallback: the live answer is cached and restored with its turn end', () => { + const live = uiMessageToChatMessage({ + id: 'a1', + role: 'assistant', + parts: [{ type: 'text', text: TEXT }, { type: TURN_END_PART_TYPE, data: END }], + } as never); + const cached = JSON.parse(JSON.stringify(sanitizeChatMessagesForCache([{ id: 'u1', role: 'user', content: QUESTION }, live]))); + expect(cached[1].parts.map((p: { type: string }) => p.type)).toEqual(['text', TURN_END_PART_TYPE]); + const restored = hydratedMessagesToChatMessages(cached); + expect(restored[1].turnEnd).toEqual(END); + expect(drawsContinue(restored)).toBe(true); + }); +}); diff --git a/ui/packages/app-shell/src/console/ai/aiChatHydration.ts b/ui/packages/app-shell/src/console/ai/aiChatHydration.ts index 8bd554fc623..7c78d8c135d 100644 --- a/ui/packages/app-shell/src/console/ai/aiChatHydration.ts +++ b/ui/packages/app-shell/src/console/ai/aiChatHydration.ts @@ -170,7 +170,9 @@ export function hydratedMessagesToChatMessages(messages: HydratedUIMessage[]): C // objectstack#37487 — with every other kept data part // (`STORED_ANSWER_DATA_PARTS`): the persisted, already-verified // `data-record-citations` list, drawn again as chips, never re-verified. - const { charts, recordCitations } = + // objectstack#38609 — and the turn end the server stored with the turn's + // last answer, so Continue is offered again after a reload. + const { charts, recordCitations, turnEnd } = message.role === 'assistant' ? storedAnswerData(message.parts) : {}; return { @@ -180,6 +182,9 @@ export function hydratedMessagesToChatMessages(messages: HydratedUIMessage[]): C ...(toolInvocations.length > 0 ? { toolInvocations } : {}), ...(charts ? { charts } : {}), ...(recordCitations ? { recordCitations } : {}), + ...(turnEnd ? { turnEnd } : {}), + // The turn the server stamped, which the answer's rating addresses. + ...(message.turnId !== undefined ? { turnId: message.turnId } : {}), }; }); } diff --git a/ui/packages/app-shell/src/console/home/__tests__/HomePage.noAgentsBuildChip-26614.test.tsx b/ui/packages/app-shell/src/console/home/__tests__/HomePage.noAgentsBuildChip-26614.test.tsx index 01b82477f44..b50e700b22b 100644 --- a/ui/packages/app-shell/src/console/home/__tests__/HomePage.noAgentsBuildChip-26614.test.tsx +++ b/ui/packages/app-shell/src/console/home/__tests__/HomePage.noAgentsBuildChip-26614.test.tsx @@ -249,13 +249,15 @@ describe('with no agent in the catalog (objectstack#26614)', () => { expect(SETUP_NEW_PACKAGE_PATH).toBe('/apps/setup/component/developer/packages?face=admin&new=package'); }); - // objectstack#37565 — the package-less scope: the "All metadata" area across packages it went to is Setup's now. - it('an author who may enter Studio but not Setup → Packages is sent to the package-less scope, never Setup (objectstack#36908)', async () => { + // objectstack#37565 — the "All metadata" area across packages it went to is Setup's now. + // objectstack#38150 — and the package-less scope it went to next is retired: the Loose list of + // flows, where that scope's addresses land. + it('an author who may enter Studio but not Setup → Packages is sent to the Loose list of flows, never Setup (objectstack#36908)', async () => { state.setupPair = false; const user = userEvent.setup(); render(); await user.click(await screen.findByTestId('home-build-in-studio')); - expect(navigateMock).toHaveBeenCalledWith('/studio/~org/metadata/flow?source=runtime'); + expect(navigateMock).toHaveBeenCalledWith('/studio/~all/metadata/flow?source=loose'); expect(navigateMock).not.toHaveBeenCalledWith(SETUP_NEW_PACKAGE_PATH); }); @@ -269,7 +271,7 @@ describe('with no agent in the catalog (objectstack#26614)', () => { */ it.each([ ['an unreported set (no `systemPermissions`) fails open, to Setup\'s New Package', undefined, SETUP_NEW_PACKAGE_PATH], - ['control: a reported set without the pair goes to the package-less scope', ['manage_metadata'], '/studio/~org/metadata/flow?source=runtime'], + ['control: a reported set without the pair goes to the Loose list of flows', ['manage_metadata'], '/studio/~all/metadata/flow?source=loose'], ])('%s', async (_case, systemPermissions, to) => { state.setupPair = 'unreported'; const answer: MePermissionsAuthenticatedResponse = { diff --git a/ui/packages/app-shell/src/console/organizations/OrganizationsPage.tsx b/ui/packages/app-shell/src/console/organizations/OrganizationsPage.tsx index e1d108aa49c..204cf145f15 100644 --- a/ui/packages/app-shell/src/console/organizations/OrganizationsPage.tsx +++ b/ui/packages/app-shell/src/console/organizations/OrganizationsPage.tsx @@ -4,6 +4,11 @@ * Supabase-style landing page that lists the organizations the current user * belongs to. Users can search, select (which switches the active * organization and navigates to `/home`), or create a new organization. + * + * Above the list it shows the user's pending invitations (the server's + * `list-user-invitations` inbox), each opening the existing accept page. While + * one is open neither first-run shortcut fires — the one-org auto-skip and the + * zero-org create dialog would otherwise carry the user past it. * @module */ @@ -18,13 +23,31 @@ import { EmptyTitle, EmptyDescription, } from '@object-ui/components'; -import { Plus, Search, Loader2 } from 'lucide-react'; +import { Plus, Search, Loader2, Mail } from 'lucide-react'; import { useAuth } from '@object-ui/auth'; -import type { AuthOrganization } from '@object-ui/auth'; -import { useObjectTranslation } from '@object-ui/i18n'; +import type { AuthInvitation, AuthOrganization } from '@object-ui/auth'; +import { useDisplayLocale, useObjectTranslation } from '@object-ui/i18n'; import { useNavigate, useSearchParams } from 'react-router-dom'; import { CreateWorkspaceDialog } from './CreateWorkspaceDialog.js'; import { resolveRootUrl } from './resolveHomeUrl.js'; +import { resolveOrgRoleLabel } from './orgRoleLabel.js'; + +/** + * better-auth's code for the invitation inbox refused to a session whose + * address is not verified (objectstack plugin-auth + * `list-user-invitations-verification.ts`). The page then shows no section: + * the accept page is where an unverified invitee is sent to verify. + */ +const LIST_INVITATIONS_NEEDS_VERIFIED_EMAIL_CODE = + 'EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION'; + +/** + * The server answers `pending` rows only, expired ones included; an expired + * invitation cannot be accepted, so it is not offered. + */ +function isOpenInvitation(inv: AuthInvitation, now: number): boolean { + return !inv.expiresAt || Date.parse(inv.expiresAt) > now; +} function getOrgInitials(name: string): string { return name @@ -37,6 +60,7 @@ function getOrgInitials(name: string): string { export function OrganizationsPage() { const { t } = useObjectTranslation(); + const displayLocale = useDisplayLocale(); const navigate = useNavigate(); // Two deliberate ways to reach this page (vs the auto-skipping post-login // redirect), both from the avatar menu: @@ -52,11 +76,13 @@ export function OrganizationsPage() { const manageMode = searchParams.get('manage') === '1'; const wantsCreate = searchParams.get('create') === '1'; const { + user, organizations, activeOrganization, isOrganizationsLoading, switchOrganization, getAuthConfig, + listUserInvitations, } = useAuth(); const [query, setQuery] = useState(''); @@ -83,6 +109,39 @@ export function OrganizationsPage() { }; }, [getAuthConfig]); + // `null` while the inbox is being read; `[]` when there is nothing to offer + // (none pending, or the listing refused). + const [pendingInvitations, setPendingInvitations] = useState(null); + + // Read once per signed-in user, keyed on the id, never on the identity of the + // context's callback (ui/AGENTS.md #10). + const listUserInvitationsRef = useRef(listUserInvitations); + listUserInvitationsRef.current = listUserInvitations; + const userId = user?.id; + useEffect(() => { + let cancelled = false; + listUserInvitationsRef.current() + .then((rows) => { + if (cancelled) return; + const now = Date.now(); + setPendingInvitations(rows.filter((inv) => isOpenInvitation(inv, now))); + }) + .catch((err: unknown) => { + if (cancelled) return; + const code = (err as { code?: unknown } | null)?.code; + if (code !== LIST_INVITATIONS_NEEDS_VERIFIED_EMAIL_CODE) { + console.warn('[OrganizationsPage] Pending invitations are not shown: listing failed:', err); + } + setPendingInvitations([]); + }); + return () => { + cancelled = true; + }; + }, [userId]); + + const invitationsLoading = pendingInvitations === null; + const hasPendingInvitations = (pendingInvitations?.length ?? 0) > 0; + const orgList = organizations ?? []; const filtered = useMemo(() => { @@ -128,8 +187,9 @@ export function OrganizationsPage() { const autoSelectedRef = useRef(false); useEffect(() => { if (autoSelectedRef.current) return; - if (isOrganizationsLoading) return; + if (isOrganizationsLoading || invitationsLoading) return; if (wantsCreate) return; // came to create — don't bounce + if (hasPendingInvitations) return; // a pending invitation is a choice to make here if (orgList.length !== 1) return; autoSelectedRef.current = true; // Single-org users have no real choice to make. In manage mode (`?manage=1`, @@ -142,7 +202,14 @@ export function OrganizationsPage() { void handleSelect(orgList[0]); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [isOrganizationsLoading, orgList.length, manageMode, wantsCreate]); + }, [ + isOrganizationsLoading, + invitationsLoading, + hasPendingInvitations, + orgList.length, + manageMode, + wantsCreate, + ]); // Open the create dialog when arriving via the header "Create workspace" // entry (`?create=1`), OR for a brand-new user who has ZERO organizations: @@ -153,22 +220,32 @@ export function OrganizationsPage() { const createOpenedRef = useRef(false); useEffect(() => { if (isOrganizationsLoading) return; - const firstRunNoOrg = orgList.length === 0 && canCreateOrg; + // A zero-org user with a pending invitation is joining, not creating. + const firstRunNoOrg = + orgList.length === 0 && canCreateOrg && !invitationsLoading && !hasPendingInvitations; if ((wantsCreate || firstRunNoOrg) && !createOpenedRef.current) { createOpenedRef.current = true; setIsCreateOpen(true); } - }, [wantsCreate, orgList.length, canCreateOrg, isOrganizationsLoading]); + }, [ + wantsCreate, + orgList.length, + canCreateOrg, + isOrganizationsLoading, + invitationsLoading, + hasPendingInvitations, + ]); // Show a spinner while we're either still loading, about to auto-redirect // because there's only one org, or about to auto-open the create dialog for a // brand-new zero-org user. This prevents the picker / empty-state from - // briefly flashing on screen before the redirect or dialog. + // briefly flashing on screen before the redirect or dialog. The invitation + // inbox is part of "still loading": both shortcuts wait for its answer. const willAutoSelect = - !wantsCreate && !isOrganizationsLoading && orgList.length === 1; + !wantsCreate && !hasPendingInvitations && orgList.length === 1; const willAutoCreate = - !isOrganizationsLoading && orgList.length === 0 && canCreateOrg && !createOpenedRef.current; - if (isOrganizationsLoading || willAutoSelect || willAutoCreate) { + !hasPendingInvitations && orgList.length === 0 && canCreateOrg && !createOpenedRef.current; + if (isOrganizationsLoading || invitationsLoading || willAutoSelect || willAutoCreate) { return (
@@ -210,6 +287,62 @@ export function OrganizationsPage() { )}
+ {hasPendingInvitations && pendingInvitations && ( +
+

+ {t('organization.pendingInvitations.title', { defaultValue: 'Pending invitations' })} +

+

+ {t('organization.pendingInvitations.description', { + defaultValue: 'You have been invited to join these organizations.', + })} +

+
    + {pendingInvitations.map((inv) => ( +
  • + + + + + +
    +
    + {inv.organizationName ?? inv.organizationId} +
    +
    + {resolveOrgRoleLabel(inv.role, t)} + {inv.expiresAt && ( + <> + {' · '} + {t('organization.invitations.expiresAt', { defaultValue: 'Expires' })}{' '} + {new Date(inv.expiresAt).toLocaleDateString(displayLocale)} + + )} +
    +
    + +
  • + ))} +
+
+ )} + {orgList.length === 0 ? ( diff --git a/ui/packages/app-shell/src/console/organizations/__tests__/OrganizationsPage.organizationNoun-12851.test.tsx b/ui/packages/app-shell/src/console/organizations/__tests__/OrganizationsPage.organizationNoun-12851.test.tsx index 9c6dd9c37f8..1e88fc21d38 100644 --- a/ui/packages/app-shell/src/console/organizations/__tests__/OrganizationsPage.organizationNoun-12851.test.tsx +++ b/ui/packages/app-shell/src/console/organizations/__tests__/OrganizationsPage.organizationNoun-12851.test.tsx @@ -31,6 +31,7 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({ isOrganizationsLoading: false, switchOrganization: vi.fn(), getAuthConfig: vi.fn().mockResolvedValue({ features: { multiOrgEnabled: true } }), + listUserInvitations: vi.fn().mockResolvedValue([]), }), })); diff --git a/ui/packages/app-shell/src/console/organizations/__tests__/OrganizationsPage.test.tsx b/ui/packages/app-shell/src/console/organizations/__tests__/OrganizationsPage.test.tsx index 1cd4d910598..322166141c3 100644 --- a/ui/packages/app-shell/src/console/organizations/__tests__/OrganizationsPage.test.tsx +++ b/ui/packages/app-shell/src/console/organizations/__tests__/OrganizationsPage.test.tsx @@ -71,6 +71,7 @@ beforeEach(() => { isOrganizationsLoading: false, switchOrganization: vi.fn(), getAuthConfig: vi.fn().mockResolvedValue({ features: { multiOrgEnabled: true } }), + listUserInvitations: vi.fn().mockResolvedValue([]), }; }); @@ -125,3 +126,85 @@ describe('OrganizationsPage — the card\'s "Manage" control (objectui#13461)', expect(authState.switchOrganization).not.toHaveBeenCalled(); }); }); + +describe('OrganizationsPage — pending invitations (objectstack#38535)', () => { + const FUTURE = new Date(Date.now() + 86_400_000).toISOString(); + const invitation = (over: Record = {}) => ({ + id: 'inv1', + organizationId: 'org-gamma', + organizationName: 'Gamma', + email: 'ada@example.test', + role: 'member', + status: 'pending', + expiresAt: FUTURE, + ...over, + }); + + it('lists a pending invitation as a row that opens its accept page', async () => { + authState.organizations = [ + { id: 'o1', name: 'Alpha', slug: 'alpha' }, + { id: 'o2', name: 'Beta', slug: 'beta' }, + ]; + authState.listUserInvitations = vi.fn().mockResolvedValue([invitation()]); + render(); + const row = await screen.findByTestId('pending-invitation-inv1'); + expect(row).toHaveTextContent('Gamma'); + fireEvent.click(screen.getByTestId('pending-invitation-open-inv1')); + expect(navigate).toHaveBeenCalledWith('/accept-invitation/inv1'); + }); + + it('shows no section when nothing is pending', async () => { + authState.organizations = [ + { id: 'o1', name: 'Alpha', slug: 'alpha' }, + { id: 'o2', name: 'Beta', slug: 'beta' }, + ]; + render(); + await screen.findByTestId('organization-card-alpha'); + expect(screen.queryByTestId('organizations-pending-invitations')).toBeNull(); + }); + + it('a single-org user with a pending invitation stays on the page (no auto-skip)', async () => { + authState.organizations = [{ id: 'o1', name: 'Alpha', slug: 'alpha' }]; + authState.listUserInvitations = vi.fn().mockResolvedValue([invitation()]); + render(); + await screen.findByTestId('pending-invitation-inv1'); + expect(authState.switchOrganization).not.toHaveBeenCalled(); + expect(navigate).not.toHaveBeenCalled(); + }); + + it('a zero-org user with a pending invitation is not pushed into the create dialog', async () => { + authState.listUserInvitations = vi.fn().mockResolvedValue([invitation()]); + render(); + await screen.findByTestId('pending-invitation-inv1'); + expect(screen.queryByTestId('create-workspace-dialog')).toBeNull(); + }); + + it('hides the section when the inbox refuses an unverified address, and first run proceeds', async () => { + authState.listUserInvitations = vi.fn().mockRejectedValue( + Object.assign(new Error('verify first'), { + code: 'EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION', + status: 403, + }), + ); + render(); + await waitFor(() => + expect(screen.getByTestId('create-workspace-dialog')).toBeInTheDocument(), + ); + expect(screen.queryByTestId('organizations-pending-invitations')).toBeNull(); + }); + + it('does not offer an expired invitation, and names the organization by id when the listing carries no name', async () => { + authState.organizations = [ + { id: 'o1', name: 'Alpha', slug: 'alpha' }, + { id: 'o2', name: 'Beta', slug: 'beta' }, + ]; + authState.listUserInvitations = vi.fn().mockResolvedValue([ + invitation({ id: 'old', expiresAt: new Date(Date.now() - 1000).toISOString() }), + invitation({ id: 'inv2', organizationName: undefined }), + ]); + render(); + const row = await screen.findByTestId('pending-invitation-inv2'); + expect(row).toHaveTextContent('org-gamma'); + expect(screen.queryByTestId('pending-invitation-old')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx index d99be8b5346..bb71a17137b 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx +++ b/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx @@ -1457,6 +1457,65 @@ describe('sanitizeChatMessagesForCache — a pending approval survives the cache expect(decision?.state).toBe('success'); }); + it('restores a cached entry from the stored pending_approval envelope alone', async () => { + // The retired literal with `pendingActionId` in `output`, as the cache + // writer mints it and as a conversation stored before the answer moved + // carries it. The writer also writes the id as a part key; it is left out + // here on purpose, so what is proven is the one recogniser reading the + // stored answer, not the cache-side fallback beside it. Approve still + // reaches the item. + const oldEntry: HydratedUIMessage[] = [ + { + id: 'a1', + role: 'assistant', + parts: [ + { type: 'text', text: 'This needs your approval.' }, + { + type: 'tool-action_delete_task', + toolCallId: 'tc-approve', + toolName: 'action_delete_task', + state: 'approval-requested', + output: { status: 'pending_approval', pendingActionId: PENDING_ACTION_ID }, + }, + ], + }, + ]; + const restored = hydratedMessagesToChatMessages(throughLocalStorage(oldEntry)); + expect(restored[0]?.toolInvocations?.[0]?.pendingActionId).toBe(PENDING_ACTION_ID); + + const { urls, decision } = await pressApprove(restored); + expect(urls).toEqual([`${API_BASE}/pending-actions/${PENDING_ACTION_ID}/approve`]); + expect(decision?.state).toBe('success'); + }); + + it('round-trips a live pending_confirmation answer through the cache to Approve', async () => { + const live = uiMessageToChatMessage({ + ...liveUiMessage, + parts: liveUiMessage.parts.map((p) => + 'output' in p + ? { + ...p, + output: { + status: 'pending_confirmation', + pendingId: PENDING_ACTION_ID, + message: 'A confirmation was sent to you.', + actionName: 'delete_task', + }, + } + : p, + ), + }); + expect(live.toolInvocations?.[0]?.pendingActionId).toBe(PENDING_ACTION_ID); + expect(live.toolInvocations?.[0]?.state).toBe('approval-requested'); + + const restored = hydratedMessagesToChatMessages( + throughLocalStorage(sanitizeChatMessagesForCache([live])), + ); + const { urls, decision } = await pressApprove(restored); + expect(urls).toEqual([`${API_BASE}/pending-actions/${PENDING_ACTION_ID}/approve`]); + expect(decision?.state).toBe('success'); + }); + it('writes the AI SDK approval envelope as a part key, where the hydration mapper reads it', () => { // The envelope rides the PART on both directions of the server path, so the // cache writes it as a part key too. The input shape here is the one diff --git a/ui/packages/app-shell/src/hooks/useChatConversation.test.ts b/ui/packages/app-shell/src/hooks/useChatConversation.test.ts index d385ec5fe9e..888e9536a9c 100644 --- a/ui/packages/app-shell/src/hooks/useChatConversation.test.ts +++ b/ui/packages/app-shell/src/hooks/useChatConversation.test.ts @@ -320,3 +320,21 @@ describe('aiMessageRowsToServerMessages — flat share rows → ModelMessage sha ]); }); }); + +describe('toUIMessages — the turn the server stamped (objectstack#31865)', () => { + it('carries each row\'s turnId, null included, and adds none to a row without one', () => { + const out = toUIMessages([ + { id: 'row-1', role: 'user', content: 'How many open deals?', turnId: 'turn-9' }, + { id: 'row-2', role: 'assistant', content: 'There are 12 open deals.', turnId: 'turn-9' }, + { id: 'row-3', role: 'assistant', content: 'Stored with no turn.', turnId: null }, + { id: 'row-4', role: 'assistant', content: 'Written before turns existed.' }, + ]); + expect(out.map((m) => [m.id, m.turnId])).toEqual([ + ['row-1', 'turn-9'], + ['row-2', 'turn-9'], + ['row-3', null], + ['row-4', undefined], + ]); + expect('turnId' in out[3]).toBe(false); + }); +}); diff --git a/ui/packages/app-shell/src/hooks/useChatConversation.ts b/ui/packages/app-shell/src/hooks/useChatConversation.ts index 7d8b5ca1880..52ae48681f0 100644 --- a/ui/packages/app-shell/src/hooks/useChatConversation.ts +++ b/ui/packages/app-shell/src/hooks/useChatConversation.ts @@ -44,6 +44,12 @@ export interface HydratedUIMessage { id: string; role: 'user' | 'assistant' | 'system'; parts: HydratedUIMessagePart[]; + /** + * The turn the server stamped on the message (`AiConversationMessageSchema.turnId`, + * `@objectstack/spec/api`), carried from a server reload only; the answer's + * rating routes address it. Absent on a cache restore. + */ + turnId?: string | null; } export interface UseChatConversationOptions { @@ -252,6 +258,8 @@ interface CacheableChatMessage { charts?: StoredAnswerData['charts']; /** objectstack#37487 — the answer's verified record citations, cached as persisted. */ recordCitations?: StoredAnswerData['recordCitations']; + /** objectstack#38609 — why the answer's turn ended and whether it may be resumed, cached as read. */ + turnEnd?: StoredAnswerData['turnEnd']; } /** @@ -266,6 +274,10 @@ interface CacheableChatMessage { * second hand-rolled reader on the cache side would be the second dialect of * one contract that Commandment #0.1 refuses. * + * It mints `{ status: 'pending_approval', pendingActionId }` whichever answer + * the live result carried, `pending_confirmation` with `pendingId` included: + * the one detector reads both, so a cached entry restores either way. + * * The two keys the detector reads are the only two written: the framework's * real envelope also carries a human `message` and the proposed arguments, and * none of that is re-serialized, which is why a cached thread does not grow a @@ -419,7 +431,7 @@ export function sanitizeChatMessagesForCache( const parts: HydratedUIMessagePart[] = storedAnswerParts( message.content ?? '', message.role === 'assistant' - ? { charts: message.charts, recordCitations: message.recordCitations } + ? { charts: message.charts, recordCitations: message.recordCitations, turnEnd: message.turnEnd } : {}, ); if (message.role === 'assistant') { @@ -502,6 +514,14 @@ interface ServerMessage { id?: string; role: string; content: unknown; + /** `AiConversationMessageSchema.turnId`: absent or null on a message stored with no turn. */ + turnId?: string | null; + /** + * `AiConversationMessageSchema.turnEnd`: on the turn's last message, why the + * turn ended and whether it may be resumed. Read through `TurnEndSchema` by + * `extractTurnEnd` once it is a `data-turn-end` part, never here. + */ + turnEnd?: unknown; } export interface ServerConversation { @@ -636,10 +656,17 @@ export function toUIMessages(rows: ServerMessage[] | undefined): HydratedUIMessa } } } + // objectstack#38609 — the stored turn end goes back as the `data-turn-end` + // part the live stream gave (`STORED_ANSWER_DATA_PARTS.turnEnd`), so one + // reader, `storedAnswerData`, parses it on every path. + if (role === 'assistant' && row.turnEnd && typeof row.turnEnd === 'object') { + parts.push(...storedAnswerParts('', { turnEnd: row.turnEnd })); + } out.push({ id: row.id ?? `msg-${idx}`, role, parts, + ...(row.turnId !== undefined ? { turnId: row.turnId } : {}), }); }); return out; diff --git a/ui/packages/app-shell/src/hooks/useOpenedOnce.ts b/ui/packages/app-shell/src/hooks/useOpenedOnce.ts new file mode 100644 index 00000000000..04f9e2007c5 --- /dev/null +++ b/ui/packages/app-shell/src/hooks/useOpenedOnce.ts @@ -0,0 +1,19 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { useState } from 'react'; + +/** + * objectstack#37444 — `true` from the first render `open` is, and from then on. + * A lazy panel or dialog behind it loads only when someone opens it (closed, it + * draws nothing, so mounting it with every page only fetched its chunk before + * the page's first screen), and stays mounted after, so closing it animates and + * keeps its state as before. The state is adjusted during render, React's way of + * deriving state from a prop, so the opening render already mounts it. + * + * Package-internal: not exported from `./index.ts` or the package entry. + */ +export function useOpenedOnce(open: boolean): boolean { + const [opened, setOpened] = useState(open); + if (open && !opened) setOpened(true); + return opened || open; +} diff --git a/ui/packages/app-shell/src/index.ts b/ui/packages/app-shell/src/index.ts index 7bb4bf78f63..a0820b13e6d 100644 --- a/ui/packages/app-shell/src/index.ts +++ b/ui/packages/app-shell/src/index.ts @@ -617,8 +617,8 @@ export { // `/studio` routes mounts it as their index. export { StudioEntryRedirect } from './views/studio-design/StudioEntryRedirect.js'; // objectstack#36909 — a retired pillar address (`/studio/`, -// `/studio//data`, `/automations`, `/access`, `/interfaces`, -// `/studio/~org/...`) lands on the page that replaced it in one redirect. A +// `/studio//data`, `/automations`, `/access`, `/interfaces`, and +// every `/studio/~org/...`) lands on the page that replaced it in one redirect. A // host that declares the `/studio` routes mounts it on `:packageId` and // `:packageId/:tab`, with the builder as its children. export { StudioPillarRedirect } from './views/studio-design/StudioPillarRedirect.js'; @@ -629,15 +629,16 @@ export { StudioEntryPermissionsProvider, useStudioEntryPermissions, } from './views/studio-design/studioEntryPermissions.js'; -// The one Studio scope that is not a package (objectui#11553): the -// organization's own package-less flows, listed at -// `/studio/~org/metadata/flow?source=runtime` (objectstack#36903; the old -// `/studio/~org/automations` redirects there). A host that declares the -// `/studio` routes reads the reserved segment from here. +// objectstack#38150 — Studio's package-less scope (`/studio/~org/...`) is +// retired: every address of it lands on the Loose list of flows on the +// cross-package leg, `/studio/~all/metadata/flow?source=loose`. The surface +// and `StudioPillarRedirect` redirect the addresses they mount on; a host +// that declares the `/studio` routes reads the reserved segment and the +// target from here, to answer those addresses on a route of its own. export { - STUDIO_ORG_SCOPE_SEGMENT, - studioOrgScopePath, -} from './views/studio-design/studioScope.js'; + RETIRED_ORG_SCOPE_SEGMENT, + retiredOrgScopeTarget, +} from './views/studio-design/studioOrgScopeRetired.js'; // Studio's "All metadata" area (objectstack ADR-0146 D1): per package, at // `/studio//metadata/*`, and across packages at the // reserved `/studio/~all/metadata/*`. A host that declares the `/studio` routes diff --git a/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx b/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx index 503b4862f60..76dab385653 100644 --- a/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx @@ -318,11 +318,13 @@ describe('「Add app」 offers 「New blank app」 whatever the catalog serves, ]); }); - // objectstack#37565 — the cross-package directory moved to Setup; the door is Studio's package-less scope, for now. - it('an author who may enter Studio but not Setup → Packages is sent to Studio\'s package-less scope, never Setup (objectstack#36908)', () => { + // objectstack#37565 — the cross-package directory moved to Setup. objectstack#38150 — the + // package-less scope the door opened next is retired: Studio's Loose list of flows, where + // that scope's addresses land. + it('an author who may enter Studio but not Setup → Packages is sent to Studio\'s Loose list of flows, never Setup (objectstack#36908)', () => { setupPair = false; const choices = addChoices(); - expect(choices.getByTestId('sidebar-app-menu-add-new-in-studio')).toHaveAttribute('href', '/studio/~org/metadata/flow?source=runtime'); + expect(choices.getByTestId('sidebar-app-menu-add-new-in-studio')).toHaveAttribute('href', '/studio/~all/metadata/flow?source=loose'); }); it.each([ @@ -686,14 +688,14 @@ describe('the docs portal\'s head names no app and only switches apps (objectsta expect(choices.queryByText('Build with AI')).toBeNull(); }); - it('an author who may not open Setup → Packages gets 「New blank app」 to Studio\'s package-less scope (objectstack#37565)', () => { + it('an author who may not open Setup → Packages gets 「New blank app」 to Studio\'s Loose list of flows (objectstack#37565, objectstack#38150)', () => { setupPair = false; apps = [CRM]; admin = true; renderPortalMenu(); expect( within(screen.getByTestId('add-app-choices')).getByTestId('sidebar-app-menu-add-new-in-studio'), - ).toHaveAttribute('href', '/studio/~org/metadata/flow?source=runtime'); + ).toHaveAttribute('href', '/studio/~all/metadata/flow?source=loose'); }); it('guard: handed no entries, it draws no 「Add app」 and no separator for it', () => { diff --git a/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPinsSave-36366.test.ts b/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPinsSave-36366.test.ts index af49833ea44..f280227b2df 100644 --- a/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPinsSave-36366.test.ts +++ b/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPinsSave-36366.test.ts @@ -165,6 +165,17 @@ describe('saving the header pins (objectstack#36366)', () => { }); }); + it('objectstack#36496: the held `selection` arm (the multi-select bar, no header) survives a header save as held', async () => { + const extension = { extend: 'crm_lead', actionLayout: { selection: { pinned: ['mass_assign'], more: [] } } }; + const { d, calls } = doors({ writable: false, extension }); + await saveObjectPins(input({ record: { pinned: ['convert'] } }), TEXTS, d); + const save = calls.find((c) => c[0] === 'save'); + expect(save?.[3]).toEqual({ + extend: 'crm_lead', + actionLayout: { selection: { pinned: ['mass_assign'], more: [] }, record: { pinned: ['convert'] } }, + }); + }); + it('S3: a staged value that arranges as the object is served writes nothing', async () => { const served = { ...SERVED, actionLayout: { record: { pinned: ['log_call'] } } }; const { d, calls } = doors({ writable: true }); diff --git a/ui/packages/app-shell/src/layout/designModeHeaderPinsModel.ts b/ui/packages/app-shell/src/layout/designModeHeaderPinsModel.ts index 90b201665f0..51535947ccf 100644 --- a/ui/packages/app-shell/src/layout/designModeHeaderPinsModel.ts +++ b/ui/packages/app-shell/src/layout/designModeHeaderPinsModel.ts @@ -24,7 +24,13 @@ import { } from '@objectstack/spec/data'; import { actionRendersAt, readActionLayoutArm, type ActionLayoutArm } from '@object-ui/types'; -export type PinPage = ObjectActionLayoutScope; +/** + * The scopes this panel arranges: the two HEADERS. The object's third arm, + * `selection` (objectstack#36496), orders the multi-select bar, which is no + * header; the panel leaves it as held, and a save keeps it (`actionLayoutValue` + * writes only the changed header scopes over the held value). + */ +export type PinPage = Exclude; /** One scope's arrangement: the buttons, then the 「More」 menu's order. */ export type PinArm = ActionLayoutArm; diff --git a/ui/packages/app-shell/src/services/__tests__/builtinComponents.formListWordsOffBoot-37444.test.tsx b/ui/packages/app-shell/src/services/__tests__/builtinComponents.formListWordsOffBoot-37444.test.tsx new file mode 100644 index 00000000000..72bfc9b61da --- /dev/null +++ b/ui/packages/app-shell/src/services/__tests__/builtinComponents.formListWordsOffBoot-37444.test.tsx @@ -0,0 +1,102 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37444 — the boot registrations do not carry the Studio + * designer's string table onto every page's first load. + * + * `services/builtinComponents.tsx` runs at boot: it registers the `form` + * metadata list with `FORM_LIST_COLUMNS`. When `formListColumns.tsx` imported + * the designer's `t()` (`metadata-admin/i18n.ts`) statically, the Console's + * `index.html` preloaded that module and the `studio` namespace's English + * catalogue on home, list and record pages alike (about 81 KiB, measured on + * the Console build of `0ba5e06ae7` against `1afd9c13`). The "On" cell now + * loads its words with `import()` on first render. + * + * The walk follows each module's STATIC relative imports in source (type-only + * imports and `import()` excluded, as the browser loads them) and asserts the + * boot module never reaches the designer's string table. It is checked to see + * the edge it guards: the Studio list module itself must reach it. + */ +import { readFileSync, existsSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import * as React from 'react'; +import { render, screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; +import { FORM_LIST_COLUMNS } from '../../views/studio-design/publicForm/formListColumns.js'; + +const SRC = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); +const DESIGNER_I18N_FILE = resolve(SRC, 'views/metadata-admin/i18n.ts'); +const DESIGNER_I18N_SPECIFIER = /^@object-ui\/i18n\/namespaces\/studio$/; + +/** Static value imports of one module: `import … from '…'`, `import '…'` and `export … from '…'`, never `import type`. */ +function staticSpecifiers(code: string): string[] { + const out: string[] = []; + const re = /^\s*(import|export)\s+(?!type\s)([^;]*?\bfrom\s+)?['"]([^'"]+)['"]/gm; + for (const m of code.matchAll(re)) { + if (m[1] === 'export' && !m[2]) continue; + out.push(m[3]); + } + return out; +} + +function resolveRelative(from: string, specifier: string): string | null { + const base = resolve(dirname(from), specifier.replace(/\.js$/, '')); + for (const candidate of [`${base}.ts`, `${base}.tsx`, resolve(base, 'index.ts'), resolve(base, 'index.tsx')]) { + if (existsSync(candidate)) return candidate; + } + return null; +} + +/** The first chain from `entry` to the designer string table, or `null`. */ +function chainToDesignerI18n(entry: string): string[] | null { + const start = resolve(SRC, entry); + const prev = new Map([[start, null]]); + const queue = [start]; + const chainTo = (at: string | null, tail: string[] = []) => { + const chain = [...tail]; + for (; at; at = prev.get(at) ?? null) chain.unshift(at.slice(SRC.length + 1)); + return chain; + }; + while (queue.length) { + const file = queue.shift() as string; + for (const specifier of staticSpecifiers(readFileSync(file, 'utf8'))) { + if (DESIGNER_I18N_SPECIFIER.test(specifier)) return chainTo(file, [specifier]); + if (!specifier.startsWith('.')) continue; + const next = resolveRelative(file, specifier); + if (!next || prev.has(next)) continue; + prev.set(next, file); + if (next === DESIGNER_I18N_FILE) return chainTo(next); + queue.push(next); + } + } + return null; +} + +describe('the boot registrations carry no Studio designer string table (objectstack#37444)', () => { + it('the walk sees the edge it guards: the Studio resource list reaches the designer table', () => { + expect(chainToDesignerI18n('views/metadata-admin/ResourceListPage.tsx')).not.toBeNull(); + }); + + it('services/builtinComponents.tsx reaches no designer string table through static imports', () => { + expect(chainToDesignerI18n('services/builtinComponents.tsx')).toBeNull(); + }); + + it('the form list "On" cell still shows its translated words once rendered', { timeout: 20000 }, async () => { + const column = FORM_LIST_COLUMNS.find((c) => c.key === 'publicState'); + const on = { name: 'intake', sharing: { enabled: true, allowAnonymous: true, publicLink: 'intake' } }; + const off = { name: 'draft', sharing: { enabled: false, publicLink: 'draft' } }; + // The Studio list loads the designer's strings before it draws this column. + await import('../../views/metadata-admin/i18n.js'); + render( +
+ {column?.render?.(undefined, on) as React.ReactNode} + {column?.render?.(undefined, off) as React.ReactNode} +
, + ); + expect(await screen.findByText('On', undefined, { timeout: 10000 })).toBeTruthy(); + expect(await screen.findByText('Off', undefined, { timeout: 10000 })).toBeTruthy(); + expect(screen.getByTestId('form-list-state-intake').getAttribute('data-on')).toBe('true'); + expect(screen.getByTestId('form-list-state-draft').getAttribute('data-on')).toBe('false'); + }); +}); diff --git a/ui/packages/app-shell/src/services/builtinComponents.tsx b/ui/packages/app-shell/src/services/builtinComponents.tsx index a2217604194..bd11096a839 100644 --- a/ui/packages/app-shell/src/services/builtinComponents.tsx +++ b/ui/packages/app-shell/src/services/builtinComponents.tsx @@ -19,6 +19,7 @@ import { lazy, Suspense } from 'react'; import { registerAppComponent } from './componentRegistry.js'; import { lazyPage, LazyPageFallback as MetadataAdminFallback } from './lazyPage.js'; import { registerMetadataResource } from '../views/metadata-admin/registry.js'; +import { FORM_LIST_COLUMNS } from '../views/studio-design/publicForm/formListColumns.js'; import { CONNECTOR_CREDENTIALS_REF } from '../views/setup/connectorCredentials.js'; import { CONNECTOR_CONNECTIONS_REF } from '../views/setup/connectorConnections.js'; import { PERMISSION_SET_ASSIGNMENT_REF, POSITION_HOLDERS_REF } from '../views/setup/peopleAssignments.js'; @@ -453,6 +454,26 @@ registerMetadataResource({ listFilter: (item) => !isAggregatedViewContainer(item), }); +// objectstack#37087 (ADR-0159 D9) — the `form` type: its list's columns and +// its own editor, Studio's form designer (`studio-design/publicForm/`), on +// the item and on `…/form/new`. The editor loads the first time a form opens. +// Studio's menu lists `form` under UI (`studioMenuPlacement.ts`). +const FormItemEditPage = lazyPage('form', () => + import('../views/studio-design/publicForm/PublicFormsDesigner.js').then((m) => m.FormItemEditPage), +); +const FormItemCreatePage = lazyPage('form', () => + import('../views/studio-design/publicForm/PublicFormsDesigner.js').then((m) => m.FormItemCreatePage), +); +registerMetadataResource({ + type: 'form', + domain: 'ui', + searchableFields: ['name', 'label', 'title', 'object'], + // `/meta/types` serves no list layout for `form`: these are the console's own. + listColumns: FORM_LIST_COLUMNS, + EditPage: FormItemEditPage, + CreatePage: FormItemCreatePage, +}); + registerMetadataResource({ type: 'dashboard', label: 'Dashboards', diff --git a/ui/packages/app-shell/src/utils/__tests__/appRoute.test.ts b/ui/packages/app-shell/src/utils/__tests__/appRoute.test.ts index ccb2cbef718..5ba1f3054f0 100644 --- a/ui/packages/app-shell/src/utils/__tests__/appRoute.test.ts +++ b/ui/packages/app-shell/src/utils/__tests__/appRoute.test.ts @@ -259,12 +259,12 @@ describe('isApprovalsInboxLink (objectstack#35505)', () => { describe('appStudioDesignPath', () => { const crm = { name: 'crm', _packageId: 'com.acme.crm' }; - it('resolves an admin viewing a packaged app to its design surface', () => { - expect(appStudioDesignPath(crm, true)).toBe('/studio/com.acme.crm/data'); + it("resolves an admin viewing a packaged app to its package's 概览 Overview (objectstack#38392)", () => { + expect(appStudioDesignPath(crm, true)).toBe('/studio/com.acme.crm/overview'); }); it('URL-encodes the package id', () => { expect(appStudioDesignPath({ _packageId: 'com.acme/crm' }, true)).toBe( - '/studio/com.acme%2Fcrm/data', + '/studio/com.acme%2Fcrm/overview', ); }); it('returns null for non-admins', () => { @@ -377,16 +377,16 @@ describe('appStudioRoutePath', () => { ); }); - it('falls back to the plain Data tab for the app root and the system area', () => { - // No route type at all (bare /apps/:pkg) → Data tab. - expect(appStudioRoutePath(crm, true, { type: undefined, name: undefined })).toBe('/studio/com.acme.crm/data'); + it("falls back to the package's 概览 Overview for the app root and the system area (objectstack#38392)", () => { + // No route type at all (bare /apps/:pkg) → 概览. + expect(appStudioRoutePath(crm, true, { type: undefined, name: undefined })).toBe('/studio/com.acme.crm/overview'); // The system settings area is not an object. - expect(appStudioRoutePath(crm, true, { type: 'system', name: 'members' })).toBe('/studio/com.acme.crm/data'); + expect(appStudioRoutePath(crm, true, { type: 'system', name: 'members' })).toBe('/studio/com.acme.crm/overview'); }); - it('falls back to the Data tab for an interface list route (no surface name)', () => { + it("falls back to the package's 概览 Overview for an interface list route (no surface name)", () => { // e.g. /apps/:pkg/page with no specific page selected. - expect(appStudioRoutePath(crm, true, { type: 'page', name: undefined })).toBe('/studio/com.acme.crm/data'); + expect(appStudioRoutePath(crm, true, { type: 'page', name: undefined })).toBe('/studio/com.acme.crm/overview'); }); it('returns null for non-admins (bridge hidden), for both surface and Data targets', () => { diff --git a/ui/packages/app-shell/src/utils/appRoute.ts b/ui/packages/app-shell/src/utils/appRoute.ts index e69d601fae8..dc2d48a0e51 100644 --- a/ui/packages/app-shell/src/utils/appRoute.ts +++ b/ui/packages/app-shell/src/utils/appRoute.ts @@ -15,7 +15,8 @@ * framework-owned, app-independent page for this user (see below). */ -import { studioHomePath, studioItemPath, studioMetadataItemAddress } from '../views/studio-design/studioAddress.js'; +import { studioItemPath, studioMetadataItemAddress } from '../views/studio-design/studioAddress.js'; +import { studioPackageOverviewPath } from '../views/studio-design/studioOverviewAddress.js'; /** * The minimal app shape THESE ROUTE HELPERS read. @@ -243,8 +244,8 @@ export function isApprovalsInboxLink(actionUrl: string | null | undefined): bool /** * App → Studio reverse bridge (ADR-0080). Resolves a running app to its owning - * package's design surface (`/studio/:packageId/data`), or `null` when there is - * nothing to open: + * package's 概览 Overview (`/studio/:packageId/overview`, where every door into + * a package lands, objectstack#38392), or `null` when there is nothing to open: * - the viewer is not a workspace admin (designing mutates shared package * metadata, so the entry point is admin-only — mirrors the runtime editors); * - the app has no owning package (runtime/DB apps), or its container is the @@ -262,7 +263,7 @@ export function appStudioDesignPath( if (!isWorkspaceAdmin) return null; const packageId = studioPackageId(app); if (!packageId) return null; - return studioHomePath(packageId); + return studioPackageOverviewPath(packageId); } /** @@ -322,8 +323,8 @@ const INTERFACE_SURFACE_ROUTE_TYPES = new Set(['dashboard', 'page', 'report']); * Console `/apps/:pkg/` route types that are NOT object records — the * interface surfaces (handled above) plus the `system` settings area. Any other * route type IS the object name (see `AppHeader`'s breadcrumb switch: the - * `else if (routeType)` branch treats it as an object), so it deep-links the - * Data pillar to that object. + * `else if (routeType)` branch treats it as an object), so it deep-links that + * object's designer ({@link appStudioObjectPath}). */ const NON_OBJECT_ROUTE_TYPES = new Set([...INTERFACE_SURFACE_ROUTE_TYPES, 'system']); @@ -333,9 +334,9 @@ const NON_OBJECT_ROUTE_TYPES = new Set([...INTERFACE_SURFACE_ROUTE_TYPES, 'syste * {@link INTERFACE_SURFACE_ROUTE_TYPES}), deep-link straight to THAT item in * Studio's "All metadata" area via {@link appStudioSurfacePath}. When it names an * object record page (the route type IS the object name), deep-link that object - * in the Data pillar via {@link appStudioObjectPath}. Otherwise (bare app root, + * in its designer via {@link appStudioObjectPath}. Otherwise (bare app root, * a `system` route, or an interface list route with no surface name) fall back - * to the package's generic Data tab via {@link appStudioDesignPath}. Returns + * to the package's 概览 Overview via {@link appStudioDesignPath}. Returns * null when the bridge should not render (non-admin / no owning package). * Centralizes the route-type → surface-type mapping so `AppHeader` stays * declarative and the decision is unit-tested here. diff --git a/ui/packages/app-shell/src/utils/editFormLockedByState.test.ts b/ui/packages/app-shell/src/utils/editFormLockedByState.test.ts index 844fa387267..c3f5f3a5a29 100644 --- a/ui/packages/app-shell/src/utils/editFormLockedByState.test.ts +++ b/ui/packages/app-shell/src/utils/editFormLockedByState.test.ts @@ -118,3 +118,54 @@ describe('editFormLockedByState reads the object-level uiReadonlyWhen (#37402)', expect(editFormLockedByState(order({}), { ...CONFIRMED, status: 'draft' })).toBe(false); }); }); + +/** + * #38249 — an object's whole-record hand lock locks its inline lines too, so + * an object that places a child collection greys Edit when the lock holds and + * no field of the child can open a line cell. Without the child's definition, + * or when a child field owns a lock that could open, Edit stays live. + */ +describe('editFormLockedByState with inline lines under the object-level uiReadonlyWhen (#38249)', () => { + const CONFIRMED = { id: 'o1', status: 'confirmed', amount: 1 }; + const order = { + name: 'order', + uiReadonlyWhen: "record.status == 'confirmed'", + fields: { status: { type: 'text' }, amount: { type: 'number' } }, + groupSubforms: [{ childObject: 'order_line', relationshipField: 'order' }], + }; + const line = (qty: Record = {}) => ({ + name: 'order_line', + fields: { order: { type: 'master_detail', reference: 'order' }, qty: { type: 'number', ...qty } }, + }); + const defs = (child: unknown) => (name: string) => (name === 'order_line' ? (child as any) : undefined); + + it('is true when the object lock holds and no child field can open a line cell', () => { + expect(editFormLockedByState(order, CONFIRMED, undefined, defs(line()))).toBe(true); + }); + + it("is false when a child field keeps its cell editable with its own uiReadonlyWhen 'false'", () => { + expect(editFormLockedByState(order, CONFIRMED, undefined, defs(line({ uiReadonlyWhen: 'false' })))).toBe(false); + }); + + it('is true when the child field owns only a static lock', () => { + expect(editFormLockedByState(order, CONFIRMED, undefined, defs(line({ uiReadonly: true })))).toBe(true); + }); + + it('is false while the object predicate does not hold', () => { + expect(editFormLockedByState(order, { ...CONFIRMED, status: 'draft' }, undefined, defs(line()))).toBe(false); + }); + + it('is false when the header is locked only field by field: that leaves the lines open', () => { + const { uiReadonlyWhen: _drop, ...plain } = order; + const byField = { + ...plain, + fields: { status: { type: 'text', readonlyWhen: "record.status == 'confirmed'" }, amount: { type: 'number', readonlyWhen: "record.status == 'confirmed'" } }, + }; + expect(editFormLockedByState(byField, CONFIRMED, undefined, defs(line()))).toBe(false); + }); + + it("fails open without the child object's definition", () => { + expect(editFormLockedByState(order, CONFIRMED)).toBe(false); + expect(editFormLockedByState(order, CONFIRMED, undefined, () => undefined)).toBe(false); + }); +}); diff --git a/ui/packages/app-shell/src/utils/editFormLockedByState.ts b/ui/packages/app-shell/src/utils/editFormLockedByState.ts index e1de5822dff..2928a3063a8 100644 --- a/ui/packages/app-shell/src/utils/editFormLockedByState.ts +++ b/ui/packages/app-shell/src/utils/editFormLockedByState.ts @@ -29,14 +29,20 @@ * so a writable field anywhere keeps Edit live; * - the object's field groups place no inline child collection * (`recordFormSubforms`, objectstack-ai/objectstack#36425), whose rows the - * form still edits whatever the header fields say. + * form still edits whatever the header fields say — unless the object's + * whole-record hand lock (`uiReadonlyWhen`) holds over the record, which + * locks those rows too (objectstack#38249), and no field of any placed + * child object owns a hand lock that could open a line cell + * (`childLinesOpenUnderParentHandLock`). That needs each child object's + * definition, from `childObjectDef`; without it, or for a child it cannot + * answer, Edit stays live. * * A predicate that faults resolves to its fail-open verdict (writable), as in * the form, so a broken rule never greys Edit. */ -import { effectiveUiReadonlyWhen, isExpressionComputedField, resolveFieldRuleState, type ObjectHandLockDef } from '@object-ui/core'; -import { filterSystemFields, isAutoGeneratedFieldType } from '@object-ui/plugin-form/core'; +import { effectiveUiReadonlyWhen, fieldReadOnlyByHand, isExpressionComputedField, resolveFieldRuleState, type ObjectHandLockDef } from '@object-ui/core'; +import { childLinesOpenUnderParentHandLock, filterSystemFields, isAutoGeneratedFieldType } from '@object-ui/plugin-form/core'; import type { FormField } from '@object-ui/types'; import { recordFormSubforms, type ObjectDefinitionForRecordForm } from './recordFormNavigation.js'; @@ -66,9 +72,11 @@ export function editFormLockedByState( objectDef: EditFormLockObject | null | undefined, record: Record | null | undefined, scope?: Record, + childObjectDef?: (name: string) => { fields?: Record } | null | undefined, ): boolean { if (!objectDef || !record) return false; - if (recordFormSubforms(objectDef)) return false; + const subforms = recordFormSubforms(objectDef); + if (subforms && !childObjectDef) return false; const declared = fieldEntries(objectDef.fields); // The fields the form draws: the form's own system-field pass drops the @@ -87,6 +95,24 @@ export function editFormLockedByState( for (const { name } of declared) ruleRecord[name] = null; for (const [k, v] of Object.entries(record)) if (v !== undefined) ruleRecord[k] = v; + if (subforms) { + // objectstack#38249 — the lines are locked only by the object's own + // whole-record hand lock (a field-level lock on the header leaves them + // open), judged by the one hand-lock verdict over the stored row. + const objectLockHolds = fieldReadOnlyByHand({}, ruleRecord, { + object: objectDef, + previous: ruleRecord, + scope, + fieldContext: 'object uiReadonlyWhen', + }); + if (!objectLockHolds) return false; + for (const subform of subforms) { + const childObject = typeof subform?.childObject === 'string' ? subform.childObject : undefined; + const child = childObject ? childObjectDef?.(childObject) : undefined; + if (!child || childLinesOpenUnderParentHandLock(child)) return false; + } + } + let shown = 0; let lockedByRule = 0; for (const { name, def } of entries) { diff --git a/ui/packages/app-shell/src/views/InterfaceListPage.relayCensus-11572.test.ts b/ui/packages/app-shell/src/views/InterfaceListPage.relayCensus-11572.test.ts index 44481258990..d7a9aec40f1 100644 --- a/ui/packages/app-shell/src/views/InterfaceListPage.relayCensus-11572.test.ts +++ b/ui/packages/app-shell/src/views/InterfaceListPage.relayCensus-11572.test.ts @@ -525,8 +525,10 @@ const NOT_RELAYED: Record = { rowHeight: { kind: 'not-inherited', reason: "Row density. Whether users may change density is the page's `userActions.rowHeight`; the starting density is not part of the spec's columns/filter/sort inheritance, and the page config has no density key." }, selection: { kind: 'not-inherited', reason: "Row selection mode, which exists to feed bulk actions. Actions on this surface are the page's `buttons`, so there is no bulk affordance for a selection to drive." }, rowActions: { kind: 'not-inherited', reason: "Per-row action names. Actions on this surface are the page config's `buttons`, object actions the page author chose (ADR-0047); the view's action set is the object page's." }, - bulkActions: { kind: 'not-inherited', reason: "Selection-bar action names. Actions on this surface are the page config's `buttons`; the view's bulk actions are the object page's." }, - bulkActionDefs: { kind: 'not-inherited', reason: "Selection-bar action definitions, the resolved twin of `bulkActions`. Not taken here for the same reason: the page's actions are its `buttons`." }, + // `bulkActions` was answered here (`not-inherited`) until objectstack#36496: + // the spec retires it (an action placed at `selection` is drawn on every grid + // of its object) and `ListView` reads it no longer, so it left the population. + bulkActionDefs: { kind: 'not-inherited', reason: "Selection-bar action definitions. Actions on this surface are the page config's `buttons`; the view's bulk actions are the object page's." }, sharing: { kind: 'not-inherited', reason: "The stored view record's own visibility, shown as a badge. The audience of THIS page is the page's; a badge describing the referenced view's sharing would mislabel it." }, // ── Keys a stored view row cannot carry ───────────────────────────────── diff --git a/ui/packages/app-shell/src/views/ObjectView.bulkWiredHeaderDuplicate-12462.test.tsx b/ui/packages/app-shell/src/views/ObjectView.bulkWiredHeaderDuplicate-12462.test.tsx index 7fac058dd6b..7e5bc7ecfaf 100644 --- a/ui/packages/app-shell/src/views/ObjectView.bulkWiredHeaderDuplicate-12462.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.bulkWiredHeaderDuplicate-12462.test.tsx @@ -12,18 +12,20 @@ * selection bar AND that is record-scoped. * * Measured on HotCRM's Leads list: `create_campaign` ("Add to Campaign", - * `locations: ['list', 'record_row']`) is wired by the `all_leads` - * view's `bulkActions`, so the selection bar already carried it with rows + * `locations: ['list', 'record_row']`) was wired by the `all_leads` + * view's `bulkActions` (since objectstack#36496: placed at `selection`, on + * every grid of the object), so the selection bar already carried it with rows * ticked while the header also drew it at every selection. The selection bar is * the list toolbar in its selection mode, so the action stays at its declared * placement there; what leaves is the header's permanent copy, and with it the * `?runAction=` deep-link arming, which arms only what the header draws. * * The real chain throughout: the real `ObjectView`, the real `ObjectGrid` and - * its selection actions (fed by `resolveBulkActions` from the view's own keys; + * its selection actions (fed by `resolveBulkActions` from the object's + * `selection` actions and the view's own defs; * on the list page they are drawn into the page bar, objectstack#35554), * the real `action:bar`. Every case is a differential on the view's wiring or - * the action's placement, with the same object and the same rows. + * the action's placement, with the same rows. */ import * as React from 'react'; @@ -107,8 +109,9 @@ const REFRESH_SCORES = { }; const LIST_VIEWS = { - // HotCRM's wiring: the default Leads view names the action in `bulkActions`. - all_leads: { name: 'all_leads', label: 'All Leads', type: 'grid', columns: ['name'], bulkActions: ['create_campaign'] }, + // HotCRM's wiring, moved onto the action: mounted with `create_campaign` + // placed at `selection` (objectstack#36496). + all_leads: { name: 'all_leads', label: 'All Leads', type: 'grid', columns: ['name'] }, // The same action, wired through an authored `bulkActionDefs` entry instead. campaign_defs: { name: 'campaign_defs', @@ -119,8 +122,8 @@ const LIST_VIEWS = { }, // CONTROL: a view that does not wire it (HotCRM's `my_leads`). my_leads: { name: 'my_leads', label: 'My Leads', type: 'grid', columns: ['name'], selection: { type: 'multiple' } }, - // CONTROL: an OBJECT-LEVEL action wired as bulk. - scoring: { name: 'scoring', label: 'Scoring', type: 'grid', columns: ['name'], bulkActions: ['refresh_scores'] }, + // CONTROL: an OBJECT-LEVEL action placed at `selection` (mounted so). + scoring: { name: 'scoring', label: 'Scoring', type: 'grid', columns: ['name'] }, }; const LEADS = [ @@ -129,7 +132,8 @@ const LEADS = [ { id: 'lead_3', name: 'Linus' }, ]; -const OBJECTS = [ +/** The Leads object, with the named actions also placed at `selection`. */ +const objectsWith = (placedAtSelection: readonly string[] = []) => [ { name: 'crm_lead', label: 'Lead', @@ -138,7 +142,9 @@ const OBJECTS = [ id: { type: 'text', label: 'Id' }, name: { type: 'text', label: 'Name' }, }, - actions: [CREATE_CAMPAIGN, REFRESH_SCORES], + actions: [CREATE_CAMPAIGN, REFRESH_SCORES].map((action) => + placedAtSelection.includes(action.name) ? { ...action, locations: [...action.locations, 'selection'] } : action, + ), listViews: LIST_VIEWS, }, ]; @@ -150,7 +156,8 @@ afterEach(() => { window.history.replaceState(null, '', '/'); }); -function mountLeads(viewName: keyof typeof LIST_VIEWS) { +function mountLeads(viewName: keyof typeof LIST_VIEWS, placedAtSelection: readonly string[] = []) { + const OBJECTS = objectsWith(placedAtSelection); vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } }))); const i18n = createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false }); @@ -223,8 +230,8 @@ async function tickRows(n: number): Promise { const addToCampaignIn = (el: HTMLElement) => within(el).queryByRole('button', { name: /Add to Campaign/ }); describe('objectui#12462 — a bulk-wired, record-scoped list action leaves the header for the selection bar', () => { - it('the view wires it in `bulkActions`: the plain action stays in the header, Add to Campaign is only in the bar', async () => { - mountLeads('all_leads'); + it('the action is placed at `selection`: the plain action stays in the header, Add to Campaign is only in the bar', async () => { + mountLeads('all_leads', ['create_campaign']); const header = await headerWithToolbar(); await rowBoxes(); @@ -253,7 +260,7 @@ describe('objectui#12462 — a bulk-wired, record-scoped list action leaves the expect((await selectionBar()).names).toContain('create_campaign'); }); - it('CONTROL — a view that does not wire it keeps the header button, and its bar does not carry it', async () => { + it('CONTROL — an object that does not place it keeps the header button, and its bar does not carry it', async () => { mountLeads('my_leads'); const header = await headerWithToolbar(); expect(addToCampaignIn(header)).not.toBeNull(); @@ -264,7 +271,7 @@ describe('objectui#12462 — a bulk-wired, record-scoped list action leaves the }); it('CONTROL — an object-level action wired as bulk keeps its header button (and is in the bar too)', async () => { - mountLeads('scoring'); + mountLeads('scoring', ['refresh_scores']); const header = await headerWithToolbar(); // The record-scoped action is not wired by this view, so it stays as well. expect(addToCampaignIn(header)).not.toBeNull(); @@ -290,7 +297,7 @@ describe('objectui#12462 — the deep link arms only what the header draws', () it('on the view that wires it as bulk, the link is not armed: nothing runs and the link stays in the URL', async () => { linkTo('all_leads'); - mountLeads('all_leads'); + mountLeads('all_leads', ['create_campaign']); // The header has drawn its toolbar and the grid its rows, so an armed link // would have run by now. `hidden: true`: an open param dialog takes the // page out of the accessibility tree, and this wait must not be what fails. diff --git a/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageViewSaves-35974.test.tsx b/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageViewSaves-35974.test.tsx index 3923624e214..843eee170cb 100644 --- a/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageViewSaves-35974.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageViewSaves-35974.test.tsx @@ -273,9 +273,13 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o expect(panelProps.current?.readOnly).toBe(false); }); + // objectstack#37444: the panel mounts the first time it is opened, so the + // cases below that read the open view's panel open it, through that view's + // own row (the door that opens the panel on a given view). it('the panel opens on the shipped view read-only', async () => { mount(SHIPPED.name); await settle(); + await clickConfig(SHIPPED.name); await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(SHIPPED.name)); await waitFor(() => expect(panelProps.current?.readOnly).toBe(true)); }); @@ -283,15 +287,18 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o it('the panel on a shared view saved into the customization package is not read-only', async () => { mount(CUSTOM.name); await settle(); + await clickConfig(CUSTOM.name); await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(CUSTOM.name)); expect(panelProps.current?.readOnly).toBe(false); }); - it('on the reader\'s own view the panel is not read-only and Manage views is unchanged', async () => { + it('on the reader\'s own view the closed panel is not mounted and Manage views is unchanged', async () => { mount(PERSONAL.id); await settle(); - await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(PERSONAL.id)); - expect(panelProps.current?.readOnly).toBe(false); + // objectstack#37444: closed, the panel is not mounted at all (it used to be, + // and this case read the verdict a closed panel was handed). Its own view is + // no row of Manage views, so no row opens the panel on it. + expect(panelProps.current).toBeNull(); // My views are no row of Manage views; the shared rows are judged as ever. expect(screen.queryByTestId(`manage-views-row-${PERSONAL.id}`)).toBeNull(); await waitFor(async () => expect(await rowOffers(SHIPPED.name)).toEqual(FACTORY_OFFERS)); @@ -304,6 +311,8 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o await settle(); await waitFor(() => expect(screen.getByTestId(`manage-views-row-${SHIPPED.name}`)).toBeTruthy()); expect(await rowOffers(SHIPPED.name)).toEqual(OFFERED); + await clickConfig(SHIPPED.name); + await waitFor(() => expect(panelProps.current?.open).toBe(true)); expect(panelProps.current?.readOnly).toBe(false); }); @@ -313,6 +322,8 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o await settle(); await waitFor(() => expect(screen.getByTestId(`manage-views-row-${SHIPPED.name}`)).toBeTruthy()); expect(await rowOffers(SHIPPED.name)).toEqual(OFFERED); + await clickConfig(SHIPPED.name); + await waitFor(() => expect(panelProps.current?.open).toBe(true)); expect(panelProps.current?.readOnly).toBe(false); }); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.relayRungCensus-7559.test.ts b/ui/packages/app-shell/src/views/ObjectView.relayRungCensus-7559.test.ts index c86794230cd..dea4144936a 100644 --- a/ui/packages/app-shell/src/views/ObjectView.relayRungCensus-7559.test.ts +++ b/ui/packages/app-shell/src/views/ObjectView.relayRungCensus-7559.test.ts @@ -476,6 +476,7 @@ const ABSENCES: Record = { performance: { kind: 'unread', reason: 'Retired at spec 17.0.0 with no reader in either repo; declared only as the console\'s own refusal since the 18.2 age-out (objectstack#25767).' }, requiredPermissions: { kind: 'unread', reason: 'The ADR-0066 audience gate `@objectstack/spec` 18 adds to a list view (objectui#12030). The SERVER enforces it before the view is served: a user who lacks the capabilities is never listed the view and is refused it by name, so nothing on the ListView path has a value to consume.' }, filterableFields: { kind: 'unread', reason: 'Retired by objectstack#24640 (maintainer ruling C, pulled into 18.0): no per-view Filter-panel whitelist replaces it. objectui#13118 removed its one reader, the whitelist branch of `ListView`\'s Filter-panel field list, and this relay\'s rung with it. Present only as the spec import that carries its tombstone from the pin bump that takes the retirement.' }, + bulkActions: { kind: 'unread', reason: "Retired by objectstack#36496 (protocol 19): an action that acts on many records is placed at `selection` and drawn on every grid view's selection bar in the order the object's `actionLayout.selection` gives, so a view carries no list. `ListView` reads it no longer and this relay's `bulkActions` rung went with it; the spec and `ListViewSchema` carry the tombstone. A view's own `bulkActionDefs` stay relayed." }, options: { kind: 'unread', reason: "Retired by objectstack#25923: the list view's `options` bag is the spec list overlay's tombstone, taken by reference, so every door refuses it by name. A stored bag is folded onto the top-level blocks by the server before the row is served, and objectstack#25923 removed every `ListView` read of it along with this relay's `options` rung." }, pageName: { kind: 'unread', reason: 'Page-context key with no reader on the list path.' }, tabs: { kind: 'unread', reason: "Spec view-tab list. ListView has no reader — the object page's view switcher is the page title's (`objectViewTitleSwitcher`), driven by `buildViewTabs`, and the `tabs` readers in the tree belong to `plugin-detail`'s DetailView." }, diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index ac9e9bc4207..b8c2f1f58e5 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -43,8 +43,9 @@ import { MetadataPanel, useMetadataInspector } from './MetadataInspector.js'; // objectstack#33293: the view config panel loads with the first list, not with // the console. Statically, it held the view-variant inspector, `SchemaForm` and // the Studio form widgets in the EAGER closure, so a dashboard route downloaded -// them too. It is drawn on every list (closed, it draws nothing), so its chunk -// is fetched as the list mounts, before any admin can open it. +// them too. objectstack#37444: it mounts the first time it is opened, not with +// every list, so the list's first screen no longer fetches it (see +// `useOpenedOnce` below). const ViewConfigPanel = lazy(() => import('./ViewConfigPanel.js').then((m) => ({ default: m.ViewConfigPanel })), ); @@ -53,9 +54,12 @@ import { dropPublishedViewList } from './metadata-admin/viewListDrop.js'; // objectstack#33582: the create-view dialog loads with the first list, as the // view config panel above does. Statically, it held the dataset catalogue and, // through it, the Studio `en` string namespace in the EAGER closure. +// objectstack#37444: like the panel, it mounts on its first opening. const CreateViewDialog = lazy(() => import('./CreateViewDialog.js').then((m) => ({ default: m.CreateViewDialog })), ); + +import { useOpenedOnce } from '../hooks/useOpenedOnce.js'; import { usePreviewDrafts, } from '../preview/PreviewModeContext.js'; @@ -308,6 +312,8 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co // refuses with 403. `isAdmin` alone still gates what only reads. const canAuthorMetadata = useCanAuthorMetadata(); const canManageViews = mayManageViews(isAdmin, canAuthorMetadata); + const viewConfigPanelMounted = useOpenedOnce(showViewConfigPanel && canManageViews); + const createViewDialogMounted = useOpenedOnce(showCreateViewDialog && canManageViews); // Get Object Definition. The outer ObjectView wrapper already guards the // missing-object case, so this always resolves while this component is @@ -1710,7 +1716,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co showViewConfigPanel && canManageViews ? 'max-w-[280px] opacity-100' : 'max-w-0 opacity-0' }`} > - + {viewConfigPanelMounted && { setShowViewConfigPanel(false); setViewConfigPanelMode('edit'); }} @@ -1725,9 +1731,9 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co onAfterChange={handleDraftBarChange} readOnly={viewConfigPanelReadOnly} /> - + }
- + {createViewDialogMounted && handleViewCreate(cfg)} /> - + } { if (!open) setPersonalViewDialog(null); }} diff --git a/ui/packages/app-shell/src/views/ObjectView.viewConfigSaveWiring-10210.test.tsx b/ui/packages/app-shell/src/views/ObjectView.viewConfigSaveWiring-10210.test.tsx index de66d7dfa6f..29bb97dec32 100644 --- a/ui/packages/app-shell/src/views/ObjectView.viewConfigSaveWiring-10210.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.viewConfigSaveWiring-10210.test.tsx @@ -21,7 +21,7 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, cleanup, act, screen, fireEvent } from '@testing-library/react'; +import { render, cleanup, act, screen, fireEvent, waitFor } from '@testing-library/react'; import { MemoryRouter, Routes, Route } from 'react-router-dom'; import { ViewMetadataSchema } from '@objectstack/spec/ui'; @@ -116,6 +116,27 @@ vi.mock('./ViewConfigPanel', () => { // The view's source reaches a dynamic import of `@objectstack/lint`: pay its // load at collection, never inside a case's clocked window (`check:test-source-alias`). +// objectstack#37444: the list's Settings view action, drawn beside the real +// plugin view (whose own view switcher the console hides), so a case can open +// the panel the way the action does. +vi.mock('@object-ui/plugin-view', async (importOriginal) => { + const actual = await importOriginal(); + const Real = actual.ObjectView; + return { + ...actual, + ObjectView: (props: React.ComponentProps) => ( + <> + + )} +
+ )} + + {passes && ( +
+

{t('engine.looseMove.confirm.dryRunNote', locale)}

+

{t('engine.looseMove.confirm.undoNote', locale)}

+
+ )} + + + + {step.kind === 'failed' ? ( + + ) : ( + + )} + + + + ); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx index d1b4e25de11..e0e25e348f3 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx @@ -58,6 +58,12 @@ export interface PackageAskRequest { preselect?: string | null; /** The type being created, as the reader reads it; names the question. */ typeLabel?: string; + /** + * The question and its explanation, for an ask that is not a create + * (objectstack#38150: where loose items move to). Absent, the create's own. + */ + title?: string; + description?: string; } /** The packages the ask offers: the server's writable verdict, kernel packages out, by name. */ @@ -73,6 +79,8 @@ export function PackageCreateAskDialog({ open, preselect, typeLabel, + title: askTitle, + description: askDescription, onAnswer, readPackages = fetchPackages, }: PackageAskRequest & { @@ -117,7 +125,9 @@ export function PackageCreateAskDialog({ }; const options = list.status === 'read' ? list.options : []; - const title = typeLabel + const title = askTitle + ? askTitle + : typeLabel ? tFormat('engine.packageAsk.titleNamed', locale, { type: typeLabel }) : t('engine.packageAsk.title', locale); @@ -132,7 +142,7 @@ export function PackageCreateAskDialog({ {title} - {t('engine.packageAsk.description', locale)} + {askDescription ?? t('engine.packageAsk.description', locale)} {list.status === 'loading' && (

@@ -244,6 +254,8 @@ export function usePackageCreateAsk(): { open={!!pending} preselect={pending?.preselect ?? null} typeLabel={pending?.typeLabel} + title={pending?.title} + description={pending?.description} onAnswer={onAnswer} /> ); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx index 51872f0bdc9..bf9fa2e2d9c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx @@ -74,7 +74,7 @@ import { CreatePackageDialog } from './PackagesPage'; import { useMetadataClient } from './useMetadata'; import { t, useMetadataLocale } from './i18n'; import { newAppStep } from '../studio-design/newAppDoor'; -import { studioHomePath } from '../studio-design/studioAddress'; +import { studioPackageOverviewPath } from '../studio-design/studioOverviewAddress'; import { StudioDesignSurface } from '../studio-design/StudioDesignSurface'; import { StudioPillarRedirect } from '../studio-design/StudioPillarRedirect'; @@ -189,7 +189,7 @@ function NewAppHost() { open={open} onOpenChange={setOpen} newApp={step} - onSaved={(r) => navigate(studioHomePath(r.id))} + onSaved={(r) => navigate(studioPackageOverviewPath(r.id))} /> ); @@ -306,7 +306,7 @@ describe('PackageFormDialog with a new-app step: one confirm creates the package // (`CreatePackageDialog`) offers 「同时创建应用」, ticked by default. // --------------------------------------------------------------------------- -/** `CreatePackageDialog` as Setup → Packages mounts it: Studio on the new package after create. */ +/** `CreatePackageDialog` as Setup → Packages mounts it: Studio on the new package's 概览 Overview after create (objectstack#38392). */ function CreatePackageHost() { const navigate = useNavigate(); const [open, setOpen] = React.useState(false); @@ -315,7 +315,7 @@ function CreatePackageHost() { - navigate(studioHomePath(id))} /> + navigate(studioPackageOverviewPath(id))} /> ); } diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.adoptLooseItems-13339.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.adoptLooseItems-13339.test.tsx deleted file mode 100644 index 8f273cd1c69..00000000000 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.adoptLooseItems-13339.test.tsx +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#13339 — the package sheet's *Adopt loose items*, and the sheet's - * one message line. - * - * Before: *Adopt loose items* asked with the browser's native - * `window.confirm`, then said "Loose items adopted into this base." whatever - * moved, so an adoption that found nothing read as one that did. And the - * message line kept the previous action's answer: a Revert refusal still - * stood under the Duplicate form opened after it. - * - * After, pinned here through the real `PackageDetailSheet`: - * - Adopt asks in an in-app dialog, never `window.confirm`; its Cancel sends - * nothing, and its confirm sends one `POST …/adopt-orphans`. - * - The answer reports the server's own `reassignedCount` - * (`ReassignOrphanedMetadataResponse`), 0 included, and a 0 (whose own - * `success` is false) is reported as a count, not as a failure. - * - Starting any action on the sheet clears the previous action's message, - * including the actions that first open a dialog or a form. - * - * Every request is recorded by the fetch stub, so "sends nothing" is read off - * the wire, not off the UI. - */ - -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; - -import { PackageDetailSheet, type InstalledPackageRow } from './PackagesPage'; -// Loaded at import so their first load is not paid inside a test's clocked window. -import '@objectstack/formula'; -import '@objectstack/lint'; - -const PKG_ID = 'com.acme.crm'; -const PKG_NAME = 'Acme CRM'; -const PKG: InstalledPackageRow = { - manifest: { id: PKG_ID, name: PKG_NAME, version: '1.0.0', type: 'app' }, - enabled: true, - status: 'installed', - source: 'authored', - writable: true, - // A writable base is disableable too (objectstack#28318): the sheet offers - // Disable from this verdict alone. - disableable: true, -}; -const DRAFTS = [ - { type: 'object', name: 'acme_lead' }, - { type: 'view', name: 'acme_lead_list' }, -]; -const REVERT_REFUSAL = 'Nothing to revert on this package'; - -type Call = { url: string; method: string }; -let calls: Call[]; -/** What `POST /adopt-orphans` answers; a test may replace it. */ -let adoptAnswer: unknown; -let confirmSpy: ReturnType; -let savedConfirm: PropertyDescriptor | undefined; - -function respond(body: unknown, status = 200) { - const text = JSON.stringify(body); - return { - ok: status >= 200 && status < 300, - status, - headers: new Headers(), - text: async () => text, - json: async () => JSON.parse(text), - } as unknown as Response; -} - -/** The adopt door's answer: the envelope around `ReassignOrphanedMetadataResponse`. */ -function adopted(items: Array<{ type: string; name: string }>) { - return { - success: true, - data: { - // The producer's own verdict: true exactly when something moved. - success: items.length > 0, - reassignedCount: items.length, - reassigned: items, - targetPackageId: PKG_ID, - }, - }; -} - -beforeEach(() => { - calls = []; - adoptAnswer = adopted([ - { type: 'object', name: 'loose_a' }, - { type: 'view', name: 'loose_b' }, - { type: 'flow', name: 'loose_c' }, - ]); - vi.stubGlobal( - 'fetch', - vi.fn(async (input: string, init: RequestInit = {}) => { - const method = (init.method ?? 'GET').toUpperCase(); - calls.push({ url: input, method }); - if (input.startsWith('/api/v1/meta/_drafts')) { - return respond({ success: true, data: { drafts: DRAFTS } }); - } - if (input.endsWith('/adopt-orphans')) return respond(adoptAnswer); - if (input.endsWith('/revert')) { - return respond({ success: false, error: { code: 'NOTHING_TO_REVERT', message: REVERT_REFUSAL } }, 409); - } - return respond({ success: true, data: {} }); - }), - ); - // happy-dom implements no `confirm`; a spy observes (and answers OK to) a - // native call, so a regression would send the POST and still be caught. - savedConfirm = Object.getOwnPropertyDescriptor(window, 'confirm'); - confirmSpy = vi.fn(() => true); - Object.defineProperty(window, 'confirm', { configurable: true, writable: true, value: confirmSpy }); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); - if (savedConfirm) Object.defineProperty(window, 'confirm', savedConfirm); - else delete (window as unknown as Record).confirm; -}); - -function renderSheet() { - const onChanged = vi.fn(); - render( - - - , - ); - return { onChanged }; -} - -const adoptPosts = () => calls.filter((c) => c.method === 'POST' && c.url.endsWith('/adopt-orphans')); - -/** Let any handler the click scheduled run before reading the wire. */ -async function settle() { - await act(async () => { - await new Promise((r) => setTimeout(r, 0)); - }); -} - -async function openAdoptDialog() { - fireEvent.click(await screen.findByRole('button', { name: 'Adopt loose items' })); - return screen.findByTestId('pkg-detail-adopt-dialog'); -} - -async function adoptAndConfirm() { - const dialog = await openAdoptDialog(); - fireEvent.click(within(dialog).getByTestId('pkg-detail-adopt-confirm')); - await settle(); -} - -describe('PackageDetailSheet — Adopt loose items asks in-app (objectui#13339)', () => { - it('opens an in-app dialog naming the package, never window.confirm, and sends nothing yet', async () => { - renderSheet(); - const dialog = await openAdoptDialog(); - expect(within(dialog).getByText(`Adopt loose items into "${PKG_NAME}"?`)).toBeInTheDocument(); - await settle(); - expect(confirmSpy).not.toHaveBeenCalled(); - expect(adoptPosts()).toEqual([]); - }); - - it('its Cancel sends no request and reports nothing', async () => { - const { onChanged } = renderSheet(); - const dialog = await openAdoptDialog(); - fireEvent.click(within(dialog).getByTestId('pkg-detail-adopt-cancel')); - await waitFor(() => expect(screen.queryByTestId('pkg-detail-adopt-dialog')).toBeNull()); - await settle(); - expect(adoptPosts()).toEqual([]); - expect(onChanged).not.toHaveBeenCalled(); - expect(screen.queryByText(/adopted into this base/)).toBeNull(); - }); - - it('its confirm sends one POST and closes the dialog', async () => { - const { onChanged } = renderSheet(); - await adoptAndConfirm(); - expect(adoptPosts()).toHaveLength(1); - expect(adoptPosts()[0].url).toBe(`/api/v1/packages/${encodeURIComponent(PKG_ID)}/adopt-orphans`); - await waitFor(() => expect(screen.queryByTestId('pkg-detail-adopt-dialog')).toBeNull()); - expect(onChanged).toHaveBeenCalledTimes(1); - expect(confirmSpy).not.toHaveBeenCalled(); - }); -}); - -describe('PackageDetailSheet — Adopt reports the server count (objectui#13339)', () => { - it('reports the answer’s reassignedCount', async () => { - renderSheet(); - await adoptAndConfirm(); - expect(await screen.findByText('3 items adopted into this base.')).toBeInTheDocument(); - }); - - it('reports 0 when nothing moved: a count, not "adopted" and not a failure', async () => { - adoptAnswer = adopted([]); - renderSheet(); - await adoptAndConfirm(); - expect(await screen.findByText('0 items adopted into this base.')).toBeInTheDocument(); - expect(screen.queryByText('Loose items adopted into this base.')).toBeNull(); - }); - - it('says "1 item" for one', async () => { - adoptAnswer = adopted([{ type: 'object', name: 'loose_a' }]); - renderSheet(); - await adoptAndConfirm(); - expect(await screen.findByText('1 item adopted into this base.')).toBeInTheDocument(); - }); -}); - -describe('PackageDetailSheet — starting an action clears the previous message (objectui#13339)', () => { - async function showRevertRefusal() { - fireEvent.click(await screen.findByRole('button', { name: 'Revert' })); - expect(await screen.findByText(REVERT_REFUSAL, { exact: false })).toBeInTheDocument(); - } - - // Each opens a dialog or a form before anything runs: the press that opens - // it is where the action starts. - it.each([ - ['Duplicate'], - ['Delete package'], - ['Disable'], - ['Adopt loose items'], - [`Discard changes (${DRAFTS.length})`], - ['View info'], - ['Edit'], - ])('a Revert refusal is gone once %s is pressed', async (label) => { - renderSheet(); - await showRevertRefusal(); - fireEvent.click(await screen.findByRole('button', { name: label })); - await settle(); - expect(screen.queryByText(REVERT_REFUSAL, { exact: false })).toBeNull(); - }); - - it('an Adopt count is gone once Duplicate is pressed', async () => { - renderSheet(); - await adoptAndConfirm(); - expect(await screen.findByText('3 items adopted into this base.')).toBeInTheDocument(); - fireEvent.click(await screen.findByRole('button', { name: 'Duplicate' })); - await settle(); - expect(screen.queryByText('3 items adopted into this base.')).toBeNull(); - expect(screen.getByTestId('pkg-detail-dup-form')).toBeInTheDocument(); - }); -}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx index f770ea46cde..f36b41a9be4 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx @@ -656,7 +656,6 @@ describe('Setup → Packages: the administration face (objectstack#36834)', () = 'engine.packages.detail.revert', 'engine.packages.detail.export', 'engine.packages.detail.duplicate', - 'engine.packages.detail.adoptOrphans', ]; it('the detail sheet offers View info, Disable and Delete, and links an authored package to Studio', async () => { @@ -675,7 +674,7 @@ describe('Setup → Packages: the administration face (objectstack#36834)', () = // are authoring: not on this face, though the package has a draft. expect(within(sheet).queryByText(row('engine.packages.detail.pendingChanges'))).toBeNull(); expect(within(sheet).queryByText(row('engine.packages.detail.browseMetadata'))).toBeNull(); - expect(within(sheet).getByTestId('pkg-detail-open-in-studio')).toHaveAttribute('href', '/studio/app.b2r4/data'); + expect(within(sheet).getByTestId('pkg-detail-open-in-studio')).toHaveAttribute('href', '/studio/app.b2r4/overview'); }); it('CONTROL: the same package on the development surface keeps every authoring action', async () => { @@ -737,7 +736,7 @@ describe('Setup → Packages: the administration face (objectstack#36834)', () = fireEvent.click(screen.getByRole('button', { name: row('engine.packages.new') })); fireEvent.click(await screen.findByTestId('stub-create-save')); - expect(await screen.findByTestId('where')).toHaveTextContent('/studio/app.fresh/data'); + expect(await screen.findByTestId('where')).toHaveTextContent('/studio/app.fresh/overview'); }); it('CONTROL: New Package on the development surface stays on the list', async () => { @@ -786,7 +785,7 @@ describe('Setup → Packages: the new-package deep link (objectstack#36908)', () // The create lands in Studio on the new package, as New Package does. fireEvent.click(screen.getByTestId('stub-create-save')); - expect(await screen.findByTestId('where')).toHaveTextContent('/studio/app.fresh/data'); + expect(await screen.findByTestId('where')).toHaveTextContent('/studio/app.fresh/overview'); }); it('CONTROL: the face without the param opens no dialog', async () => { @@ -821,7 +820,7 @@ describe('Setup → Packages: New Package offers 「同时创建应用」 (objec const save = await screen.findByTestId('stub-create-save'); expect(save).toHaveAttribute('data-new-app', 'step'); fireEvent.click(save); - expect(await screen.findByTestId('where')).toHaveTextContent('/studio/app.fresh/data'); + expect(await screen.findByTestId('where')).toHaveTextContent('/studio/app.fresh/overview'); }); it('the `?new=package` door opens the dialog with the app step', async () => { @@ -882,7 +881,7 @@ describe('Setup → Packages: a read-only base’s customizations in its detail await waitFor(() => expect(within(section).getByTestId('pkg-detail-customizations-summary')).toHaveTextContent('0 customized, 1 rearranged, 0 switched off'), ); - expect(within(section).getByTestId('pkg-detail-customize')).toHaveAttribute('href', '/studio/com.acme.code/data'); + expect(within(section).getByTestId('pkg-detail-customize')).toHaveAttribute('href', '/studio/com.acme.code/overview'); }); it('an authored package’s detail draws no customizations section: it is changed in place', async () => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.moduleDisable-28118.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.moduleDisable-28118.test.tsx index 0d7f13204e7..fa0f4911311 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.moduleDisable-28118.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.moduleDisable-28118.test.tsx @@ -50,7 +50,7 @@ const ZH = await loadStudioCatalogue('zh'); const label = (key: string) => t(`engine.packages.detail.${key}`, 'en'); /** The write actions a writable base offers besides Disable. */ -const OTHER_WRITES = ['edit', 'publish', 'revert', 'duplicate', 'adoptOrphans', 'deletePackage']; +const OTHER_WRITES = ['edit', 'publish', 'revert', 'duplicate', 'deletePackage']; const MODULE_ID = 'com.acme.suite.orders'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.readOnlyActions-13157.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.readOnlyActions-13157.test.tsx index 17d6c303515..03d76eda282 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.readOnlyActions-13157.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.readOnlyActions-13157.test.tsx @@ -13,8 +13,7 @@ * * Pinned here through the real `PackageDetailSheet`: * (a) a read-only package (`writable: false`, whatever its scope) offers - * none of Edit, Publish, Revert, Disable, Duplicate, Adopt loose items or - * Delete app; the reads (View info, Export) stay; + * none of Edit, Publish, Revert, Disable, Duplicate or Delete app; the reads (View info, Export) stay; * (b) CONTROL: a writable package offers every one of them, as before; * (c) Duplicate is one of the refused writes: the server answers a read-only * source `422 DUPLICATE_SOURCE_NOT_A_BASE` (its source must be a @@ -31,11 +30,13 @@ import { MemoryRouter } from 'react-router-dom'; import { PackageDetailSheet, type InstalledPackageRow } from './PackagesPage'; import { t } from './i18n'; +// Pay the source's dynamic `@objectstack/lint` load during collection, never inside a clocked case. +import '@objectstack/lint'; const label = (key: string) => t(`engine.packages.detail.${key}`, 'en'); /** Every write action the sheet offers on a writable package. */ -const WRITES = ['edit', 'publish', 'revert', 'disable', 'duplicate', 'adoptOrphans', 'deletePackage']; +const WRITES = ['edit', 'publish', 'revert', 'disable', 'duplicate', 'deletePackage']; /** The read actions, offered on every package. */ const READS = ['viewInfo', 'export']; diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx index 6f52037de24..579e3e30bdc 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx @@ -24,11 +24,10 @@ * Source filter, and in the detail sheet only enable / disable and delete * (with its keep-data choice); New Package lands in Studio on the new * package, and Import sits beside it (objectstack#37139). Publish, revert, - * discard drafts, adopt loose items and manifest edit stay on the - * development surface. + * discard drafts and manifest edit stay on the development surface. * * objectstack#37139 — the development face's whole-package actions (Edit, - * Export, Duplicate, Revert, Adopt loose items) are shared with Studio's 「⋯」 + * Export, Duplicate, Revert) are shared with Studio's 「⋯」 * package menu through `packageActions.tsx`. */ @@ -48,7 +47,6 @@ import { AlertTriangle, Trash2, Copy, - Inbox, Pencil, Eye, MoreHorizontal, @@ -101,12 +99,9 @@ import { useMetadataClient } from './useMetadata.js'; import { newAppStep } from '../studio-design/newAppDoor.js'; import { PackageFormDialog } from './PackageFormDialog.js'; import { - AdoptLooseItemsDialog, DuplicatePackageForm, EditPackageDialog, PACKAGES_API, - adoptLooseItems, - adoptedText, exportPackageFile, packagesApiJson, revertPackage, @@ -138,7 +133,8 @@ import { useProtocolCheckSkippedText } from '../../console/marketplace/protocolC import { ProtocolCheckSkippedNote } from '../../console/marketplace/ProtocolCheckSkippedNote.js'; import type { InstalledPackageAtEitherStage } from '@objectstack/spec/api-assembled'; import type { PackagePublishResult } from '@objectstack/spec/system'; -import { studioHomePath } from '../studio-design/studioAddress.js'; +import { studioPackageOverviewPath } from '../studio-design/studioOverviewAddress.js'; +import { LooseItemsBanner } from './LooseItemsBanner.js'; import { PackageCustomizationsPanel } from '../studio-design/PackageCustomizationsPanel.js'; import { isCustomizationPackage } from '@objectstack/spec/kernel'; import { @@ -590,13 +586,6 @@ function InstalledAppUpdateCell({ rowId, read }: { rowId: string; read: UpdateRe ); } -/** - * A package's Studio address: the builder on the package's Data pillar. The - * administration face's create lands here, and its "Open in Studio" link - * points here (objectstack#36834). - */ -const studioPackagePath = (packageId: string) => studioHomePath(packageId); - /* -------------------------------------------------------------------------- */ /* Create-package dialog */ /* -------------------------------------------------------------------------- */ @@ -685,8 +674,8 @@ export function PackageDetailSheet({ * objectstack#36834 — which face of the Packages page opened the sheet. The * `admin` face (Setup → Packages) offers the administration actions only: * View info, Disable / Enable and Delete, plus "Open in Studio" on an - * authored package. Edit, Publish, Revert, Export, Duplicate, Adopt loose - * items and the pending changes' Publish / Discard stay on the development + * authored package. Edit, Publish, Revert, Export, Duplicate and the + * pending changes' Publish / Discard stay on the development * face. On the administration face a read-only base also draws what this * deployment changed on it (objectstack#36908). */ @@ -726,9 +715,7 @@ export function PackageDetailSheet({ // objectui#11784 — the confirmations this sheet asks are in-app, never // `window.confirm` / `window.prompt`: those are blocked or auto-answered in // an embedded frame, and the old delete chained two confirms where the - // second one's Cancel still deleted. objectui#13339 — Adopt loose items is - // the fourth. - const [adoptOpen, setAdoptOpen] = React.useState(false); + // second one's Cancel still deleted. const [deleteOpen, setDeleteOpen] = React.useState(false); // Disable takes a package's metadata out of service for every user, so it // is confirmed first; Enable restores and runs at once. @@ -751,7 +738,6 @@ export function PackageDetailSheet({ React.useEffect(() => { setMsg(null); setBusy(null); - setAdoptOpen(false); setDeleteOpen(false); setDiscardOpen(false); setDupOpen(false); @@ -825,8 +811,7 @@ export function PackageDetailSheet({ // `true` is never writable). On a read-only package the server refuses // Edit, Publish, Revert and Delete (`WRITABLE_PACKAGE_REQUIRED`) and // Duplicate (`DUPLICATE_SOURCE_NOT_A_BASE`: its source must be a writable - // base); Adopt orphans would bind loose items into a package the org cannot - // author. So none of them is offered there. The reads stay. Disable has its + // base). So none of them is offered there. The reads stay. Disable has its // own served verdict, `disableable`, below. const writable = pkg.writable === true; // objectstack#28118 — Disable is offered from the disable door's own served @@ -847,7 +832,7 @@ export function PackageDetailSheet({ // objectui#13339 — the sheet's one message line answers the action the // author started LAST. An action that runs straight away clears it as it - // starts (`run`, and the delete / duplicate / adopt calls); one that first + // starts (`run`, and the delete / duplicate calls); one that first // opens a dialog or a form clears it here, at the press that opens it, so // a previous action's answer (a Revert refusal, say) never stands under // the next action's form as if it were that action's. @@ -1105,31 +1090,6 @@ export function PackageDetailSheet({ } }; - // ADR-0070 D5 — adopt every package-less (loose) item in this env INTO this - // base. The *Adopt loose items* button opens an in-app confirmation - // (objectui#13339); only its confirm runs this, and its Cancel sends nothing. - // - // The answer reports the server's own count, `reassignedCount` - // (`ReassignOrphanedMetadataResponse`), 0 included: the sheet used to say - // "Loose items adopted" whatever moved, so an adoption that found nothing - // read as one that did. The answer's own `success` is false exactly when - // nothing moved (`reassigned.length > 0`); on this door that is a count of - // 0, not a failure, so the count is what the author is told. - const adoptOrphans = async () => { - setAdoptOpen(false); - setBusy('adopt'); - setMsg(null); - try { - const count = await adoptLooseItems(id); - setMsg({ kind: 'ok', text: adoptedText(count, locale) }); - onChanged(); - } catch (e: any) { - setMsg({ kind: 'err', text: e?.message ?? 'Adopt failed' }); - } finally { - setBusy(null); - } - }; - const toggleEnable = () => run( 'toggle', @@ -1174,7 +1134,7 @@ export function PackageDetailSheet({ <> onOpenChange(false)} data-testid="pkg-detail-open-in-studio" @@ -1360,12 +1320,6 @@ export function PackageDetailSheet({ {busy === 'duplicate' ? t('engine.packages.detail.duplicating', locale) : t('engine.packages.detail.duplicate', locale)} )} - {authoring && writable && ( - - )} {writable && ( ) : null; - // objectstack#36903 — a host that says what its empty list means (the - // package-less scope, whose list is its source filter's narrowing of the - // environment's rows) reads an unsearched, empty list as empty, not as a - // search with no match. + // objectstack#36903 — a host that says what its empty list means reads an + // unsearched, empty list as empty, not as a search with no match. const hintedEmpty = !!host?.emptyListHint && !query.trim() && filtered.length === 0; // The list context every row link carries to its detail (decision 10). const listContext = listContextQuery(listState); // Compute source + invalid counts for filter / header stats. const sourceCounts = React.useMemo(() => { - const c = { all: scopedItems.length, artifact: 0, runtime: 0 }; + const c = { all: scopedItems.length, artifact: 0, runtime: 0, loose: 0 }; for (const r of scopedItems) { c[sourceOf(r)]++; + if (isLooseRow(r.item)) c.loose++; } return c; }, [scopedItems, sourceOf]); @@ -917,6 +941,61 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string }; const refresh = () => setRefreshKey((k) => k + 1); + + // objectstack#38150 — under "Loose", a person who may author selects rows + // and moves them: the picker (#38149's ask, nothing pre-selected), then the + // confirm step, which reads the door's dry run (`LooseMoveDialog`). + const looseSelecting = looseOffered && sourceFilter === 'loose' && canAuthor && !walled; + const looseItemOf = React.useCallback( + (row: ItemRow): LooseItem => { + const member = bundleMemberOf(row.item, config.bundleMemberField); + return { type, name: String(row.item[primaryKey] ?? ''), ...(member ? { member } : {}) }; + }, + [type, primaryKey, config.bundleMemberField], + ); + // A selection belongs to one type's loose list; leaving it drops it. + React.useEffect(() => { + setLooseSelected(new Map()); + }, [type, looseSelecting]); + const looseRows = looseSelecting ? filtered : []; + const looseAllSelected = looseRows.length > 0 && looseRows.every((row) => looseSelected.has(looseItemKey(looseItemOf(row)))); + const looseSomeSelected = !looseAllSelected && looseRows.some((row) => looseSelected.has(looseItemKey(looseItemOf(row)))); + const toggleLoose = (item: LooseItem, on: boolean) => { + setLooseSelected((prev) => { + const next = new Map(prev); + if (on) next.set(looseItemKey(item), item); + else next.delete(looseItemKey(item)); + return next; + }); + }; + const toggleAllLoose = (on: boolean) => { + setLooseSelected((prev) => { + const next = new Map(prev); + for (const row of looseRows) { + const item = looseItemOf(row); + if (on) next.set(looseItemKey(item), item); + else next.delete(looseItemKey(item)); + } + return next; + }); + }; + const startLooseMove = async () => { + const items = [...looseSelected.values()]; + if (items.length === 0) return; + const target = await askPackage({ + preselect: null, + title: tFormat('engine.looseMove.pick.title', locale, { count: items.length }), + description: t('engine.looseMove.pick.description', locale), + }); + if (!target) return; + // The confirm names the package as the ask listed it (the list read is the + // ask's own, already held); its id when the name cannot be read. + const label = await fetchPackages().then( + (entries) => entries.find((p) => p.id === target)?.name ?? target, + () => target, + ); + setLooseMove({ target: { id: target, label }, items }); + }; // objectstack#36896 — × / Back from a detail lands where the list was: the // position is kept per list address and restored once the rows are drawn. const scrollAnchorRef = useListScrollRestore( @@ -1020,12 +1099,14 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string // its package, lock and diagnostics are looked up here, never carried on // the grid's row. const rowInfos = new Map(); + // objectstack#38150 — under "Loose" the table leads with the select column. + const leadColumns = looseSelecting ? 1 : 0; const gridRowsAll = filtered.map((row, i) => { const info = metadataRowInfo(row, i); rowInfos.set(info.id, info); const values: Record = { id: info.id }; shownColumns.forEach((c, ci) => { - values[metadataGridField(ci)] = gridValue(valueAtPath(row.item, c.key)); + values[metadataGridField(ci + leadColumns)] = gridValue(valueAtPath(row.item, c.key)); }); return values; }); @@ -1107,6 +1188,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string return seen; }; const gridColumns: MetadataGridColumn[] = [ + ...(looseSelecting ? [{ key: SELECT_COLUMN, label: t('engine.looseMove.col.select', locale), width: '64px' }] : []), ...shownColumns.map((c, ci) => ({ key: c.key, // The Studio list heads its label-first column by the identity it @@ -1192,6 +1274,11 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string pair: customizations.index.pairId, }); } + // objectstack#38150 — a row its writable package makes "new" was authored + // here: its badge is not explained as shipped by a code package. + if (row.source === 'artifact' && isWritablePackageItem(row.item, writablePackages)) { + return `${t('engine.list.source.runtimeDesc', locale)} (${String(row.item._packageId)})`; + } return provenanceDesc(row); }; const rowLock = (row: ItemRow): React.ReactNode => { @@ -1332,8 +1419,25 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string ); }; const cellDraws: Record React.ReactNode> = {}; + if (looseSelecting) cellDraws[metadataGridField(0)] = (_value, rec) => { + const info = rowInfoOf(rec); + if (!info) return null; + const item = looseItemOf(info.row); + return ( + + toggleLoose(item, on === true)} + // The row's click opens the item; the box only selects it. + onClick={(e) => e.stopPropagation()} + aria-label={tFormat('engine.looseMove.select', locale, { name: info.name })} + data-testid={`loose-select-${info.name}`} + /> + + ); + }; shownColumns.forEach((c, ci) => { - cellDraws[metadataGridField(ci)] = (_value, rec) => { + cellDraws[metadataGridField(ci + leadColumns)] = (_value, rec) => { const info = rowInfoOf(rec); if (!info) return null; if (ci === 0) return firstCell(info, c); @@ -1490,6 +1594,11 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string {tFormat('engine.list.sourceFilter.system', locale, { count: sourceCounts.artifact })} + {looseOffered && ( + + {tFormat('engine.list.sourceFilter.loose', locale, { count: sourceCounts.loose })} + + )}

@@ -1573,6 +1682,11 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string {t('engine.list.allSources', locale)} ({sourceCounts.all}) {t('engine.list.source.artifact', locale)} ({sourceCounts.artifact}) {t('engine.list.source.runtime', locale)} ({sourceCounts.runtime}) + {looseOffered && ( + + {tFormat('engine.list.sourceFilter.loose', locale, { count: sourceCounts.loose })} + + )} {activation && ( @@ -1771,6 +1885,51 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string )} )} + {/* objectstack#38150 — the "Loose" list's selection bar: select every + row the filter shows, and move the selection into a package. */} + {!loading && looseSelecting && filtered.length > 0 && ( +
+ + + {tFormat('engine.looseMove.selected', locale, { count: looseSelected.size })} + + +
+ )} + setLooseMove(null)} + onMoved={(answer) => { + // The answer names the package as the confirm's title did: the + // label the dialog was opened on, the id only when no name was read. + const pkgLabel = looseMove?.target.label ?? answer.targetPackageId; + setLooseMove(null); + setLooseSelected(new Map()); + toast.success(tFormat('engine.looseMove.moved', locale, { count: answer.moved.length, package: pkgLabel })); + refresh(); + }} + /> {!loading && filtered.length > 0 && ( // objectstack#36897 — every type's list is the same table: the // record list's `ObjectGrid`, fed the rows above in their order @@ -1937,6 +2096,9 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string /** The page columns after the list's own (`metadataListGrid.ts` keys none of them as a field). */ const CHANGED_COLUMN = '__changed'; +/** objectstack#38150 — the select column of the "Loose" list, first when drawn. */ +const SELECT_COLUMN = '__select'; +const EMPTY_LOOSE_ITEMS: readonly LooseItem[] = []; const SOURCE_COLUMN = '__source'; const CONTROLS_COLUMN = '__controls'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.controlWidgetGridNaming-9889.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.controlWidgetGridNaming-9889.test.tsx index e527aaf8f3d..5b8ca7d9c2e 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.controlWidgetGridNaming-9889.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.controlWidgetGridNaming-9889.test.tsx @@ -110,6 +110,7 @@ const CONTROL_CASES: WidgetCase[] = [ { widget: 'related-list-entries', control: (c) => c.querySelector('input[type="text"]'), faceName: 'the related-list entry box' }, { widget: 'secret', control: (c) => c.querySelector('input[type="password"]'), faceName: 'the masked credential box' }, { widget: 'field-history', control: (c) => c.querySelector('[role="combobox"]'), faceName: 'the Default / On / Off picker' }, + { widget: 'knowledge-retrieval-mode', control: (c) => c.querySelector('[role="combobox"]'), faceName: 'the retrieval-mode picker' }, ]; /** diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.declaredBooleanDefault-38420.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.declaredBooleanDefault-38420.test.tsx new file mode 100644 index 00000000000..a80f51f75c9 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.declaredBooleanDefault-38420.test.tsx @@ -0,0 +1,184 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38420 — an UNSET metadata-form switch shows the default the + * schema declares for it. + * + * The builtin Switch drew `!!value`, so every unset boolean read OFF. On a key + * whose schema says `.default(true)` that is the opposite of what runs: a + * knowledge source that stores neither `aiExposed` nor + * `refresh.onRecordChange` is searched and synced, while both switches said + * off, beside help text saying "On by default". + * + * The rule is "show, do not write" (the flow node inspector's boolean rule): + * the control draws the value in effect, and nothing is written until the + * author toggles. + * + * Pins, all against the real spec — the served form and the schema derived + * from the registered metadata type, as the `/meta/types` row carries them: + * - the knowledge-source form, edit and read-only: both unset switches ON; + * - an explicit `false` draws OFF, an explicit `true` draws ON; + * - an untouched form writes nothing; the first toggle writes an explicit + * boolean; + * - EVERY boolean row a registered form declares whose derived schema + * defaults to `true` draws ON when unset — enumerated here, never listed, + * with a floor so the walk cannot pass by finding nothing; + * - CONTROL: a boolean with no declared default, unset, draws OFF. + */ + +import '@testing-library/jest-dom/vitest'; +// The source under test reaches these through dynamic imports: their first load is paid at collection. +import '@objectstack/lint'; +import '@object-ui/plugin-detail'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, cleanup, fireEvent } from '@testing-library/react'; +import { z } from 'zod'; +import { getMetadataTypeSchema } from '@objectstack/spec/kernel'; +import { METADATA_FORM_REGISTRY } from '@objectstack/spec/system'; + +import { SchemaForm } from './SchemaForm'; +import type { FormFieldSpec, FormViewSpec } from './form-spec'; +import './register-builtins'; + +afterEach(cleanup); + +type Json = Record; + +/** The schema a `/meta/types` row serves for `type`, derived from the registered spec schema. */ +function servedSchema(type: string): Json { + const zodSchema = getMetadataTypeSchema(type); + expect(zodSchema, `no registered schema for ${type}`).toBeDefined(); + return z.toJSONSchema(zodSchema!, { unrepresentable: 'any' }) as Json; +} + +/** The object node of a property: itself, or the object branch of a union. */ +function objectNode(node: unknown): Json | undefined { + if (!node || typeof node !== 'object') return undefined; + const n = node as Json; + if (n.properties && typeof n.properties === 'object') return n; + for (const key of ['anyOf', 'oneOf']) { + const branches = n[key]; + if (Array.isArray(branches)) { + const hit = branches.find((b) => b && typeof b === 'object' && (b as Json).properties); + if (hit) return hit as Json; + } + } + return undefined; +} + +interface DefaultTrueRow { + type: string; + /** Dotted path of the row, through the composites it sits in. */ + path: string; + fieldSpec: FormFieldSpec; + schema: Json; +} + +/** + * Every boolean row a form declares whose derived schema defaults to `true`, + * top level and inside `composite` groups (the nesting the form renders as + * sub-rows of one object). + */ +function defaultTrueRows(): DefaultTrueRow[] { + const rows: DefaultTrueRow[] = []; + const walk = (type: string, fields: FormFieldSpec[], parent: Json | undefined, prefix: string) => { + for (const f of fields) { + const prop = (parent?.properties as Json | undefined)?.[f.field] as Json | undefined; + const path = prefix ? `${prefix}.${f.field}` : f.field; + if (f.type === 'composite' && Array.isArray(f.fields)) { + walk(type, f.fields as FormFieldSpec[], objectNode(prop), path); + continue; + } + if (prop && prop.type === 'boolean' && prop.default === true) rows.push({ type, path, fieldSpec: f, schema: prop }); + } + }; + for (const [type, form] of Object.entries(METADATA_FORM_REGISTRY)) { + if (!getMetadataTypeSchema(type)) continue; + const root = objectNode(servedSchema(type)); + for (const section of (form as { sections?: { fields?: FormFieldSpec[] }[] }).sections ?? []) { + walk(type, section.fields ?? [], root, ''); + } + } + return rows; +} + +const switchNamed = (name: string) => screen.getByRole('switch', { name: new RegExp(`^${name}`) }); + +describe('an unset metadata-form switch shows the default its schema declares (objectstack#38420)', () => { + const form = METADATA_FORM_REGISTRY.knowledge_source as unknown as FormViewSpec; + const schema = servedSchema('knowledge_source') as never; + const STORED = { + name: 'task_notes', + label: 'Task notes', + source: { kind: 'object', object: 'acme_task', content: ['title'] }, + }; + + it.each([ + ['edit', false], + ['read-only', true], + ])('⭐ %s mode: a knowledge source storing neither key draws both switches ON', (_mode, readOnly) => { + render(); + expect(switchNamed('Searchable by AI agents')).toHaveAttribute('aria-checked', 'true'); + expect(switchNamed('Sync on record changes')).toHaveAttribute('aria-checked', 'true'); + }); + + it('an explicit false draws OFF and an explicit true draws ON', () => { + const { unmount } = render( + , + ); + expect(switchNamed('Searchable by AI agents')).toHaveAttribute('aria-checked', 'false'); + expect(switchNamed('Sync on record changes')).toHaveAttribute('aria-checked', 'false'); + unmount(); + render( + , + ); + expect(switchNamed('Searchable by AI agents')).toHaveAttribute('aria-checked', 'true'); + expect(switchNamed('Sync on record changes')).toHaveAttribute('aria-checked', 'true'); + }); + + it('display only: an untouched form writes nothing, and the first toggle writes an explicit false', () => { + const onChange = vi.fn(); + render(); + expect(onChange).not.toHaveBeenCalled(); + fireEvent.click(switchNamed('Searchable by AI agents')); + expect(onChange).toHaveBeenCalledTimes(1); + const next = onChange.mock.calls[0][0] as Json; + expect(next.aiExposed).toBe(false); + expect('refresh' in next).toBe(false); + }); + + it('every boolean row a registered form declares with a true default draws ON when unset', () => { + const rows = defaultTrueRows(); + const paths = rows.map((r) => `${r.type}.${r.path}`); + // Floor: the two rows the card names, one nested in a composite, and one on another form. + expect(paths).toEqual(expect.arrayContaining([ + 'knowledge_source.aiExposed', + 'knowledge_source.refresh.onRecordChange', + 'skill.active', + ])); + for (const row of rows) { + const key = row.fieldSpec.field; + const { unmount } = render( + , + ); + expect(screen.getByRole('switch'), `${row.type}.${row.path}`).toHaveAttribute('aria-checked', 'true'); + unmount(); + } + }); + + it('CONTROL: a boolean with no declared default draws OFF when unset', () => { + render( + , + ); + expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'false'); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx index f0ff5d8b0dd..3095ad68c42 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx @@ -2612,13 +2612,20 @@ function FieldControl({ // the sub-field as boolean. Without this, capability toggles inside the // Object editor's "Capabilities" section fell through to RawJsonEditor // and rendered as empty textareas. + // + // The switch shows the value IN EFFECT — "show, do not write", the flow + // node inspector's boolean rule (`FlowNodeConfigField`): an UNSET key draws + // the schema's declared `default` (a `.default(true)` key is ON), a stored + // boolean draws itself. Nothing is written until the author toggles, so an + // untouched item still saves without the key and keeps tracking the default. if (effectiveType === 'boolean' || widget === 'switch' || fieldSpec?.type === 'boolean' || fieldSpec?.type === 'toggle') { + const declaredDefault = effective && 'default' in effective ? effective.default : schema?.default; return ( onChange(c)} disabled={readOnly} /> diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx index d344ccc1f26..eb887e3587b 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx @@ -181,6 +181,7 @@ const CASES: Case[] = [ { key: 'code', schema: { type: 'string', title: TITLE }, spec: { language: 'javascript' }, value: 'x = 1' }, { key: 'secret', schema: { type: 'string', title: TITLE }, value: 's3cr3t' }, { key: 'field-history', schema: { type: 'boolean', title: TITLE }, formData: { type: 'json' }, value: false }, + { key: 'knowledge-retrieval-mode', schema: { type: 'string', title: TITLE, enum: ['vector', 'keyword', 'hybrid'] }, value: 'keyword' }, { key: 'dynamic-config', schema: { type: 'object', title: TITLE }, spec: { dependsOn: 'driver' }, formData: { driver: 'pg' }, ctx: { dynamicSchemas: { pg: { properties: { host: { type: 'string' } } } } }, value: {} }, { key: 'dynamic-config', variant: 'unconfigured', schema: { type: 'object', title: TITLE }, spec: { dependsOn: 'driver' }, formData: { driver: '' }, value: {} }, ]; diff --git a/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx index bd5cc505e1c..fd68b811bcc 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx @@ -109,6 +109,7 @@ const FAILED_CTX: WidgetContext = { objectViews: failed('views: HTTP 503'), objectActions: failed('actions: HTTP 503'), datasets: failed('datasets: HTTP 503'), + knowledgeRetrieval: failed('index_status: HTTP 403'), }; const LOADED_CTX: WidgetContext = { @@ -118,6 +119,7 @@ const LOADED_CTX: WidgetContext = { objectViews: loaded([{ name: 'account.all', label: 'All' }]), objectActions: loaded([{ name: 'approve' }]), datasets: loaded([{ name: 'sales_metrics', label: 'Sales metrics', dimensions: [], measures: [] }]), + knowledgeRetrieval: loaded({ adapter: 'turso', mounted: true, modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' }), }; interface ControlCase { @@ -170,6 +172,8 @@ const CASES: ControlCase[] = [ { key: 'secret', schema: { type: 'string' }, value: 's3cr3t', banner: null }, // No catalog: the one face is the trigger, on every arm. { key: 'field-history', schema: { type: 'boolean' }, value: false, banner: null }, + // A refused store read offers the three modes and lets the save judge: no block. + { key: 'knowledge-retrieval-mode', schema: { type: 'string' }, value: 'keyword', banner: null }, ]; /** diff --git a/ui/packages/app-shell/src/views/metadata-admin/directoryScope.ts b/ui/packages/app-shell/src/views/metadata-admin/directoryScope.ts index e62307771ea..179bab90fcd 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/directoryScope.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/directoryScope.ts @@ -10,13 +10,14 @@ import { ENVIRONMENT_AREA_TYPES } from './metadataAreaHost.js'; /** * Types never listed. `field` is edited inside its object; `package` is the - * scope container itself, with its own management surface. `form` (ADR-0159 - * card ②, objectstack#37086) has no designer, menu placement or ADR-0084 row - * yet: card ③ (objectstack#37087) brings all three and takes it off this set. - * Its forms are still served and judged; only Studio's directory and menu - * leave the type out. + * scope container itself, with its own management surface. + * + * `form` was on this set while the type had no designer, menu placement or + * ADR-0084 row (ADR-0159 card ②, objectstack#37086). Card ③ + * (objectstack#37087) brought all three, so the directory and the menu list + * the type like any other. */ -export const HIDDEN_DIRECTORY_TYPES: ReadonlySet = new Set(['field', 'package', 'form']); +export const HIDDEN_DIRECTORY_TYPES: ReadonlySet = new Set(['field', 'package']); /** * The served type entries a directory lists, in served order: diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ActionDefaultInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ActionDefaultInspector.tsx index f3d48dee150..e38171b52f6 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ActionDefaultInspector.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ActionDefaultInspector.tsx @@ -316,6 +316,8 @@ const LOCATION_LABELS: Record = { record_section: 'engine.inspector.action.location.record_section', record_related: 'engine.inspector.action.location.record_related', list: 'engine.inspector.action.location.list', + // objectstack#36496 — acts on many records: the selection bar of every grid. + selection: 'engine.inspector.action.location.selection', }; const LOCATIONS: Array<{ value: ActionLocation; labelKey: string }> = ( diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectPicker.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectPicker.test.tsx index ff2f8e861df..4ce5bdd8bd1 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectPicker.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectPicker.test.tsx @@ -43,6 +43,10 @@ vi.mock('../useMetadata', () => ({ useMetadataClient: () => h.client })); import { ObjectPicker, type ObjectPickerProps } from './ObjectPicker'; import { t } from '../i18n'; +import { loadStudioCatalogue } from '@object-ui/i18n/namespaces/studio'; + +// The refusal-line pins read the zh table, which the namespace loads lazily. +await loadStudioCatalogue('zh'); // objectstack#28240 — editing a package, the picker reads `GET /api/v1/packages` // for the package's closure. No package is listed here, so nothing is narrowed @@ -204,38 +208,50 @@ describe('ObjectPicker — objectsOnly: a door that takes no expression (objects expect(refusal()).toBeNull(); }); - it('Enter on a prefix that leaves several matches commits no object and says none is chosen', async () => { - const { input, onCommit } = renderPicker({ objectsOnly: true }); - await openList(input); - await userEvent.type(input, 'repairs'); - expect(offered()).toHaveLength(2); - await userEvent.keyboard('{Enter}'); - // The value was empty and stays empty: nothing to commit. - expect(onCommit).not.toHaveBeenCalled(); - expect(refusal()).toHaveTextContent( - t('engine.inspector.objectPicker.notChosen', 'en-US').replace('{text}', 'repairs'), - ); - }); + /** The refusal line `key` renders for `text` in `locale`. */ + const line = (key: string, locale: 'en-US' | 'zh-CN', text: string) => + t(`engine.inspector.objectPicker.${key}`, locale).replace('{text}', text); - it('a typed name that is no object keeps the chosen one and says it was refused, on Enter and on blur alike', async () => { - const enter = renderPicker({ objectsOnly: true, value: 'showcase_account' }); - await openList(enter.input); - await userEvent.clear(enter.input); - await userEvent.type(enter.input, 'crm_custom_eval'); - await userEvent.keyboard('{Enter}'); - expect(enter.onCommit).not.toHaveBeenCalled(); - expect(enter.input).toHaveValue('showcase_account'); - expect(refusal()).not.toBeNull(); - cleanup(); + /** The refusal reads `key` in `locale`, and a zh line is its own text, not the en fallback. */ + const expectRefusal = (key: string, locale: 'en-US' | 'zh-CN', text: string) => { + expect(refusal()).toHaveTextContent(line(key, locale, text)); + if (locale !== 'en-US') expect(refusal()).not.toHaveTextContent(line(key, 'en-US', text)); + }; - const blur = renderPicker({ objectsOnly: true, value: 'showcase_account' }); - await openList(blur.input); - await userEvent.clear(blur.input); - await userEvent.type(blur.input, 'crm_custom_eval'); - await userEvent.tab(); - expect(blur.onCommit).not.toHaveBeenCalled(); - expect(refusal()).not.toBeNull(); - }); + for (const locale of ['en-US', 'zh-CN'] as const) { + it(`[${locale}] Enter on a prefix that leaves several matches commits no object and says none is chosen`, async () => { + const { input, onCommit } = renderPicker({ objectsOnly: true, locale }); + await openList(input); + await userEvent.type(input, 'repairs'); + expect(offered()).toHaveLength(2); + await userEvent.keyboard('{Enter}'); + // The value was empty and stays empty: nothing to commit. + expect(onCommit).not.toHaveBeenCalled(); + expectRefusal('notChosen', locale, 'repairs'); + }); + + it(`[${locale}] a typed name that is no object keeps the chosen one and says it is kept, on Enter and on blur alike`, async () => { + const enter = renderPicker({ objectsOnly: true, value: 'showcase_account', locale }); + await openList(enter.input); + await userEvent.clear(enter.input); + await userEvent.type(enter.input, 'crm_custom_eval'); + await userEvent.keyboard('{Enter}'); + expect(enter.onCommit).not.toHaveBeenCalled(); + expect(enter.input).toHaveValue('showcase_account'); + // The stored target stays, so the line says so -- never "no object chosen". + expectRefusal('notAnObjectKept', locale, 'crm_custom_eval'); + expect(refusal()).not.toHaveTextContent(line('notChosen', locale, 'crm_custom_eval')); + cleanup(); + + const blur = renderPicker({ objectsOnly: true, value: 'showcase_account', locale }); + await openList(blur.input); + await userEvent.clear(blur.input); + await userEvent.type(blur.input, 'crm_custom_eval'); + await userEvent.tab(); + expect(blur.onCommit).not.toHaveBeenCalled(); + expectRefusal('notAnObjectKept', locale, 'crm_custom_eval'); + }); + } it('an input cleared on purpose still commits no object', async () => { const { input, onCommit } = renderPicker({ objectsOnly: true, value: 'showcase_account' }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectPicker.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectPicker.tsx index 67673128c8d..60471986fc3 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectPicker.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectPicker.tsx @@ -324,7 +324,8 @@ export function ObjectPicker({ const [systemOpen, setSystemOpen] = React.useState(false); const [outsideOpen, setOutsideOpen] = React.useState(false); const [declaring, setDeclaring] = React.useState(false); - // objectsOnly — the text last refused, so the picker can say no object is chosen. + // objectsOnly — the text last refused, so the picker can say it is no object: + // either no object is chosen, or the stored one is kept. const [refused, setRefused] = React.useState(null); const entries = catalog.status === 'loaded' ? catalog.data : NO_ENTRIES; @@ -718,7 +719,15 @@ export function ObjectPicker({ )} {refused !== null && (

- {tFormat('engine.inspector.objectPicker.notChosen', locale, { text: refused })} + {tFormat( + // A stored target is kept (`commitTyped` restores it), so the line + // must not say none is chosen; only an empty field has none. + value + ? 'engine.inspector.objectPicker.notAnObjectKept' + : 'engine.inspector.objectPicker.notChosen', + locale, + { text: refused }, + )}

)} {declaring && closure && ( diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/inspectorStrings.hookAction.i18n-10586.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/inspectorStrings.hookAction.i18n-10586.test.tsx index 9a2accf25f4..9fa15e03155 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/inspectorStrings.hookAction.i18n-10586.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/inspectorStrings.hookAction.i18n-10586.test.tsx @@ -386,7 +386,9 @@ const ACTION_EN = [ // Placement 'Placement', 'Where this action surfaces in the UI.', - 'No placement selected — this action will not appear on any record or list surface. Tick a placement above, or place it from a view’s bulk actions.', + // objectstack#36496: "or place it from a view's bulk actions" dropped — a view + // no longer lists bulk actions; `selection` is one of the placements above. + 'No placement selected — this action will not appear on any record or list surface. Tick a placement above.', 'Capability-gated on a.b — every placement ticked above hides this action from anyone who does not hold it. Not greyed out and not an error: the button is simply absent, and the server refuses the invocation with a 403 either way. This session does not hold a.b, so the button is hidden from you too — grant it through a permission set to see it in the app.', 'This session does not hold a.b, so the button is hidden from you too — grant it through a permission set to see it in the app.', 'Capability-gated on a.b + c.d — every placement ticked above hides this action from anyone who does not hold all of them. Not greyed out and not an error: the button is simply absent, and the server refuses the invocation with a 403 either way.', diff --git a/ui/packages/app-shell/src/views/metadata-admin/knowledgeRetrieval.ts b/ui/packages/app-shell/src/views/metadata-admin/knowledgeRetrieval.ts new file mode 100644 index 00000000000..2da93bdd350 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/knowledgeRetrieval.ts @@ -0,0 +1,84 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The retrieval modes a knowledge source's store runs, for the Studio form's + * `source.retrieval.mode` picker (objectstack#38692 phase 1a). + * + * The knowledge service answers them on its `index_status` settings action + * (`POST /api/settings/knowledge/index_status`): each mounted store's modes and + * default (`details.adapters`), and the store a source that names none binds + * to (`details.defaultAdapter`). The source on screen binds to the store its + * `adapter` names, else that one. A store that reports no modes (memory) takes + * only a source that leaves the mode out; the picker says so rather than + * offering a mode its save would refuse. + * + * The action is gated on the settings namespace's write permission, so an + * author who is not a platform administrator is refused the read: the picker + * then offers the three modes and the save judges the choice, as before this + * reader existed. + */ + +import { bearerAuthHeaders } from '../../utils/authToken.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The three modes the spec names (`KNOWLEDGE_RETRIEVAL_MODES`), in the form's order. */ +export const RETRIEVAL_MODES = ['vector', 'keyword', 'hybrid'] as const; +export type RetrievalMode = (typeof RETRIEVAL_MODES)[number]; + +/** The store a source binds to, and the modes it reports. */ +export interface KnowledgeStoreRetrieval { + /** The store's adapter id; absent when the source names none and none is placed. */ + adapter?: string; + /** Whether the service lists the store as mounted. */ + mounted: boolean; + /** The modes it runs; absent: it reports none ("驱动未声明"). */ + modes?: RetrievalMode[]; + /** Its default mode; absent with `modes`. */ + default?: RetrievalMode; +} + +interface IndexStatusDetails { + adapters?: Array<{ id?: unknown; retrieval?: { modes?: unknown; default?: unknown } }>; + defaultAdapter?: unknown; +} + +const isMode = (m: unknown): m is RetrievalMode => typeof m === 'string' && (RETRIEVAL_MODES as readonly string[]).includes(m); + +/** + * The store `adapter` (else the deployment's) and its modes, read from an + * `index_status` answer body (`{ success, data: { details } }`, or the bare + * result). A body that is not that shape throws, so the caller reads a failed + * load, never an empty one. + */ +export function storeRetrievalOf(body: unknown, adapter: string | undefined): KnowledgeStoreRetrieval { + const result = + body && typeof body === 'object' && (body as { success?: unknown }).success === true + ? (body as { data?: unknown }).data + : body; + const details = (result as { details?: IndexStatusDetails } | null | undefined)?.details; + if (!details || !Array.isArray(details.adapters)) { + throw new Error('the knowledge service answered no list of stores'); + } + const bound = adapter ?? (typeof details.defaultAdapter === 'string' ? details.defaultAdapter : undefined); + if (bound === undefined) return { mounted: false }; + const row = details.adapters.find((a) => a?.id === bound); + if (!row) return { adapter: bound, mounted: false }; + const report = row.retrieval; + const modes = Array.isArray(report?.modes) ? report.modes.filter(isMode) : undefined; + if (!modes || modes.length === 0 || !isMode(report?.default)) return { adapter: bound, mounted: true }; + return { adapter: bound, mounted: true, modes, default: report.default }; +} + +const serverUrl = (): string => (import.meta.env?.VITE_SERVER_URL || '').replace(/\/$/, ''); + +/** Read the store `adapter` (else the deployment's) binds to, and its modes. */ +export async function fetchStoreRetrieval(adapter: string | undefined): Promise { + const res = await createAuthenticatedFetch()(`${serverUrl()}/api/settings/knowledge/index_status`, { + method: 'POST', + credentials: 'include', + headers: { Accept: 'application/json', 'Content-Type': 'application/json', ...bearerAuthHeaders() }, + body: '{}', + }); + if (!res.ok) throw new Error(`index_status answered ${res.status}`); + return storeRetrievalOf(await res.json(), adapter); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/looseMove-38150.test.ts b/ui/packages/app-shell/src/views/metadata-admin/looseMove-38150.test.ts new file mode 100644 index 00000000000..d102781ef55 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/looseMove-38150.test.ts @@ -0,0 +1,127 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38150 PR-A2 — the "Loose" source value in the list's address + * state, and the console's call to the move door (`looseMove.ts`). Pinned, + * each with its control: + * + * - `source=loose` round-trips through the codec; an unknown value reads as + * every source; + * - under `loose` the list keeps the rows the reader's `loose` member keeps; + * with no such member the filter is not offered and keeps every row; + * - the move door's 422 refusal resolves as the door's own answer; any other + * failure throws with the server's sentence; + * - the references a refusal names are added once, the selection's own items + * never twice. + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +// The source reaches `celAuthoring`'s dynamic `@objectstack/lint` import; its +// first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; +import { + applyListState, + decodeListState, + DEFAULT_LIST_STATE, + writeListState, + type ListRowReader, +} from './metadataListState'; +import { isLooseRow, moveLooseItems, referencesLeftBehind, withLooseItems } from './looseMove'; + +afterEach(() => vi.unstubAllGlobals()); + +interface Row { + item: Record; +} +const ROWS: Row[] = [ + { item: { name: 'a' } }, + { item: { name: 'b', _packageId: 'sys_metadata' } }, + { item: { name: 'c', _packageId: 'app.alpha' } }, + { item: { name: 'd', _packageId: 'app.alpha.custom' } }, +]; +const base: ListRowReader = { + name: (r) => String(r.item.name), + label: () => undefined, + matches: () => true, + source: (r) => (r.item._packageId === 'app.alpha' ? 'artifact' : 'runtime'), +}; + +describe('the list state: "loose" (objectstack#38150)', () => { + it('round-trips source=loose', () => { + const state = decodeListState(new URLSearchParams('source=loose')); + expect(state.source).toBe('loose'); + expect(writeListState(new URLSearchParams(), state).toString()).toBe('source=loose'); + }); + + it('control: an unknown source reads as every source', () => { + expect(decodeListState(new URLSearchParams('source=org')).source).toBe('all'); + }); + + it('keeps the rows the reader reads as loose, never a .custom pair row the runtime source would keep', () => { + const state = { ...DEFAULT_LIST_STATE, source: 'loose' as const }; + const kept = applyListState(ROWS, state, { ...base, loose: (r) => isLooseRow(r.item) }, 'en-US'); + expect(kept.map((r) => r.item.name)).toEqual(['a', 'b']); + const runtime = applyListState(ROWS, { ...DEFAULT_LIST_STATE, source: 'runtime' }, base, 'en-US'); + expect(runtime.map((r) => r.item.name)).toEqual(['a', 'b', 'd']); + }); + + it('control: with no loose member the filter is not offered and keeps every row', () => { + const kept = applyListState(ROWS, { ...DEFAULT_LIST_STATE, source: 'loose' }, base, 'en-US'); + expect(kept).toHaveLength(ROWS.length); + }); +}); + +function answer(status: number, payload: unknown) { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify(payload), { status, headers: { 'Content-Type': 'application/json' } })), + ); +} + +describe('the move door call (objectstack#38150)', () => { + const ITEMS = [{ type: 'flow', name: 'f1' }]; + + it('a 422 refusal resolves as the door answer, every item with its own code', async () => { + const refused = { + outcome: 'refused', + targetPackageId: 'com.probe.ghost', + moved: [], + refused: [{ type: 'flow', name: 'f1', code: 'WRITABLE_PACKAGE_REQUIRED', error: 'Not installed.' }], + }; + answer(422, { success: false, error: { code: 'WRITABLE_PACKAGE_REQUIRED', message: 'Not installed.', details: refused } }); + await expect(moveLooseItems('com.probe.ghost', ITEMS, true)).resolves.toEqual(refused); + }); + + it('control: a failure that is not an answer throws with the server sentence', async () => { + answer(403, { success: false, error: { code: 'FORBIDDEN', message: 'Moving loose metadata is refused here.' } }); + await expect(moveLooseItems('app.alpha', ITEMS, true)).rejects.toThrow('Moving loose metadata is refused here.'); + }); + + it('sends the selection, with dryRun only on a dry run', async () => { + const fetchMock = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response(JSON.stringify({ success: true, data: { outcome: 'moved', targetPackageId: 'app.alpha', moved: [], refused: [] } }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }), + ); + vi.stubGlobal('fetch', fetchMock); + await moveLooseItems('app.alpha', ITEMS, true); + await moveLooseItems('app.alpha', ITEMS, false); + const bodies = fetchMock.mock.calls.map((c) => JSON.parse(String(c[1]?.body))); + expect(String(fetchMock.mock.calls[0][0])).toContain('/api/v1/packages/app.alpha/move-in'); + expect(bodies).toEqual([{ items: ITEMS, dryRun: true }, { items: ITEMS }]); + }); +}); + +describe('the selection (objectstack#38150)', () => { + it('adds what a refusal names as left behind once, never an item the selection holds', () => { + const items = [{ type: 'flow', name: 'f1' }, { type: 'dataset', name: 'ds1' }]; + const more = referencesLeftBehind(items, [ + { type: 'flow', name: 'f1', code: 'REFERENCE_LEFT_BEHIND', error: 'x', references: [{ type: 'dataset', name: 'ds1' }, { type: 'dataset', name: 'ds2' }] }, + { type: 'flow', name: 'f2', code: 'REFERENCE_LEFT_BEHIND', error: 'y', references: [{ type: 'dataset', name: 'ds2' }] }, + ]); + expect(more).toEqual([{ type: 'dataset', name: 'ds2' }]); + expect(withLooseItems(items, more)).toEqual([...items, { type: 'dataset', name: 'ds2' }]); + expect(withLooseItems(items, items)).toEqual(items); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/looseMove.ts b/ui/packages/app-shell/src/views/metadata-admin/looseMove.ts new file mode 100644 index 00000000000..890b6a9caaf --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/looseMove.ts @@ -0,0 +1,111 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38150 — the console's half of the move door (ADR-0084's + * amendment of 2026-11-26, "Loose items stay where they are, and one door + * moves them"; ruling 7184753035, question 3): a selection of loose items, + * one, several or every loose item of a type, moved into one package through + * `POST /api/v1/packages/:id/move-in`. + * + * Invariants: + * - What is loose is `isPackageLessItem` on the served `_packageId`, the one + * reading; never `classifyProvenance`, which also files a `.custom` pair + * item and a served overlay as "runtime". + * - The answer is the server's. A refusal arrives as a 422 whose details are + * the whole answer (`outcome: 'refused'`, every item's own code and + * sentence), and is returned as that answer, never re-worded here. Any + * other failure throws. + * - The confirm step reads a dry run, which runs the judgement made before any + * door (loose, target, the object judges, the set) and writes nothing, so a + * save-door judge can still refuse the real move. The confirm says so. + */ + +import type { + MoveIntoPackageItem, + MoveIntoPackageRefusedItem, + MoveIntoPackageResponse, +} from '@objectstack/spec/api'; +import { PACKAGES_API, packagesApiJson } from './packageActions.js'; +import { isPackageLessItem } from '../studio-design/studioScope.js'; + +export type LooseItem = MoveIntoPackageItem; + +/** One loose item's key in a selection: its type, name and bundle member. */ +export function looseItemKey(item: { type: string; name: string; member?: string | null }): string { + return `${item.type}\u0000${item.name}\u0000${item.member ?? ''}`; +} + +/** Whether a served row is loose: bound to no package (`isPackageLessItem`). */ +export function isLooseRow(item: { _packageId?: unknown } | null | undefined): boolean { + return isPackageLessItem(item); +} + +/** `items` with `more` added, each once, in the order first named. */ +export function withLooseItems(items: readonly LooseItem[], more: readonly LooseItem[]): LooseItem[] { + const seen = new Set(items.map(looseItemKey)); + const out = [...items]; + for (const item of more) { + const key = looseItemKey(item); + if (seen.has(key)) continue; + seen.add(key); + out.push(item); + } + return out; +} + +/** + * The loose items a refused answer names as left behind + * (`REFERENCE_LEFT_BEHIND`'s `references`) that the selection does not hold + * yet: what "add them and check again" adds. + */ +export function referencesLeftBehind(items: readonly LooseItem[], refused: readonly MoveIntoPackageRefusedItem[]): LooseItem[] { + const held = new Set(items.map(looseItemKey)); + const out: LooseItem[] = []; + for (const r of refused) { + for (const ref of r.references ?? []) { + const item = { type: ref.type, name: ref.name }; + const key = looseItemKey(item); + if (held.has(key)) continue; + held.add(key); + out.push(item); + } + } + return out; +} + +function isMoveAnswer(value: unknown): value is MoveIntoPackageResponse { + const v = value as Partial | null | undefined; + return ( + !!v && + typeof v === 'object' && + (v.outcome === 'moved' || v.outcome === 'would_move' || v.outcome === 'refused') && + Array.isArray(v.moved) && + Array.isArray(v.refused) + ); +} + +/** + * Ask the move door: `dryRun` answers what the move would do and writes + * nothing. Resolves with the door's answer, a refusal included; throws on any + * other failure (the gates' refusals, a fault), with the server's sentence. + */ +export async function moveLooseItems( + targetPackageId: string, + items: readonly LooseItem[], + dryRun: boolean, +): Promise { + try { + return await packagesApiJson( + `${PACKAGES_API}/${encodeURIComponent(targetPackageId)}/move-in`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ items, ...(dryRun ? { dryRun: true } : {}) }), + }, + ); + } catch (err) { + const details = (err as { details?: unknown } | null)?.details; + if (isMoveAnswer(details) && details.outcome === 'refused') return details; + throw err; + } +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts b/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts index 5c0386b4f3d..69a03b5b472 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts @@ -31,7 +31,11 @@ import { compareChangedAt } from './listChangedAt.js'; /** The search text. */ export const LIST_QUERY_PARAM = 'q'; -/** The source filter: `artifact` or `runtime`; absent = every source. */ +/** + * The source filter: `artifact`, `runtime` or `loose`; absent = every source. + * `loose` (objectstack#38150) is offered on the cross-package leg only: the + * rows bound to no package, read by `isPackageLessItem` exactly. + */ export const LIST_SOURCE_PARAM = 'source'; /** "Only customizations": `1`; absent = off. */ export const LIST_CUSTOMIZED_PARAM = 'customized'; @@ -57,7 +61,10 @@ export const LIST_STATE_PARAMS: readonly string[] = [ LIST_TARGET_OBJECT_PARAM, ]; -export type ListSourceFilter = 'all' | 'artifact' | 'runtime'; +export type ListSourceFilter = 'all' | 'artifact' | 'runtime' | 'loose'; + +/** The source filter's value for the loose rows (objectstack#38150). */ +export const LIST_LOOSE_SOURCE = 'loose'; export type ListStatusFilter = 'all' | 'active' | 'inactive'; /** @@ -127,7 +134,7 @@ export function decodeListState(params: URLSearchParams): MetadataListState { const targetObject = params.get(LIST_TARGET_OBJECT_PARAM)?.trim(); return { query: params.get(LIST_QUERY_PARAM) ?? '', - source: source === 'artifact' || source === 'runtime' ? source : 'all', + source: source === 'artifact' || source === 'runtime' || source === LIST_LOOSE_SOURCE ? source : 'all', customizedOnly: params.get(LIST_CUSTOMIZED_PARAM) === '1', status: status === 'active' || status === 'inactive' ? status : 'all', sort: decodeListSort(params.get(LIST_SORT_PARAM)), @@ -180,6 +187,12 @@ export interface ListRowReader { matches(row: R, query: string): boolean; /** Where the row comes from. */ source(row: R): 'artifact' | 'runtime'; + /** + * The "Loose" source value is offered (objectstack#38150, the cross-package + * leg): is the row bound to no package? Absent, `source=loose` is not + * offered and reads as every source, as an unoffered filter does. + */ + loose?: (row: R) => boolean; /** "Only customizations" is offered: is the row a customization? */ customized?: (row: R) => boolean; /** @@ -238,7 +251,9 @@ export function applyListState( const collator = collatorFor(locale); const kept = rows.filter((row) => { if (state.query && !read.matches(row, state.query)) return false; - if (state.source !== 'all' && read.source(row) !== state.source) return false; + if (state.source === LIST_LOOSE_SOURCE) { + if (read.loose && !read.loose(row)) return false; + } else if (state.source !== 'all' && read.source(row) !== state.source) return false; if (state.targetObject && read.targetObject && read.targetObject(row) !== state.targetObject) return false; if (state.customizedOnly && read.customized && !read.customized(row)) return false; if (state.status !== 'all' && read.active) { diff --git a/ui/packages/app-shell/src/views/metadata-admin/packageActions.tsx b/ui/packages/app-shell/src/views/metadata-admin/packageActions.tsx index 6554fa599bd..abf26b38f7f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/packageActions.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/packageActions.tsx @@ -17,19 +17,8 @@ import * as React from 'react'; import { Copy } from 'lucide-react'; -import { - Button, - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from '@object-ui/components'; +import { Button } from '@object-ui/components'; import { createAuthenticatedFetch } from '@object-ui/auth'; -import type { ReassignOrphanedMetadataResponse } from '@objectstack/spec/api'; import { t, tFormat } from './i18n.js'; import { PackageFormDialog } from './PackageFormDialog.js'; import { readEnvelopeFailureText } from '../../utils/apiErrorEnvelope.js'; @@ -55,7 +44,7 @@ function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise(path: string, init?: RequestInit): Promise { // objectstack#29119 — every write this page sends (publish, revert, discard, - // delete, adopt, enable/disable, import) may change the package list, so the + // delete, move-in, enable/disable, import) may change the package list, so the // list reads from before it are forgotten however it ends, the session's // held list the app → Studio entries read included. const writes = (init?.method ?? 'GET').toUpperCase() !== 'GET'; @@ -133,27 +122,6 @@ export async function exportPackageFile(id: string): Promise { URL.revokeObjectURL(url); } -/** - * ADR-0070 D5 — adopt every package-less (loose) item in this environment INTO - * the package. Answers the server's own count, `reassignedCount` - * (`ReassignOrphanedMetadataResponse`), 0 included: the answer's own `success` - * is false exactly when nothing moved, which on this door is a count of 0, not - * a failure, so the count is what the author is told. - */ -export async function adoptLooseItems(id: string): Promise { - const r = await packagesApiJson(packagePath(id, '/adopt-orphans'), { - method: 'POST', - }); - return r.reassignedCount; -} - -/** The answer to an adoption, in the author's language. */ -export function adoptedText(count: number, locale: string): string { - return tFormat(count === 1 ? 'engine.packages.detail.adoptedOne' : 'engine.packages.detail.adoptedOther', locale, { - count, - }); -} - /* -------------------------------------------------------------------------- */ /* The actions' dialogs and forms */ /* -------------------------------------------------------------------------- */ @@ -187,43 +155,6 @@ export function EditPackageDialog({ /> ); } - -/** - * The in-app confirmation *Adopt loose items* asks first (objectui#13339): only - * its confirm adopts, and its Cancel sends nothing. - */ -export function AdoptLooseItemsDialog({ - open, - onOpenChange, - displayName, - onConfirm, - locale, -}: { - open: boolean; - onOpenChange: (v: boolean) => void; - /** The package's name, as its surface's title shows it. */ - displayName: string; - onConfirm: () => void; - locale: string; -}) { - return ( - - - - {tFormat('engine.packages.detail.adoptTitle', locale, { name: displayName })} - {t('engine.packages.detail.adoptDescription', locale)} - - - {t('engine.cancel', locale)} - - {t('engine.packages.detail.adoptOrphans', locale)} - - - - - ); -} - /** * ADR-0070 D4 — the Duplicate form (objectui#11784): the new package's name and * id, the same id input (`PackageIdInput`) and the same id rule diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/ActionPreview.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/ActionPreview.tsx index 407ce3270d4..bdd8991e3b2 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/ActionPreview.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/ActionPreview.tsx @@ -934,6 +934,16 @@ function PlacementPreview({ locations, folded, label, icon, variant, iconOnly, l
)} + {/* objectstack#36496 — the selection bar a grid shows once two or more + rows are selected, on every grid of the object. */} + {locations.includes('selection') && ( + +
+ {tFormat('engine.actionPreview.placement.selected', locale, { n: 2 })} +
{btn}
+
+ + )} {/* No `global_nav` frame. The location was retired from the spec's `ACTION_LOCATIONS` in @objectstack/spec 17.0.0-rc.6 (objectstack#6888, maintainer ruling 2026-08-09 direction 2) because no running-app diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/__tests__/block-config-i18n.test.ts b/ui/packages/app-shell/src/views/metadata-admin/previews/__tests__/block-config-i18n.test.ts index db367773882..0151e9d080f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/__tests__/block-config-i18n.test.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/__tests__/block-config-i18n.test.ts @@ -316,7 +316,7 @@ describe('en-US labels are unchanged by the key migration (#3913)', () => { // options, incl. the shared `format` list and the shared ALIGN_OPTS 'engine.inspector.pageBlock.option.format.currency': 'Currency', 'engine.inspector.pageBlock.option.align.center': 'Center', - 'engine.inspector.pageBlock.option.location.record': 'Record · page and rows', + 'engine.inspector.pageBlock.option.location.record_page': 'Record page', 'engine.inspector.pageBlock.option.severity.warning': 'Warning', // ── the placeholder family (#3979) ─────────────────────────────────────── // ALL SIX, not a sample: this column was migrated by hand rather than diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/__tests__/block-config.test.ts b/ui/packages/app-shell/src/views/metadata-admin/previews/__tests__/block-config.test.ts index fbafc9ac335..0558e47c3ad 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/__tests__/block-config.test.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/__tests__/block-config.test.ts @@ -4,6 +4,7 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { ACTION_LOCATIONS, + RecordQuickActionsLocationSchema, PageAccordionProps, PageComponentType, PageHeaderProps, @@ -360,9 +361,32 @@ describe('page palette ↔ spec PageComponentType coverage', () => { // POSITIVE half. Without it the negative pin below passes on an empty // option list, which is how a deleted dropdown reads as a passing test. - it('offers exactly the locations the spec declares', () => { + // + // The set is the BAR's, not the whole action-location vocabulary: the spec + // narrows `RecordQuickActionsProps.location` to every location but + // `record` (objectstack#38045, maintainer ruling A), and this dropdown + // offers what that schema accepts — read from the schema at run time, so + // the pin cannot agree with a stale copy of the list. + it('offers exactly the locations the spec accepts for the bar', () => { + const offered = (locationField()?.options ?? []).map((o) => o.value); + expect(offered.length, 'option list is empty — the pin would be vacuous').toBeGreaterThan(0); + expect([...offered].sort()).toEqual([...RecordQuickActionsLocationSchema.options].sort()); + }); + + // NEGATIVE pin for objectstack#38045. `record` says what an ACTION acts on + // — the record page and each list row — and a bar sits in one place: a bar + // at `record` drew only the actions that declare `record` literally and + // skipped the ⋯ fold, an empty or wrong bar with no message. The spec now + // refuses the word on the bar with a prescription naming `record_page`, so + // offering it would teach authors — and every AI copying this corpus — to + // write metadata that fails to parse. + it('does NOT offer `record`, which the spec refuses on the bar', () => { const offered = (locationField()?.options ?? []).map((o) => o.value); - expect([...offered].sort()).toEqual([...ACTION_LOCATIONS].sort()); + expect(offered.length, 'option list is empty — the pin would be vacuous').toBeGreaterThan(0); + expect(offered).not.toContain('record'); + expect(RecordQuickActionsLocationSchema.safeParse('record').success).toBe(false); + // …while the word itself stays on the action-location vocabulary. + expect(ACTION_LOCATIONS as readonly string[]).toContain('record'); }); // NEGATIVE pin, converted from the coverage the removed option used to @@ -389,6 +413,19 @@ describe('page palette ↔ spec PageComponentType coverage', () => { expect(t(key, 'en-US')).toBe(key); expect(t(key, 'zh-CN')).toBe(key); }); + + // The same for `record` (objectstack#38045): both locale tables lost + // `…option.location.record` with the option. The control row is a key the + // dropdown still offers, so a `t()` that returned every key unchanged + // could not pass this case. + it('has no leftover translation for the removed `record` option in either locale', () => { + const key = 'engine.inspector.pageBlock.option.location.record'; + expect(t(key, 'en-US')).toBe(key); + expect(t(key, 'zh-CN')).toBe(key); + const control = 'engine.inspector.pageBlock.option.location.record_page'; + expect(t(control, 'en-US')).toBe('Record page'); + expect(t(control, 'zh-CN')).toBe('记录页'); + }); }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/block-config.ts b/ui/packages/app-shell/src/views/metadata-admin/previews/block-config.ts index aae9aca0118..54a5b3f40ea 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/block-config.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/block-config.ts @@ -75,6 +75,30 @@ * (`designer.canvas.addSection`). One key per meaning is why that is expressible. */ +import type { RecordQuickActionsLocation } from '@objectstack/spec/ui'; + +/** + * The `record:quick_actions` location dropdown, one label key per place the + * spec lets the bar be set to (objectstack#38045, maintainer ruling A). + * + * Typed as a TOTAL `Record`, the + * `ActionDefaultInspector` `LOCATION_LABELS` mechanism: the compiler holds the + * options equal to the set the spec accepts. A location the bar gains is a + * missing-key error here, and one it refuses is an excess-property error — + * which is what removed `record`: the word says what an ACTION acts on (the + * record page and each list row), a bar sits in one place, and a bar at + * `record` drew only the actions that declare `record` literally. The bar's + * default, `record_page`, already draws those. Insertion order is the display + * order (the renderer default first), not the spec's declaration order. + */ +const QUICK_ACTIONS_LOCATION_LABELS: Record = { + record_page: 'engine.inspector.pageBlock.option.location.record_page', + record_row: 'engine.inspector.pageBlock.option.location.record_row', + record_section: 'engine.inspector.pageBlock.option.location.record_section', + record_related: 'engine.inspector.pageBlock.option.location.record_related', + list: 'engine.inspector.pageBlock.option.location.list', +}; + /** Where a field/field-list picker resolves its object from: * - 'page' — the record page's bound object (draft.object) * - 'self' — a sibling property on the same block (objectProp) @@ -628,18 +652,12 @@ export const BLOCK_CONFIG: Record = { name: 'location', label: 'engine.inspector.pageBlock.field.record:quick_actions.location', kind: 'select', - options: [ - { value: 'record_page', label: 'engine.inspector.pageBlock.option.location.record_page' }, - { value: 'record', label: 'engine.inspector.pageBlock.option.location.record' }, - { value: 'record_row', label: 'engine.inspector.pageBlock.option.location.record_row' }, - { value: 'record_section', label: 'engine.inspector.pageBlock.option.location.record_section' }, - { value: 'record_related', label: 'engine.inspector.pageBlock.option.location.record_related' }, - { value: 'list', label: 'engine.inspector.pageBlock.option.location.list' }, - // No `global_nav` option: the location was retired from the spec's - // `ACTION_LOCATIONS` in @objectstack/spec 17.0.0-rc.6 (objectstack#6888). - // Offering it here would let the designer author a value the schema now - // rejects by name. Pinned negatively in `__tests__/block-config.test.ts`. - ], + // Exactly the places the spec accepts for this bar: no `record` + // (objectstack#38045) and no retired `global_nav` (objectstack#6888) — + // offering either would let the designer author a value the schema + // refuses by name. Pinned both ways in `__tests__/block-config.test.ts`. + options: (Object.keys(QUICK_ACTIONS_LOCATION_LABELS) as RecordQuickActionsLocation[]) + .map((value) => ({ value, label: QUICK_ACTIONS_LOCATION_LABELS[value] })), }, ], diff --git a/ui/packages/app-shell/src/views/metadata-admin/studio-locale.i18n.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/studio-locale.i18n.test.tsx index 1f9971c49a0..8213d724824 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/studio-locale.i18n.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/studio-locale.i18n.test.tsx @@ -37,7 +37,8 @@ const SAMPLE_KEYS = [ 'engine.studio.publish', 'engine.studio.saveDraft', 'engine.studio.cancel', - 'engine.studio.menu.orgFlows', + // objectstack#38150 — `engine.studio.menu.orgFlows` stood here; it retired with the package-less scope. + 'engine.studio.menu.allTypes', 'engine.studio.menu.owd', 'engine.studio.app.create', 'engine.studio.pkg.new', diff --git a/ui/packages/app-shell/src/views/metadata-admin/studioListSource.ts b/ui/packages/app-shell/src/views/metadata-admin/studioListSource.ts index 8b2fe18fb3a..187ff2023a0 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/studioListSource.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/studioListSource.ts @@ -5,35 +5,54 @@ * (objectstack#37918, the maintainer's decision 7 on epic objectstack#37424): * 系统自带 / 已修改 / 新建 — system-shipped, modified, new. * - * Read from two facts the list already has, and only those: + * Read from three facts, and only those: * * - the row's customization mark (`customizationMarks.ts`), from the base's * served customization read: a served override is "customized", any other * item of the base's `.custom` pair is "added" (ADR-0146 D3); + * - whether the row's package is one the author can write (objectstack#38150, + * the ruling on objectstack#38061): the listed package's `writable` verdict, + * the server's own ({@link useWritablePackageIds}). An item of such a + * package was made here, so it reads "new" whatever its provenance says; * - the row's provenance (`classifyProvenance` in `ResourceListPage`): a row * authored at runtime, or in a customization package, is `runtime`. * * A served override is served under the BASE's id, so its provenance reads - * `artifact`; the mark is what says it was modified. That is why the Studio - * list's source filter cannot read the provenance alone: its two narrowings - * — "modified and new", "system-shipped" — are {@link studioListSource}'s two - * values, written to the list's address as the existing `source` values - * (`metadataListState.ts`, unchanged), and the detail's ‹ › order reads the - * same function (`useListOrderedNames.ts`), so the two cannot disagree. + * `artifact`; the mark is what says it was modified. An item of a package + * authored in Studio is served under that package's id, so its provenance + * reads `artifact` too; the package's verdict is what says it is new. That is + * why the Studio list's source filter cannot read the provenance alone: its + * two narrowings — "modified and new", "system-shipped" — are + * {@link studioListSource}'s two values, written to the list's address as the + * existing `source` values (`metadataListState.ts`, unchanged), and the + * detail's ‹ › order reads the same function (`useListOrderedNames.ts`), so + * the two cannot disagree. + * + * Setup's list is not this: it reads the provenance as served, and neither + * the mark nor the package's verdict. */ +import * as React from 'react'; import type { CustomizationMarkKind } from '../studio-design/customizationMarks.js'; +import { fetchListedPackageManifests } from '../studio-design/packages-io.js'; /** What the Studio list's Source column says of a row. */ export type StudioSourceKind = 'system' | 'modified' | 'new'; -/** The kind of a row: its mark first, then its provenance. */ +/** + * The kind of a row: its mark first, then its package's verdict, then its + * provenance. `inWritablePackage` is required, never defaulted: a caller that + * left it out would read an authored package's item as system-shipped while + * the caller beside it read "new". + */ export function studioSourceKind( provenance: 'artifact' | 'runtime', mark: CustomizationMarkKind | null, + inWritablePackage: boolean, ): StudioSourceKind { if (mark === 'customized') return 'modified'; if (mark === 'added') return 'new'; + if (inWritablePackage) return 'new'; return provenance === 'runtime' ? 'new' : 'system'; } @@ -51,3 +70,65 @@ export const STUDIO_SOURCE_KEY: Readonly> = Obj modified: 'engine.list.source.modified', new: 'engine.list.source.new', }); + +/** + * The packages the author can write, as the Studio list holds them: + * + * - `off`: the list is not Studio's, and nothing was asked; + * - `loading`: the package list has not answered yet; + * - `read`: the ids whose listed verdict is `writable`; + * - `failed`: the package list could not be read. + * + * Only `read` names a package. In every other state no row is in a writable + * package, and a row reads as its mark and its provenance say. + */ +export type WritablePackageIds = + | { status: 'off' } + | { status: 'loading' } + | { status: 'read'; ids: ReadonlySet } + | { status: 'failed' }; + +const OFF: WritablePackageIds = Object.freeze({ status: 'off' }); +const LOADING: WritablePackageIds = Object.freeze({ status: 'loading' }); +const FAILED: WritablePackageIds = Object.freeze({ status: 'failed' }); + +/** + * The ids of the listed packages the author can write, read once per mount + * while `enabled`. The verdict is the package list's own `writable`, which + * the server computes per read (`packages-io.ts`), and the request is the one + * the other readers of that list share. + * + * A failed read is not reported here: the Studio surface reports its package + * list once, and the list page still draws, each row read from its mark and + * its provenance. + */ +export function useWritablePackageIds(enabled: boolean): WritablePackageIds { + const [answer, setAnswer] = React.useState(null); + React.useEffect(() => { + if (!enabled) return; + let cancelled = false; + fetchListedPackageManifests().then( + (manifests) => { + if (cancelled) return; + const ids = new Set(); + for (const listed of manifests.values()) if (listed.writable) ids.add(listed.id); + setAnswer({ status: 'read', ids }); + }, + () => { + if (!cancelled) setAnswer(FAILED); + }, + ); + return () => { + cancelled = true; + }; + }, [enabled]); + if (!enabled) return OFF; + return answer ?? LOADING; +} + +/** Whether a served item belongs to a package the author can write. */ +export function isWritablePackageItem(item: Record, writable: WritablePackageIds): boolean { + if (writable.status !== 'read') return false; + const packageId = item._packageId; + return typeof packageId === 'string' && writable.ids.has(packageId); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts b/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts index a6e41f4d4f7..689e9573efd 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts @@ -34,9 +34,10 @@ import { holdersOfName, servedHolderOf } from './permission-set-holder.js'; import { usePackageCustomizations } from '../studio-design/CustomizationMark.js'; import { customizationMarkOf, customizationTotal } from '../studio-design/customizationMarks.js'; import { classifyProvenance } from './ResourceListPage.js'; +import { isPackageLessItem } from '../studio-design/studioScope.js'; import { useListChangedAt } from './listChangedAt.js'; import { useInSetupApp } from '../../console/setupApp.js'; -import { studioListSource, studioSourceKind } from './studioListSource.js'; +import { isWritablePackageItem, studioListSource, studioSourceKind, useWritablePackageIds } from './studioListSource.js'; import { decodeListState, hasListContext, @@ -49,8 +50,8 @@ import { export interface ListOrderedNames { /** * `loading` until the list — and any read its filters need (the - * customization read, the activation ledger) — has answered; `error` when - * the list read failed. + * customization read, the package list, the activation ledger) — has + * answered; `error` when the list read failed. */ status: 'loading' | 'ready' | 'error'; /** The names in list order; empty until `ready`. */ @@ -101,12 +102,21 @@ export function useListOrderedNames(type: string): ListOrderedNames { const locale = useMetadataLocale(); const activePackage = envScope ? null : host ? host.packageId : urlPackage; const unscoped = envScope || activePackage === null; + // objectstack#38150 — the cross-package leg (`ResourceListPage`'s `allLeg`) offers "Loose". + const looseOffered = !!host && host.packageId === null && !envScope; const pairId = React.useMemo(() => { if (!host?.packageId || envScope) return null; const pair = customizationPackageId(host.packageId); return pair.ok ? pair.value : null; }, [host?.packageId, envScope]); const customizations = usePackageCustomizations(host?.packageId ?? null); + // objectstack#38150 — the Studio list's Source reads a row's customization + // mark and whether its package is one the author can write, so both reads + // are asked for, and waited on, only when the order filters on that Source + // (`artifact` / `runtime`). "Loose" (`source=loose`) never reads it: its + // filter asks only whether a row names a package (`isPackageLessItem`). + const sourceNarrowed = studioList && (state.source === 'artifact' || state.source === 'runtime'); + const writablePackages = useWritablePackageIds(sourceNarrowed); const [rows, setRows] = React.useState<{ type: string; rows: Row[] } | 'error' | null>(null); React.useEffect(() => { @@ -155,9 +165,10 @@ export function useListOrderedNames(type: string): ListOrderedNames { return React.useMemo((): ListOrderedNames => { if (rows === 'error') return { status: 'error', names: EMPTY, fromList }; if (rows === null || rows.type !== type) return { status: 'loading', names: EMPTY, fromList }; - if ((state.customizedOnly || (studioList && state.source !== 'all')) && customizations.status === 'loading') { + if ((state.customizedOnly || sourceNarrowed) && customizations.status === 'loading') { return { status: 'loading', names: EMPTY, fromList }; } + if (writablePackages.status === 'loading') return { status: 'loading', names: EMPTY, fromList }; if (needsLedger && ledger === null) return { status: 'loading', names: EMPTY, fromList }; if (state.sort.key === 'changed' && changedAt === null) return { status: 'loading', names: EMPTY, fromList }; @@ -184,7 +195,12 @@ export function useListOrderedNames(type: string): ListOrderedNames { name: (row) => String(row.item[primaryKey] ?? ''), label: (row) => (typeof row.item.label === 'string' ? row.item.label : undefined), matches: (row, query) => matchesQuery(row.item, query, searchKey.split('\n')), - source: (row) => (studioList ? studioListSource(studioSourceKind(row.source, markOf(row))) : row.source), + source: (row) => + studioList + ? studioListSource(studioSourceKind(row.source, markOf(row), isWritablePackageItem(row.item, writablePackages))) + : row.source, + // objectstack#38150 — the list offers "Loose" on the area's cross-package leg alone. + ...(looseOffered ? { loose: (row: Row) => isPackageLessItem(row.item) } : {}), changedAt: (row) => changedAt?.[String(row.item[primaryKey] ?? '')], ...(customizedOffered && !studioList ? { customized: (row: Row) => markOf(row) !== null } : {}), ...(envScope && hasCatalogActivation(type) @@ -201,5 +217,5 @@ export function useListOrderedNames(type: string): ListOrderedNames { }; return { status: 'ready', names: orderedListNames(scoped, state, read, locale), fromList }; // Keyed on the config members read, never on `config`, rebuilt every render. - }, [rows, changedAt, type, locale, state, fromList, customizations, needsLedger, ledger, envScope, unscoped, activePackage, pairId, primaryKey, listFilter, bundleMemberField, searchKey, studioList]); + }, [rows, changedAt, type, locale, state, fromList, customizations, needsLedger, ledger, envScope, unscoped, activePackage, pairId, primaryKey, listFilter, bundleMemberField, searchKey, studioList, looseOffered, sourceNarrowed, writablePackages]); } diff --git a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx index e40a417842f..0c25b04b66a 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx @@ -68,6 +68,7 @@ import { expressionSource, writeExpressionSource } from './inspectors/expression import { humanizeKey } from './inspectors/json-schema-to-fields.js'; import { datasetSelectOptions } from './inspectors/dataset-picker-options.js'; import type { DatasetCatalogEntry } from './previews/useDatasetCatalog.js'; +import { RETRIEVAL_MODES, type KnowledgeStoreRetrieval } from './knowledgeRetrieval.js'; import { useMonacoFallback } from './useMonacoFallback.js'; import { DraftChip } from '../studio-design/StudioDraftMark.js'; import { ContextPackRelatedEntries, isContextPackEntrySchema } from './ContextPackRelatedEntries.js'; @@ -341,6 +342,14 @@ export interface WidgetContext { * every render. */ loadCapabilityAudience?: () => Promise; + /** + * objectstack#38692 phase 1a — the store the knowledge source on screen binds + * to and the retrieval modes it reports, for the `knowledge-retrieval-mode` + * picker (`knowledgeRetrieval.ts`). `ResourceEditPage` loads it only for a + * form that declares the hint. Absent reads as {@link NOT_ASKED}: the picker + * offers the three modes. + */ + knowledgeRetrieval?: LoadState; } /* Stable empties for the arms that have no catalog to offer yet — `idle` and @@ -843,6 +852,87 @@ function RefDatasetWidget({ id, ariaLabelledBy, required, value, onChange, readO ); } +/* -------------------------------------------------------------------------- */ +/* knowledge-retrieval-mode — a knowledge source's `source.retrieval.mode` */ +/* -------------------------------------------------------------------------- */ + +/** The Select's value for "no mode": Radix refuses an empty-string item. */ +const STORE_DEFAULT = '__store_default__'; + +/** + * The retrieval-mode picker of a knowledge source (objectstack#38692 phase + * 1a). It offers the modes the source's store runs, read from + * `context.knowledgeRetrieval`, and a blank choice that names the store's + * default ("Store default (hybrid)"); the value written is the mode, or + * `undefined` for the default. + * + * - LOADED, the store reports modes — those, in the order it reports them; + * - LOADED, the store reports none (memory) — the default alone, and the + * sentence that the store declares no modes; a mode already written is kept + * as its own option, flagged, so the author sees what the save will refuse; + * - LOADED, the store is not mounted, or the read was refused or failed, or + * no host feeds it — the three modes, and the save judges the choice; + * - LOADING — the stored mode in a disabled control. + */ +function KnowledgeRetrievalModeWidget({ id, ariaLabelledBy, required, value, onChange, readOnly, context }: WidgetProps) { + const locale = useMetadataLocale(); + const state = context?.knowledgeRetrieval ?? NOT_ASKED; + const current = typeof value === 'string' && value ? value : ''; + if (isLoading(state)) { + return ( + + ); + } + const store = state.status === 'loaded' && state.data.mounted ? state.data : undefined; + const undeclared = store !== undefined && store.modes === undefined; + const offered: readonly string[] = undeclared ? [] : (store?.modes ?? RETRIEVAL_MODES); + const modeLabel = (mode: string) => t(`engine.form.retrievalMode.${mode}`, locale); + const defaultLabel = + store?.default !== undefined + ? tFormat('engine.form.retrievalMode.defaultIs', locale, { mode: modeLabel(store.default) }) + : t('engine.form.retrievalMode.default', locale); + const kept = current !== '' && !offered.includes(current); + return ( +
+ + {undeclared && ( +

+ {tFormat('engine.form.retrievalMode.undeclared', locale, { store: store?.adapter ?? '' })} +

+ )} +
+ ); +} + /* -------------------------------------------------------------------------- */ /* ref-multi: — pick declared registry items by name, as a list */ /* -------------------------------------------------------------------------- */ @@ -3820,6 +3910,7 @@ export const WIDGETS = { 'secret': SecretWidget, 'dynamic-config': DynamicConfigWidget, 'field-history': FieldHistoryWidget, + 'knowledge-retrieval-mode': KnowledgeRetrievalModeWidget, } satisfies Record; /** Every key of {@link WIDGETS}, as a literal union. */ @@ -3935,6 +4026,7 @@ export const WIDGET_LABELLING: Record = { 'secret': 'control', 'dynamic-config': 'group', 'field-history': 'control', + 'knowledge-retrieval-mode': 'control', }; /** diff --git a/ui/packages/app-shell/src/views/objectViewHeaderToolbar.ts b/ui/packages/app-shell/src/views/objectViewHeaderToolbar.ts index 091357cae96..8c0fed25132 100644 --- a/ui/packages/app-shell/src/views/objectViewHeaderToolbar.ts +++ b/ui/packages/app-shell/src/views/objectViewHeaderToolbar.ts @@ -25,8 +25,8 @@ export function useObjectViewHeaderToolbar({ }) { // objectui#12462 (ruling A-narrow) — the header does not draw a duplicate of // the selection bar. The bar is the list toolbar in its selection mode: a - // `list` action the ACTIVE view wires to it (`bulkActions`, or a - // `bulkActionDefs` entry) is still drawn at its declared placement, on the + // `list` action on it (placed at `selection` too, objectstack#36496, or + // named by an ACTIVE view's `bulkActionDefs` entry) is still drawn at its declared placement, on the // rows it acts on, so the header's permanent copy is the duplicate. Only a // RECORD-SCOPED action leaves (`isRecordScopedAction`: it also mounts on // rows or records). Launched from the header it runs on exactly one ticked @@ -34,19 +34,20 @@ export function useObjectViewHeaderToolbar({ // its header entry, because it can run with nothing selected and the bar // cannot. Nothing else moves: the bar reads the same view keys itself. // - // The names are the ones `ObjectGrid` folds into its bar from the keys this - // page relays to it (see `renderListView`): every non-empty `bulkActions` - // name except `delete`, which the grid routes to its built-in bulk delete - // rather than to an object action, and the `name` of every `bulkActionDefs` - // entry the grid can render. Keyed on a string of the names, not on + // The bar's actions are the object's placed at `selection` (read off each + // action here) and the `name` of every `bulkActionDefs` entry of the active + // view the grid can render. Keyed on a string of the names, not on // `activeView`, which is a fresh object on every render while a draft is // open (AGENTS.md #10). const bulkWiredNamesKey = bulkWiredActionNamesKey(activeView); const headerToolbarActions = useMemo(() => { const wired = new Set(JSON.parse(bulkWiredNamesKey) as string[]); - if (wired.size === 0) return localizedToolbarActions; return localizedToolbarActions.filter( - (a: any) => !(typeof a?.name === 'string' && wired.has(a.name) && isRecordScopedAction(a)), + (a: any) => !( + typeof a?.name === 'string' + && (wired.has(a.name) || actionRendersAt(a, 'selection')) + && isRecordScopedAction(a) + ), ); }, [localizedToolbarActions, bulkWiredNamesKey]); diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index 52f8673d60b..7d1574fa970 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -943,15 +943,12 @@ export function useObjectViewListRenderer({ .map((a: any) => localizeActionTexts(objectDef.name, a)) : []), /** - * Selection-bar actions. Unlike `rowActionDefs` above, these are - * NOT resolved here: `ObjectGrid` is the single convergence point - * of all three list callers (this view, plugin-view's ObjectView - * and plugin-list's ListView), so it resolves each `bulkActions` - * name against `objectDef.actions` and promotes it into the def - * list itself (`resolveBulkActions`, objectui#3002). What we pass - * through is the view author's own declaration. + * Selection-bar defs. The bar's actions are the object's placed at + * `selection` (objectstack#36496), which `ObjectGrid`, the single + * convergence point of all three list callers, reads off the + * object itself (`selectionBarActions`). What we pass through is + * the view author's own inline defs. */ - bulkActions: viewDef.bulkActions ?? listSchema.bulkActions, bulkActionDefs: (viewDef as any).bulkActionDefs ?? (listSchema as any).bulkActionDefs, sharing: viewDef.sharing ?? listSchema.sharing, // objectui#13089 — the Add button `ListView` draws from diff --git a/ui/packages/app-shell/src/views/objectViewListRoute.deferredAuthoring-37444.test.tsx b/ui/packages/app-shell/src/views/objectViewListRoute.deferredAuthoring-37444.test.tsx new file mode 100644 index 00000000000..684dfa5c5c6 --- /dev/null +++ b/ui/packages/app-shell/src/views/objectViewListRoute.deferredAuthoring-37444.test.tsx @@ -0,0 +1,162 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37444 — the object list route loads no authoring code before its + * first screen. + * + * ## What changed, and what this file pins about it + * + * `objectViewViewCrud.tsx` and `objectViewViewSharing.ts` imported the package + * ask (`./metadata-admin/PackageCreateAsk`) and the designer strings + * (`./metadata-admin/i18n`) statically, and the ask's dialog was rendered, + * closed, on every list. Through them the list route's graph held the package + * page's create dialog, `SchemaForm` and the Studio catalogue. The view config + * panel and the create-view dialog, both `lazy()`, were also drawn closed on + * every list, so their chunks were fetched before the list's first screen too. + * The bundle half (which chunks a list load fetches, and the LCP it costs) is + * measured on the built console and recorded on the PR. What a unit test CAN + * pin is that none of those modules is evaluated until someone asks for it. + * + * ## The instrument: counted mock factories + * + * `vi.mock(path, factory)` runs `factory` the first time the module is + * imported, and not before. Each count below is the unit-level image of "its + * chunk was fetched". A STATIC import of one of them anywhere in + * `ObjectView.tsx`'s graph runs its factory while this file imports + * `ObjectView`, before any case starts, and the first case reds. + * + * ⚠️ The module registry is per FILE, so a load cannot be undone between + * cases. The case that needs every module unloaded runs first, and each later + * case asserts the count it STARTS from, so a reorder fails loudly. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { describe, it, expect, vi } from 'vitest'; +import { act, render, screen, waitFor, fireEvent } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; + +const loads = vi.hoisted(() => ({ + packageAsk: 0, + packagesPage: 0, + schemaForm: 0, + designerStrings: 0, + viewConfigPanel: 0, + createViewDialog: 0, +})); + +const toastError = vi.hoisted(() => vi.fn()); + +vi.mock('sonner', async (importOriginal) => ({ + ...(await importOriginal>()), + toast: { error: toastError, success: vi.fn(), info: vi.fn(), warning: vi.fn(), message: vi.fn() }, +})); + +vi.mock('../providers/MetadataProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadata: () => ({ apps: [] }), +})); + +// A stand-in dialog: open, it offers one package; the case answers with it. +vi.mock('./metadata-admin/PackageCreateAsk', () => { + loads.packageAsk += 1; + return { + PackageCreateAskDialog: ({ open, onAnswer }: { open: boolean; onAnswer: (id: string | null) => void }) => ( +
+
+ ), + runtimeCreateRefusalText: (notSaved: { reason: string }, kind: string, locale: string) => + notSaved.reason === 'cancelled' ? null : `refused ${kind} in ${locale}`, + }; +}); + +vi.mock('./metadata-admin/PackagesPage', async (importOriginal) => { + loads.packagesPage += 1; + return importOriginal>(); +}); + +vi.mock('./metadata-admin/SchemaForm', async (importOriginal) => { + loads.schemaForm += 1; + return importOriginal>(); +}); + +vi.mock('./metadata-admin/i18n', async (importOriginal) => { + loads.designerStrings += 1; + return importOriginal>(); +}); + +vi.mock('./ViewConfigPanel', async (importOriginal) => { + loads.viewConfigPanel += 1; + return importOriginal>(); +}); + +vi.mock('./CreateViewDialog', async (importOriginal) => { + loads.createViewDialog += 1; + return importOriginal>(); +}); + +// `objectViewViewCrud` reaches a dynamic `import('@objectstack/lint')`: pay its +// load at collection, never inside a case's clocked window. +import '@objectstack/lint'; +import './ObjectView'; +import { reportViewNotSaved, useRuntimeCreateApp } from './objectViewViewCrud'; +import { RuntimeCreateNotSavedError } from './runtime-metadata-persistence'; + +type CreateApp = ReturnType; + +function AskHost({ onApp }: { onApp: (app: CreateApp) => void }) { + const app = useRuntimeCreateApp(); + onApp(app); + return app.askDialog; +} + +describe('objectstack#37444 — the object list route loads no authoring code before it is asked', () => { + it('importing the list route evaluates none of the authoring modules', () => { + expect(loads).toEqual({ + packageAsk: 0, + packagesPage: 0, + schemaForm: 0, + designerStrings: 0, + viewConfigPanel: 0, + createViewDialog: 0, + }); + }); + + it('the package ask loads its dialog on the first ask, answers it, and keeps it mounted closed', async () => { + expect(loads.packageAsk).toBe(0); + let app: CreateApp | null = null; + render( + + { app = next; }} /> + , + ); + // Nothing asked yet: the dialog module is not loaded and nothing is drawn. + expect(loads.packageAsk).toBe(0); + expect(screen.queryByTestId('stub-package-ask')).toBeNull(); + + let answer: Promise | undefined; + act(() => { + answer = app!.askPackage({ preselect: null }); + }); + await waitFor(() => expect(screen.getByTestId('stub-package-ask')).toHaveAttribute('data-open', 'true')); + expect(loads.packageAsk).toBe(1); + + fireEvent.click(screen.getByTestId('stub-package-ask-pick')); + await expect(answer!).resolves.toBe('com.example.pick'); + // Answered, it closes but stays mounted, so it closes the way it always did. + await waitFor(() => expect(screen.getByTestId('stub-package-ask')).toHaveAttribute('data-open', 'false')); + }); + + it('a refused view create says why once its words have loaded; a cancelled one says nothing', async () => { + toastError.mockClear(); + expect(reportViewNotSaved(new Error('other'), 'en')).toBe(false); + expect(reportViewNotSaved(new RuntimeCreateNotSavedError('system-app'), 'zh-CN')).toBe(true); + // The words are in the designer strings, loaded on the refusal: the toast follows. + await waitFor(() => expect(toastError).toHaveBeenCalledTimes(1)); + expect(toastError).toHaveBeenCalledWith('refused view in zh-CN'); + expect(reportViewNotSaved(new RuntimeCreateNotSavedError('cancelled'), 'en')).toBe(true); + await act(() => new Promise((resolve) => setTimeout(resolve, 50))); + expect(toastError).toHaveBeenCalledTimes(1); + }); +}); diff --git a/ui/packages/app-shell/src/views/objectViewTabs.ts b/ui/packages/app-shell/src/views/objectViewTabs.ts index 8d6b83ba30a..bb96da25882 100644 --- a/ui/packages/app-shell/src/views/objectViewTabs.ts +++ b/ui/packages/app-shell/src/views/objectViewTabs.ts @@ -80,27 +80,18 @@ export function defaultListColumnsFromObject( } /** - * The action names a list view wires to its selection bar, as `ObjectGrid` - * folds them from the two keys this page relays to it (`resolveBulkActions` in - * `@object-ui/plugin-grid`), sorted and JSON-encoded so a memo keys on a - * primitive (objectui#12462). - * - * - `bulkActions`: every non-empty name except `delete` (any case). The grid - * sends `delete` to its built-in bulk delete, never to an object action of - * that name, so the bar does not carry such an action. - * - `bulkActionDefs`: the `name` of every entry the grid can render, which is - * an object with a non-empty string `name` (`isUsableBulkActionDef`). - * - * The legacy `batchActions` spelling is not read: this page never relays it. + * The action names a list view wires to its selection bar itself, as + * `ObjectGrid` folds them from the key this page relays to it + * (`resolveBulkActions` in `@object-ui/plugin-grid`), sorted and JSON-encoded + * so a memo keys on a primitive (objectui#12462): the `name` of every + * `bulkActionDefs` entry the grid can render, which is an object with a + * non-empty string `name` (`isUsableBulkActionDef`). The object's actions + * placed at `selection` are the bar's on every view (objectstack#36496); the + * header reads them off each action. */ export function bulkWiredActionNamesKey(view: unknown): string { - const { bulkActions, bulkActionDefs } = (view ?? {}) as { bulkActions?: unknown; bulkActionDefs?: unknown }; + const { bulkActionDefs } = (view ?? {}) as { bulkActionDefs?: unknown }; const names = new Set(); - if (Array.isArray(bulkActions)) { - for (const name of bulkActions) { - if (typeof name === 'string' && name !== '' && name.toLowerCase() !== 'delete') names.add(name); - } - } if (Array.isArray(bulkActionDefs)) { for (const def of bulkActionDefs) { const name = def && typeof def === 'object' ? (def as { name?: unknown }).name : undefined; diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx index f3d42e95239..a5cd5c3716b 100644 --- a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx @@ -8,12 +8,12 @@ * component reads the returned handlers. */ -import { useCallback, useEffect, useMemo, useRef, type Dispatch, type ReactElement, type SetStateAction } from 'react'; +import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type ReactElement, type SetStateAction } from 'react'; import { useParams, type useNavigate } from 'react-router-dom'; import { formatMetadataError } from '@object-ui/data-objectstack'; import { viewSaveRefusalText } from './viewSaveRefusal.js'; import { toast } from 'sonner'; -import type { useObjectTranslation } from '@object-ui/i18n'; +import { useObjectTranslation } from '@object-ui/i18n'; import type { useObjectListLayout } from './listLayoutStore.js'; import { PREVIEW_QUERY_FLAG, PREVIEW_QUERY_VALUE } from '../preview/PreviewModeContext.js'; import type { usePreviewDrafts } from '../preview/PreviewModeContext.js'; @@ -21,8 +21,7 @@ import { isSavedViewId } from '../utils/viewIdentity.js'; import type { useConsoleActionRuntime } from '../hooks/useConsoleActionRuntime.js'; import type { useMetadataClient } from './metadata-admin/useMetadata.js'; import { persistRuntimeMetadata, createRuntimeMetadata, isRuntimeCreateNotSaved, saveAndPublishRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js'; -import { runtimeCreateRefusalText, usePackageCreateAsk } from './metadata-admin/PackageCreateAsk.js'; -import { useMetadataLocale } from './metadata-admin/i18n.js'; +import type { PackageAskRequest } from './metadata-admin/PackageCreateAsk.js'; import type { RuntimeCreateApp, SaveAndPublishOutcome } from './runtime-metadata-persistence.js'; import type { DraftVersionGuard } from './metadata-admin/draftVersionGuard.js'; import { draftBarPackageOf } from '../preview/DraftPreviewBar.js'; @@ -35,6 +34,58 @@ import type { InPlaceViewRequest } from './CreateViewDialog.js'; import { buildInPlaceViewConfig, type PersonalViewListState } from './personalViews.js'; import { FILTER_FOLD_REFUSAL_KEYS } from './viewFilterFold.js'; +/** + * objectstack#37444 — the package ask's dialog, loaded the first time it is asked. + * + * `usePackageCreateAsk` (`./metadata-admin/PackageCreateAsk.tsx`) renders its + * dialog closed on every render, and that module imports the package page's + * create dialog, `SchemaForm` and the Studio catalogue. Imported here it put + * all of them in the object list route's graph, before the first screen of a + * page that almost never asks. This is the same promise contract (`ask()` + * opens and resolves with the chosen or created id, or `null` on Cancel; a + * second `ask()` answers the first `null`; an unmount answers an open ask) + * with the dialog behind `lazy()`: nothing of it loads until the first ask, + * and once loaded it stays mounted so it closes the way it always did. + */ +const PackageCreateAskDialog = lazy(() => + import('./metadata-admin/PackageCreateAsk.js').then((m) => ({ default: m.PackageCreateAskDialog })), +); + +function useDeferredPackageCreateAsk(): { + ask: (request?: PackageAskRequest) => Promise; + dialog: ReactElement; +} { + const [pending, setPending] = useState<(PackageAskRequest & { resolve: (id: string | null) => void }) | null>(null); + const [asked, setAsked] = useState(false); + const pendingRef = useRef(pending); + pendingRef.current = pending; + const ask = useCallback( + (request: PackageAskRequest = {}) => + new Promise((resolve) => { + pendingRef.current?.resolve(null); + setAsked(true); + setPending({ ...request, resolve }); + }), + [], + ); + useEffect(() => () => pendingRef.current?.resolve(null), []); + const onAnswer = useCallback((id: string | null) => { + pendingRef.current?.resolve(id); + setPending(null); + }, []); + const dialog = asked ? ( + + + + ) : <>; + return { ask, dialog }; +} + /** * objectstack#35624 — the app a view created here is saved into * (`RuntimePersistCtx.app`): the routed app's package by the draft preview @@ -47,7 +98,7 @@ export function useRuntimeCreateApp(): RuntimeCreateApp & { askDialog: ReactElem const { appName } = useParams(); const { apps } = useMetadata(); const packageId = draftBarPackageOf(appName, apps as Parameters[1]); - const { ask, dialog } = usePackageCreateAsk(); + const { ask, dialog } = useDeferredPackageCreateAsk(); // Memoised for cost only: the create reads the fields, never the identity. return useMemo( () => ({ @@ -63,11 +114,25 @@ export function useRuntimeCreateApp(): RuntimeCreateApp & { askDialog: ReactElem * objectstack#38149 — a view create that was not saved: a cancelled ask says * nothing and keeps the dialog open; a refused one says why and where to go. * `true` when `err` was such a create (the caller answers "not saved"). + * + * `locale` is the session's i18n language or a designer locale already + * derived from it (`designerLocaleOf` answers both the same). objectstack#37444: + * the refusal's words live in the Studio catalogue, so they are loaded here, on + * the refusal, rather than with the list page; the toast follows once they land. */ export function reportViewNotSaved(err: unknown, locale: string): boolean { if (!isRuntimeCreateNotSaved(err)) return false; - const text = runtimeCreateRefusalText(err, 'view', locale); - if (text) toast.error(text); + void Promise.all([ + import('./metadata-admin/PackageCreateAsk.js'), + import('./metadata-admin/i18n.js'), + import('@object-ui/i18n/namespaces/studio'), + ]).then(async ([{ runtimeCreateRefusalText }, { designerLocaleOf }, { loadStudioCatalogue }]) => { + const designerLocale = designerLocaleOf(locale); + // A catalogue that fails to load leaves the built-in English answer. + await loadStudioCatalogue(designerLocale).catch(() => undefined); + const text = runtimeCreateRefusalText(err, 'view', designerLocale); + if (text) toast.error(text); + }); return true; } @@ -113,7 +178,7 @@ export function useObjectViewViewCrud({ baseView: ReturnType[number]; }) { const createApp = useRuntimeCreateApp(); - const locale = useMetadataLocale(); + const { language: locale } = useObjectTranslation(); // objectui#12504 — no toolbar control writes the shared view. The sort and // the columns are the list's draft (`./listDraftStore.ts`), the widths and // the density the reader's layout in this browser (`listLayout`), and diff --git a/ui/packages/app-shell/src/views/objectViewViewSharing.ts b/ui/packages/app-shell/src/views/objectViewViewSharing.ts index d3efaf704d0..1996f30e682 100644 --- a/ui/packages/app-shell/src/views/objectViewViewSharing.ts +++ b/ui/packages/app-shell/src/views/objectViewViewSharing.ts @@ -25,11 +25,10 @@ import { useCallback } from 'react'; import { toast } from 'sonner'; -import type { useObjectTranslation } from '@object-ui/i18n'; +import { useObjectTranslation } from '@object-ui/i18n'; import { buildAddViewSpec } from './objectViewTabs.js'; -import { isRuntimeCreateNotSaved, saveAndPublishRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js'; -import { runtimeCreateRefusalText } from './metadata-admin/PackageCreateAsk.js'; -import { useMetadataLocale } from './metadata-admin/i18n.js'; +import { saveAndPublishRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js'; +import { reportViewNotSaved } from './objectViewViewCrud.js'; import type { RuntimeCreateApp, RuntimePersistCtx } from './runtime-metadata-persistence.js'; import { viewSaveRefusalText } from './viewSaveRefusal.js'; @@ -78,7 +77,7 @@ export function useViewSharing({ refresh: () => void; t: TFn; }): UseViewSharing { - const locale = useMetadataLocale(); + const { language } = useObjectTranslation(); const openView = useCallback((id: string) => { if (routeViewId) navigate(`../${id}`, { relative: 'path' }); else navigate(`view/${id}`); @@ -109,11 +108,7 @@ export function useViewSharing({ return true; } catch (err) { // objectstack#38149 — no package took it: nothing was written. - if (isRuntimeCreateNotSaved(err)) { - const text = runtimeCreateRefusalText(err, 'view', locale); - if (text) toast.error(text); - return false; - } + if (reportViewNotSaved(err, language)) return false; console.error('[ObjectView] Failed to create a shared view:', err); toast.error(t('form.saveError'), { description: viewSaveRefusalText(err, t), @@ -121,7 +116,7 @@ export function useViewSharing({ }); return false; } - }, [metadataClient, objectDef, objectName, publishNew, refresh, openView, t, locale]); + }, [metadataClient, objectDef, objectName, publishNew, refresh, openView, t, language]); return { createShared }; } diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts index 9d40e9949ee..54021b522ce 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts @@ -55,8 +55,10 @@ import { overrideDraftBody } from './studio-design/customizeOverride.js'; * `PageSchema`) joins the original three (#1541): a record page is edited in * the browser and staged/published through the same `/meta` draft model. * objectstack#37359 — `mapping`, a shared import mapping saved from the import - * wizard, is created the same way: into a package of the app, published at once. */ -export type RuntimeArtifactType = 'view' | 'report' | 'dashboard' | 'page' | 'mapping'; + * wizard, is created the same way: into a package of the app, published at once. + * objectstack#37087 — `form` (ADR-0159), the public form Setup switches and + * Studio's form editor saves, through the same package targets. */ +export type RuntimeArtifactType = 'view' | 'report' | 'dashboard' | 'page' | 'mapping' | 'form'; /** * The metadata `name` (the `:name` in `/meta/page/:name`) for an object's @@ -318,7 +320,9 @@ function invalidateViewCaches( name: string, ctx: RuntimePersistCtx, ): void { - if (type !== 'view') return; + // [#37087] A `form` save over an old shape removes the old-shape `view` row + // at that address (ADR-0159 card ②), so the object's cached views are stale too. + if (type !== 'view' && type !== 'form') return; const objectName = ctx.objectName; if (!objectName || !name) return; const invalidate = ctx.dataSource?.invalidateViewKeys; diff --git a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx index e6bcc341241..ff1ebcbba15 100644 --- a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx +++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx @@ -15,6 +15,8 @@ import { MemoryRouter } from 'react-router-dom'; const fake = vi.hoisted(() => ({ items: [] as unknown[], + listed: [] as string[], + layeredTypes: [] as string[], listFails: null as string | null, layered: (_name: string, _packageId?: string): { code?: unknown; effective?: unknown; draft?: unknown } => ({}), packages: new Map(), @@ -35,7 +37,8 @@ vi.mock('../../providers/AdapterProvider.js', () => { const adapter = { getClient: () => ({ meta: { - getItems: async () => { + getItems: async (type: string) => { + fake.listed.push(type); if (fake.listFails) throw new Error(fake.listFails); return { items: fake.items }; }, @@ -50,7 +53,10 @@ vi.mock('@object-ui/react', async (importOriginal) => ({ })); vi.mock('../metadata-admin/useMetadata.js', async (importOriginal) => { const client = { - layered: async (_type: string, name: string, options?: { packageId?: string }) => fake.layered(name, options?.packageId), + layered: async (type: string, name: string, options?: { packageId?: string }) => { + fake.layeredTypes.push(type); + return fake.layered(name, options?.packageId); + }, save: (...args: unknown[]) => fake.save(...args), publish: async () => ({}), reset: async () => ({}), @@ -70,13 +76,14 @@ const sharing = (enabled?: boolean) => ({ allowAnonymous: true, publicLink: 'contact-us', }); +/** A `form` item (ADR-0159): its body at the top level. */ const form = (enabled: boolean | undefined, extra: Record = {}) => ({ name: 'web_to_lead', object: 'crm_lead', - viewKind: 'form', label: 'Contact us', _packageId: 'crm', - config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: sharing(enabled) }, + title: 'Contact us', + sharing: sharing(enabled), ...extra, }); @@ -107,6 +114,8 @@ const ADMIN = ['manage_platform_settings', 'manage_metadata']; beforeEach(() => { fake.items = []; + fake.listed = []; + fake.layeredTypes = []; fake.listFails = null; fake.layered = () => ({}); fake.packages = new Map(); @@ -129,6 +138,8 @@ describe('PublicFormsSetupPage', () => { fake.packages.set('crm', { writable: true, manifest: { id: 'crm' } }); render(, { wrapper: host(['manage_platform_settings']) }); expect(await screen.findByTestId('public-form-row-web_to_lead')).toHaveAttribute('data-on', 'true'); + // [#37087] The list is the effective `form` read. + expect(fake.listed).toEqual(['form']); expect(screen.getByTestId('public-forms-no-switch')).toHaveTextContent('«publicFormsSetup.noSwitchPermission»'); expect(screen.getByTestId('public-form-switch-web_to_lead')).toBeDisabled(); }); @@ -146,12 +157,14 @@ describe('PublicFormsSetupPage', () => { expect(row).toHaveAttribute('data-shipped-off', 'true'); expect(screen.getByTestId('public-form-shipped-off-web_to_lead')).toHaveTextContent('«publicFormsSetup.shippedOff»'); expect(screen.getByTestId('public-form-switch-web_to_lead')).toBeDisabled(); + // [#37087] The app's own document is the `form` layered read's. + expect(fake.layeredTypes.every((type) => type === 'form')).toBe(true); }); } it('a list read that fails says so in business words, never the server\'s own message', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); - fake.listFails = 'GET /api/v1/meta/view failed: ECONNRESET upstream'; + fake.listFails = 'GET /api/v1/meta/form failed: ECONNRESET upstream'; render(, { wrapper: host(ADMIN) }); const alert = await screen.findByTestId('public-forms-load-failed'); expect(alert).toHaveTextContent('«publicFormsSetup.loadFailed»'); @@ -170,6 +183,8 @@ describe('PublicFormsSetupPage', () => { await waitFor(() => expect(row).toHaveAttribute('data-unknown', 'true')); expect(row).toHaveAttribute('data-on', 'false'); expect(screen.getByTestId('public-form-unknown-web_to_lead')).toHaveTextContent('«publicFormsSetup.statusUnknown»'); + // Not knowing whether it is live, the page offers no switch: Refresh reads it again. + expect(screen.getByTestId('public-form-switch-web_to_lead')).toBeDisabled(); }); it('a switch over a pending draft says so and does not read as done', async () => { @@ -197,7 +212,7 @@ describe('PublicFormsSetupPage', () => { ] as const) { (fake.toast.error as ReturnType).mockClear(); fake.save = async () => { - throw Object.assign(new Error('Capability manage_metadata required for PUT /meta/view/web_to_lead'), { status }); + throw Object.assign(new Error('Capability manage_metadata required for PUT /meta/form/web_to_lead'), { status }); }; const { unmount } = render(, { wrapper: host(ADMIN) }); fireEvent.click(await screen.findByTestId('public-form-switch-web_to_lead')); @@ -210,4 +225,134 @@ describe('PublicFormsSetupPage', () => { } warn.mockRestore(); }); + + describe('[#37087] a switch-on refused because another form holds the address (409 FORM_ADDRESS_TAKEN)', () => { + /** + * The server's refusal, as the metadata client throws it: the raw body on + * `body`, the holder in its `details` (#38626), in RestServer's flat + * spelling or, `nested`, the dispatcher's. + */ + const addressTaken = (holderOf: { name: string; packageId: string | null } | null = { name: 'crm_lead.newsletter', packageId: 'crm' }, nested = false) => { + const message = "The form 'web_to_lead' cannot open the public address '/forms/contact-us': the form 'crm_lead.newsletter' of the package 'crm' holds it."; + const details = holderOf ? { details: { holder: holderOf } } : {}; + const body = nested + ? { success: false, error: { code: 'FORM_ADDRESS_TAKEN', message, ...details } } + : { error: message, code: 'FORM_ADDRESS_TAKEN', ...details }; + return Object.assign(new Error(message), { status: 409, code: 'FORM_ADDRESS_TAKEN', body }); + }; + /** The form that holds the address: on, at the same slug. */ + const holder = (extra: Record = {}) => + form(true, { name: 'crm_lead.newsletter', label: 'Newsletter signup', title: 'Newsletter signup', ...extra }); + + const said = () => ((fake.toast.error as ReturnType).mock.calls[0] as [string])[0]; + + it('names both forms: the one being switched on and the one that holds its address', async () => { + fake.items = [form(false), holder()]; + fake.layered = () => ({ code: form(false), effective: form(false) }); + fake.packages.set('crm', { writable: true, manifest: { id: 'crm' } }); + fake.save = async () => { + throw addressTaken(); + }; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + render(, { wrapper: host(ADMIN) }); + const row = await screen.findByTestId('public-form-row-web_to_lead'); + expect(row).toHaveAttribute('data-on', 'false'); + fake.listed = []; + fireEvent.click(screen.getByTestId('public-form-switch-web_to_lead')); + await waitFor(() => expect(fake.toast.error).toHaveBeenCalledTimes(1)); + // One sentence, both names: the switched form in the frame, the holder in the reason. + expect(said()).toBe( + '«publicFormsSetup.switchFailed» ' + + JSON.stringify({ name: 'Contact us', message: '«publicFormsSetup.refusalAddressTaken» {"holder":"Newsletter signup"}' }), + ); + // Never the server's own message; that goes to the console log. + expect(said()).not.toContain('cannot open the public address'); + expect(said()).not.toContain('refusalServer'); + expect(warn).toHaveBeenCalled(); + // The holder is read from the refusal: the environment's forms are not read again. + expect(fake.listed).toEqual([]); + // Nothing was switched: the row stays off and no success is said. + expect(fake.toast.success).not.toHaveBeenCalled(); + expect(screen.getByTestId('public-form-row-web_to_lead')).toHaveAttribute('data-on', 'false'); + await waitFor(() => expect(screen.getByTestId('public-form-switch-web_to_lead')).not.toBeDisabled()); + warn.mockRestore(); + }); + + it('two forms shown under one name are told apart by the holder\'s package name, never an item name or package id', async () => { + fake.items = [form(false), holder({ label: 'Contact us', title: 'Contact us', _packageId: 'support' })]; + fake.packages.set('support', { id: 'support', name: 'Support desk', writable: true, manifest: { id: 'support', name: 'Support desk' } } as never); + fake.layered = () => ({ code: form(false), effective: form(false) }); + fake.packages.set('crm', { writable: true, manifest: { id: 'crm' } }); + fake.save = async () => { + throw addressTaken({ name: 'crm_lead.newsletter', packageId: 'support' }, true); + }; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + render(, { wrapper: host(ADMIN) }); + fireEvent.click(await screen.findByTestId('public-form-switch-web_to_lead')); + await waitFor(() => expect(fake.toast.error).toHaveBeenCalledTimes(1)); + // The dispatcher's nested envelope names the holder the same way. + expect(said()).toContain('«publicFormsSetup.refusalAddressTaken» {\\"holder\\":\\"Contact us (Support desk)\\"}'); + expect(said()).not.toContain('crm_lead.newsletter'); + expect(said()).not.toContain('(support)'); + warn.mockRestore(); + }); + + it('[#38626] a stale list: the holder is the one the refusal names, not the form the list last saw at the address', async () => { + // The list was read while `crm_lead.newsletter` sat at `contact-us`; since then it moved to `newsletter` + // and `crm_lead.signup` took `contact-us`. The refusal names `crm_lead.signup`. + const moved = holder({ sharing: { enabled: true, allowAnonymous: true, publicLink: 'contact-us' } }); + const signup = form(true, { name: 'crm_lead.signup', label: 'Event signup', title: 'Event signup', sharing: { enabled: false, allowAnonymous: true, publicLink: 'events' } }); + fake.items = [form(false), moved, signup]; + fake.layered = () => ({ code: form(false), effective: form(false) }); + fake.packages.set('crm', { writable: true, manifest: { id: 'crm' } }); + fake.save = async () => { + throw addressTaken({ name: 'crm_lead.signup', packageId: 'crm' }); + }; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + render(, { wrapper: host(ADMIN) }); + fireEvent.click(await screen.findByTestId('public-form-switch-web_to_lead')); + await waitFor(() => expect(fake.toast.error).toHaveBeenCalledTimes(1)); + expect(said()).toContain('«publicFormsSetup.refusalAddressTaken» {\\"holder\\":\\"Event signup\\"}'); + expect(said()).not.toContain('Newsletter signup'); + warn.mockRestore(); + }); + + it('with no holder in the refusal, says another form holds the address and names none, never the generic server sentence', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + for (const how of ['the refusal carries no holder', 'the holder is not a holder'] as const) { + (fake.toast.error as ReturnType).mockClear(); + fake.items = [form(false), holder()]; + fake.layered = () => ({ code: form(false), effective: form(false) }); + fake.packages.set('crm', { writable: true, manifest: { id: 'crm' } }); + fake.save = async () => { + throw how === 'the refusal carries no holder' ? addressTaken(null) : addressTaken({ name: '', packageId: 'crm' }); + }; + const { unmount } = render(, { wrapper: host(ADMIN) }); + fireEvent.click(await screen.findByTestId('public-form-switch-web_to_lead')); + await waitFor(() => expect(fake.toast.error).toHaveBeenCalledTimes(1)); + expect(said(), how).toBe( + '«publicFormsSetup.switchFailed» ' + + JSON.stringify({ name: 'Contact us', message: '«publicFormsSetup.refusalAddressTakenUnknown»' }), + ); + unmount(); + } + warn.mockRestore(); + }); + + it('CONTROL: another 409 is not read as an address clash', async () => { + fake.items = [form(false), holder()]; + fake.layered = () => ({ code: form(false), effective: form(false) }); + fake.packages.set('crm', { writable: true, manifest: { id: 'crm' } }); + fake.save = async () => { + throw Object.assign(new Error('conflict'), { status: 409, code: 'SOMETHING_ELSE' }); + }; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + render(, { wrapper: host(ADMIN) }); + fireEvent.click(await screen.findByTestId('public-form-switch-web_to_lead')); + await waitFor(() => expect(fake.toast.error).toHaveBeenCalledTimes(1)); + expect(said()).toContain('«publicFormsSetup.refusalServer»'); + expect(said()).not.toContain('refusalAddressTaken'); + warn.mockRestore(); + }); + }); }); diff --git a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx index 169a0eda27c..4aad49452c0 100644 --- a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx +++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx @@ -15,6 +15,11 @@ * changed) in Studio. Which forms are listed and where a switch is saved are * `publicForms.ts`'s. * + * A switch-on the server refuses because another form holds the address + * (`409 FORM_ADDRESS_TAKEN`) is said with both names: the form being switched + * on and the form that holds its address (objectstack#37087). The holder is + * read from the environment's forms, by `publicForms.ts`'s rule. + * * The address is the router's answer for the anonymous form route `/f/:slug` * (`useHref`, which prefixes the console's basename), as Studio's page builds * it (objectui#11769), so it follows the mount the console runs under. @@ -49,11 +54,16 @@ import { AUTHORING_CAPABILITY } from '../../hooks/useCanAuthorMetadata.js'; import { PUBLIC_FORMS_CAPABILITY } from './publicFormsRef.js'; import { PublicFormSwitchRefusal, + isAddressTakenRefusal, markShippedOff, + refusedAddressHolderOf, publicFormRowsOf, switchPublicForm, + type PublicAddressHolder, type PublicFormRow, } from './publicForms.js'; +import { addressHolderShownName } from '../studio-design/publicForm/publicFormDesign.js'; +import { fetchListedPackageManifests, type ListedPackageManifest } from '../studio-design/packages-io.js'; /** The anonymous form route, as the console's router declares it (`/f/:slug`). */ const PUBLIC_FORM_ROUTE = '/f'; @@ -85,6 +95,22 @@ function serverRefusalText(t: Translate, err: unknown): string { return t('publicFormsSetup.refusalServer'); } +/** + * The sentence for a switch-on refused because another form holds the address: + * it names that form as {@link addressHolderShownName} does. With no holder + * read, it says another form holds the address, and names none. + */ +function addressTakenText(t: Translate, row: PublicFormRow, read: HolderRead | null): string { + if (!read) return t('publicFormsSetup.refusalAddressTakenUnknown'); + return t('publicFormsSetup.refusalAddressTaken', { holder: addressHolderShownName(read.holder, row, read.packageNames) }); +} + +/** The holder of an address, with the package list its package's display name is read from (`null`: unreadable). */ +interface HolderRead { + holder: PublicAddressHolder; + packageNames: ReadonlyMap | null; +} + type Read = { kind: 'loading' } | { kind: 'failed' } | { kind: 'ready'; rows: PublicFormRow[] }; export function PublicFormsSetupPage() { @@ -129,7 +155,7 @@ function PublicFormsSetupBody() { (async () => { try { if (!client?.meta?.getItems) throw new Error('meta.getItems is not available on this client'); - const answer = await client.meta.getItems('view'); + const answer = await client.meta.getItems('form'); const rows = await markShippedOff(publicFormRowsOf(answer), metadataClient as any); if (live) setRead({ kind: 'ready', rows }); } catch (err) { @@ -167,6 +193,15 @@ function PublicFormsSetupBody() { } }; + /** The form the refusal names as holding `row`'s address, with the package list; `null` when the refusal names none. */ + const readAddressHolder = async (row: PublicFormRow, err: unknown): Promise => { + const holder = refusedAddressHolderOf(err, read.kind === 'ready' ? read.rows : []); + if (!holder) return null; + // Only a holder sharing the row's title is named with its package. + const packageNames = holder.title === row.title ? await fetchListedPackageManifests().catch(() => null) : null; + return { holder, packageNames }; + }; + const flip = async (row: PublicFormRow, on: boolean) => { setBusy(row.name); try { @@ -188,6 +223,13 @@ function PublicFormsSetupBody() { ); setNonce((n) => n + 1); } catch (err) { + if (isAddressTakenRefusal(err)) { + // The server's own words (they name both forms and their packages) go to the console log. + console.warn('[public forms] switch refused:', formatMetadataError(err)); + const message = addressTakenText(t, row, await readAddressHolder(row, err)); + toast.error(t('publicFormsSetup.switchFailed', { name: row.title, message })); + return; + } const message = err instanceof PublicFormSwitchRefusal ? refusalText(t, err) : serverRefusalText(t, err); toast.error(t('publicFormsSetup.switchFailed', { name: row.title, message })); if (err instanceof PublicFormSwitchRefusal && err.reason === 'shipped-off') setNonce((n) => n + 1); @@ -277,7 +319,7 @@ function PublicFormsSetupBody() {
void flip(row, next)} aria-label={t(row.on ? 'publicFormsSetup.switchOffLabel' : 'publicFormsSetup.switchOnLabel', { name: row.title, diff --git a/ui/packages/app-shell/src/views/setup/accessDirectory.test.ts b/ui/packages/app-shell/src/views/setup/accessDirectory.test.ts index 384168d9ed7..7595150d3ee 100644 --- a/ui/packages/app-shell/src/views/setup/accessDirectory.test.ts +++ b/ui/packages/app-shell/src/views/setup/accessDirectory.test.ts @@ -102,6 +102,9 @@ describe("a Studio cross-package address (studioAllLegSetupRedirect)", () => { '/studio/~all/metadata/flow?package=all', '/studio/crm/metadata', '/studio/~allx/metadata', + // objectstack#38150 — the Loose list of flows stays in Studio; so does a retired `~org` + // address, which is not this mapping's to move (`studioOrgScopeRetired.ts` redirects it). + '/studio/~all/metadata/flow?source=loose', '/studio/~org/metadata/flow?source=runtime', ]) { expect(studioAddressAfterSetupMove(address), address).toBe(address); diff --git a/ui/packages/app-shell/src/views/setup/publicForms.test.ts b/ui/packages/app-shell/src/views/setup/publicForms.test.ts index 0bc794c30ed..6c91b1927de 100644 --- a/ui/packages/app-shell/src/views/setup/publicForms.test.ts +++ b/ui/packages/app-shell/src/views/setup/publicForms.test.ts @@ -4,10 +4,12 @@ import { describe, it, expect, vi } from 'vitest'; import { PublicFormSwitchRefusal, baseShipsFormOff, + isAddressTakenRefusal, markShippedOff, overrideHoldsOnlySwitch, publicFormRowOf, publicFormRowsOf, + refusedAddressHolderOf, switchPublicForm, } from './publicForms'; @@ -24,15 +26,20 @@ const sharing = (enabled: boolean, extra: Record = {}) => ({ ...extra, }); +/** A served `form` item (ADR-0159): its body at the top level. */ const formItem = (overrides: Record = {}, enabled = true) => ({ name: 'web_to_lead', object: 'crm_lead', - viewKind: 'form', label: 'Contact us', _packageId: 'crm', - config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: sharing(enabled), sections: [] }, + title: 'Contact us', + sharing: sharing(enabled), + sections: [], ...overrides, }); +/** The same form as the effective read projects an app's old view shape (ADR-0159 D5). */ +const projectedItem = (overrides: Record = {}, enabled = true) => + formItem({ data: { provider: 'object', object: 'crm_lead' }, _formDefinedIn: 'view', ...overrides }, enabled); describe('publicFormRowOf', () => { it('lists a form open to anonymous intake as on', () => { @@ -51,26 +58,29 @@ describe('publicFormRowOf', () => { }); it('does not list an internal form: not anonymous, or no address', () => { - const notAnonymous = formItem({ config: { title: 'x', sharing: { enabled: true, allowAnonymous: false, publicLink: 'x' } } }); - const noLink = formItem({ config: { title: 'x', sharing: { enabled: true, allowAnonymous: true } } }); - const noSharing = formItem({ config: { title: 'x' } }); + const notAnonymous = formItem({ sharing: { enabled: true, allowAnonymous: false, publicLink: 'x' } }); + const noLink = formItem({ sharing: { enabled: true, allowAnonymous: true } }); + const noSharing = formItem({ sharing: undefined }); expect(publicFormRowOf(notAnonymous)).toBeNull(); expect(publicFormRowOf(noLink)).toBeNull(); expect(publicFormRowOf(noSharing)).toBeNull(); }); - it('does not list a view that is not a form, or one with no config', () => { - expect(publicFormRowOf(formItem({ viewKind: 'list' }))).toBeNull(); - expect(publicFormRowOf(formItem({ config: null }))).toBeNull(); + it('lists a form an app still ships as an old view shape, as the effective read projects it', () => { + expect(publicFormRowOf(projectedItem())).toEqual(publicFormRowOf(formItem())); + }); + + it('does not list an item with no name, or nothing', () => { + expect(publicFormRowOf(formItem({ name: '' }))).toBeNull(); expect(publicFormRowOf(null)).toBeNull(); }); it('names a form by its served label, else its title, else its first section, else its name; a package-less item has none', () => { expect(publicFormRowOf(formItem({ label: undefined }))?.title).toBe('Contact us'); - const sectioned = { sharing: sharing(true), sections: [{ name: 'contact_us', label: 'Get in touch', fields: [] }] }; - expect(publicFormRowOf(formItem({ label: undefined, config: sectioned }))?.title).toBe('Get in touch'); - expect(publicFormRowOf(formItem({ label: '', config: { sharing: sharing(true) } }))?.title).toBe('web_to_lead'); - expect(publicFormRowOf(formItem({ name: 'crm_lead.web_to_lead', label: '', config: { sharing: sharing(true) } }))?.title).toBe( + const sectioned = { title: undefined, sections: [{ name: 'contact_us', label: 'Get in touch', fields: [] }] }; + expect(publicFormRowOf(formItem({ label: undefined, ...sectioned }))?.title).toBe('Get in touch'); + expect(publicFormRowOf(formItem({ label: '', title: undefined }))?.title).toBe('web_to_lead'); + expect(publicFormRowOf(formItem({ name: 'crm_lead.web_to_lead', label: '', title: undefined }))?.title).toBe( 'web_to_lead', ); expect(publicFormRowOf(formItem({ _packageId: undefined }))?.packageId).toBeNull(); @@ -81,19 +91,77 @@ describe('publicFormRowsOf', () => { it('reads `{ items }` or a bare array, drops internal forms and sorts by the name shown', () => { const b = formItem({ name: 'b_form', label: 'Beta' }); const a = formItem({ name: 'a_form', label: 'Alpha' }); - const list = formItem({ name: 'all', viewKind: 'list' }); + const list = formItem({ name: 'all', sharing: undefined }); expect(publicFormRowsOf({ items: [b, list, a] }).map((r) => r.name)).toEqual(['a_form', 'b_form']); expect(publicFormRowsOf([b, a]).map((r) => r.name)).toEqual(['a_form', 'b_form']); expect(publicFormRowsOf(undefined)).toEqual([]); }); }); +describe('[#38626] refusedAddressHolderOf: the holder the refusal names', () => { + const refusal = (body: unknown) => Object.assign(new Error('taken'), { status: 409, code: 'FORM_ADDRESS_TAKEN', body }); + const holder = { name: 'crm_lead.newsletter', packageId: 'crm' }; + /** The list the page shows: the holder under its shown name. */ + const rows = [publicFormRowOf(formItem({ name: 'crm_lead.newsletter', label: 'Newsletter signup' }))!]; + + it('reads both doors\' spellings: RestServer\'s flat body and the dispatcher\'s nested envelope', () => { + const named = { name: 'crm_lead.newsletter', title: 'Newsletter signup', packageId: 'crm' }; + expect(refusedAddressHolderOf(refusal({ error: 'x', code: 'FORM_ADDRESS_TAKEN', details: { holder } }), rows)).toEqual(named); + expect(refusedAddressHolderOf(refusal({ success: false, error: { code: 'FORM_ADDRESS_TAKEN', message: 'x', details: { holder } } }), rows)).toEqual(named); + }); + + it('a stale list: the list row\'s address does not matter, the refusal\'s holder is named by name and package', () => { + const stale = [{ ...rows[0], slug: 'newsletter' }, publicFormRowOf(formItem({}, false))!]; + expect(refusedAddressHolderOf(refusal({ details: { holder } }), stale)?.title).toBe('Newsletter signup'); + // The same name in another package is another form. + expect(refusedAddressHolderOf(refusal({ details: { holder: { ...holder, packageId: 'hr' } } }), stale)).toEqual({ + name: 'crm_lead.newsletter', + title: 'newsletter', + packageId: 'hr', + }); + }); + + it('a holder the list does not show is named by its name without the object prefix; a package-less holder reads as null', () => { + expect(refusedAddressHolderOf(refusal({ details: { holder: { name: 'crm_lead.internal', packageId: null } } }), rows)).toEqual({ + name: 'crm_lead.internal', + title: 'internal', + packageId: null, + }); + }); + + it('answers null when the refusal carries no holder, or not one', () => { + expect(refusedAddressHolderOf(refusal({ error: 'x' }), rows)).toBeNull(); + expect(refusedAddressHolderOf(refusal({ details: { holder: { name: '' } } }), rows)).toBeNull(); + expect(refusedAddressHolderOf(refusal({ details: { holder: { name: 'a', packageId: 3 } } }), rows)).toBeNull(); + expect(refusedAddressHolderOf(new Error('no body'), rows)).toBeNull(); + expect(refusedAddressHolderOf(undefined, rows)).toBeNull(); + }); +}); + +describe('[#37087] isAddressTakenRefusal', () => { + it('is the server\'s 409 FORM_ADDRESS_TAKEN, by either status key', () => { + expect(isAddressTakenRefusal(Object.assign(new Error('taken'), { status: 409, code: 'FORM_ADDRESS_TAKEN' }))).toBe(true); + expect(isAddressTakenRefusal({ statusCode: 409, code: 'FORM_ADDRESS_TAKEN' })).toBe(true); + }); + + it('is not a pending-draft conflict, another status with the code, or no error at all', () => { + expect(isAddressTakenRefusal({ status: 409, code: 'METADATA_CONFLICT' })).toBe(false); + expect(isAddressTakenRefusal({ status: 400, code: 'FORM_ADDRESS_TAKEN' })).toBe(false); + expect(isAddressTakenRefusal({ status: 409 })).toBe(false); + expect(isAddressTakenRefusal(undefined)).toBe(false); + }); +}); + describe('overrideHoldsOnlySwitch', () => { const base = formItem(); it('is true when the override differs from the base only by the switch, its declaration and the decorations', () => { const override = { ...formItem({}, false), _layer: 'custom', overrides: { package: 'crm', basedOn: '3.0.0' } }; expect(overrideHoldsOnlySwitch(override, base)).toBe(true); }); + it('[#37087] is true over an old-shape base: its projection\'s `data` binding and marker are not design', () => { + const override = { ...stripped(formItem({}, false)), overrides: { package: 'crm', basedOn: '3.0.0' } }; + expect(overrideHoldsOnlySwitch(override, projectedItem())).toBe(true); + }); it('is false when the override also changes the design', () => { const override = { ...formItem({ label: 'Talk to us' }, false), @@ -130,10 +198,11 @@ describe('switchPublicForm', () => { expect(out).toBe('published'); expect(client.save).toHaveBeenCalledTimes(1); const [type, name, body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; - expect([type, name]).toEqual(['view', 'web_to_lead']); + expect([type, name]).toEqual(['form', 'web_to_lead']); expect(options).toMatchObject({ mode: 'draft', ifNoneMatch: '*', packageId: 'crm' }); - expect(body).toEqual({ ...stripped(doc), config: { ...doc.config, sharing: sharing(false) } }); - expect(client.publish).toHaveBeenCalledWith('view', 'web_to_lead', { packageId: 'crm' }); + expect(body).toEqual({ ...stripped(doc), sharing: sharing(false) }); + expect(client.publish).toHaveBeenCalledWith('form', 'web_to_lead', { packageId: 'crm' }); + expect(client.layered).toHaveBeenCalledWith('form', 'web_to_lead', { packageId: 'crm' }); expect(invalidateViewKeys).toHaveBeenCalledWith('crm_lead', 'web_to_lead'); }); @@ -147,9 +216,9 @@ describe('switchPublicForm', () => { const [, , body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; expect(options).toMatchObject({ packageId: 'crm.custom' }); expect(body.overrides).toEqual({ package: 'crm', basedOn: '3.0.0' }); - expect(body.config.sharing).toEqual(sharing(false)); + expect(body.sharing).toEqual(sharing(false)); expect(body._packageId).toBeUndefined(); - expect(client.publish).toHaveBeenCalledWith('view', 'web_to_lead', { packageId: 'crm.custom' }); + expect(client.publish).toHaveBeenCalledWith('form', 'web_to_lead', { packageId: 'crm.custom' }); expect(client.reset).not.toHaveBeenCalled(); }); @@ -158,10 +227,10 @@ describe('switchPublicForm', () => { const client = clientOf((_n, pkg) => (pkg === 'crm' ? { code: doc, effective: doc } : { code: null, effective: null })); const doors = listed({ crm: { writable: false, version: '3.0.0' }, 'crm.custom': { writable: true, version: '0.0.0' } }); await switchPublicForm(row, false, client, {}, doors); - expect(client.layered).toHaveBeenNthCalledWith(1, 'view', 'web_to_lead', { packageId: 'crm.custom' }); - expect(client.layered).toHaveBeenNthCalledWith(2, 'view', 'web_to_lead', { packageId: 'crm' }); + expect(client.layered).toHaveBeenNthCalledWith(1, 'form', 'web_to_lead', { packageId: 'crm.custom' }); + expect(client.layered).toHaveBeenNthCalledWith(2, 'form', 'web_to_lead', { packageId: 'crm' }); const [, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; - expect(body.config.sharing).toEqual(sharing(false)); + expect(body.sharing).toEqual(sharing(false)); }); it('switching back on restores the app\'s own form when the override held nothing but the switch', async () => { @@ -173,7 +242,7 @@ describe('switchPublicForm', () => { const out = await switchPublicForm(row, true, client, { dataSource: { invalidateViewKeys } as any }, doors); expect(out).toBe('restored'); expect(client.reset).toHaveBeenCalledTimes(1); - expect(client.reset).toHaveBeenCalledWith('view', 'web_to_lead', { packageId: 'crm.custom' }); + expect(client.reset).toHaveBeenCalledWith('form', 'web_to_lead', { packageId: 'crm.custom' }); expect(client.save).not.toHaveBeenCalled(); expect(invalidateViewKeys).toHaveBeenCalledWith('crm_lead', 'web_to_lead'); }); @@ -189,7 +258,7 @@ describe('switchPublicForm', () => { const [, , body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; expect(options).toMatchObject({ packageId: 'crm.custom' }); expect(body.label).toBe('Talk to us'); - expect(body.config.sharing).toEqual(sharing(true)); + expect(body.sharing).toEqual(sharing(true)); expect(body.overrides).toEqual({ package: 'crm', basedOn: '3.0.0' }); }); @@ -203,7 +272,7 @@ describe('switchPublicForm', () => { expect(out).toEqual({ kind: 'earlier-version', basedOn: '2.0.0' }); expect(client.reset).not.toHaveBeenCalled(); const [, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; - expect(body.config.sharing).toEqual(sharing(true)); + expect(body.sharing).toEqual(sharing(true)); // The override keeps the version it declared: re-basing is a person's call. expect(body.overrides).toEqual({ package: 'crm', basedOn: '2.0.0' }); }); @@ -220,13 +289,14 @@ describe('switchPublicForm', () => { describe('a form the installed app ships switched off', () => { const shippedOff = { 'enabled: false': formItem({}, false), - 'no enabled': formItem({ config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: { allowAnonymous: true, publicLink: 'contact-us' } } }), + 'no enabled': formItem({ sharing: { allowAnonymous: true, publicLink: 'contact-us' } }), + 'enabled: false, as an old shape': projectedItem({}, false), }; const doors = () => listed({ crm: { writable: false, version: '3.0.0' }, 'crm.custom': { writable: true, version: '0.0.0' } }); for (const [how, base] of Object.entries(shippedOff)) { it(`(${how}) is never switched on: nothing is written, and the refusal says the app ships it off`, async () => { - expect(baseShipsFormOff(base, 'web_to_lead')).toBe(true); + expect(baseShipsFormOff(base)).toBe(true); // No override yet: the list serves the app's own document. const fresh = clientOf(() => ({ code: base, effective: base })); const freshDoors = doors(); @@ -257,9 +327,9 @@ describe('switchPublicForm', () => { } it('(allowAnonymous: false) the routes\' own rule: an app that ships the form closed to anonymous visitors withdraws it, even once an override opens it', async () => { - const base = formItem({ config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: sharing(true, { allowAnonymous: false }) } }); + const base = formItem({ sharing: sharing(true, { allowAnonymous: false }) }); const override = { ...stripped(formItem()), overrides: { package: 'crm', basedOn: '3.0.0' } }; - expect(baseShipsFormOff(base, 'web_to_lead', override)).toBe(true); + expect(baseShipsFormOff(base)).toBe(true); // The served override reads on, by the candidates rule alone. const served = publicFormRowOf({ ...override, _packageId: 'crm' })!; expect(served.on).toBe(true); @@ -280,9 +350,26 @@ describe('switchPublicForm', () => { expect(marked.shippedOff).toBeUndefined(); }); + it('[#37087] does not read a form as on when the read answers no document of the app\'s own', async () => { + const client = clientOf(() => ({ code: null, effective: formItem() })); + const [marked] = await markShippedOff([publicFormRowOf(formItem())!], client, doors()); + expect(marked).toMatchObject({ on: false, unknown: true }); + // …and switching it on writes nothing. + await expect(switchPublicForm(row, true, client, {}, doors())).rejects.toMatchObject({ reason: 'load-failed' }); + expect(client.save).not.toHaveBeenCalled(); + }); + + it('[#37087] withdraws by the form\'s name whatever slug the served override declares (ADR-0159 D6 rule 6)', async () => { + const base = formItem({}, false); + const elsewhere = { ...stripped(formItem({ sharing: sharing(true, { publicLink: 'elsewhere' }) })), overrides: { package: 'crm', basedOn: '3.0.0' } }; + const client = clientOf(() => ({ code: base, effective: elsewhere })); + const [marked] = await markShippedOff([publicFormRowOf({ ...elsewhere, _packageId: 'crm' })!], client, doors()); + expect(marked).toMatchObject({ on: false, shippedOff: true }); + }); + it('leaves a form the app ships on, a writable package\'s form and a form with no package as listed', async () => { const on = formItem(); - expect(baseShipsFormOff(on, 'web_to_lead')).toBe(false); + expect(baseShipsFormOff(on)).toBe(false); const client = clientOf((name) => ({ code: name === 'own' ? formItem({}, false) : on, effective: on })); const listedDoors = listed({ crm: { writable: false, version: '3.0.0' }, mine: { writable: true } }); const rows = [ @@ -335,12 +422,22 @@ describe('switchPublicForm', () => { for (const c of [ok, unreadable]) expect(c.save).not.toHaveBeenCalled(); }); + it('[#37087] saves an old shape\'s switch as a `form` item: no `data`, no projection marker', async () => { + const doc = projectedItem(); + const client = clientOf(() => ({ code: doc, effective: doc })); + await switchPublicForm(row, false, client, {}, listed({ crm: { writable: true } })); + const [type, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; + expect(type).toBe('form'); + expect(body).toEqual({ ...stripped(formItem()), sharing: sharing(false) }); + expect('data' in body).toBe(false); + }); + it('saves a form that names no package where it lives', async () => { const doc = formItem({ _packageId: undefined }); const client = clientOf(() => ({ code: doc, effective: doc })); const out = await switchPublicForm({ ...row, packageId: null }, false, client, {}, listed({})); expect(out).toBe('published'); - expect(client.layered).toHaveBeenCalledWith('view', 'web_to_lead', {}); + expect(client.layered).toHaveBeenCalledWith('form', 'web_to_lead', {}); const [, , , options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; expect(options).toEqual({ mode: 'draft', ifNoneMatch: '*' }); }); diff --git a/ui/packages/app-shell/src/views/setup/publicForms.ts b/ui/packages/app-shell/src/views/setup/publicForms.ts index 44496fc6d31..1c6dba76dcb 100644 --- a/ui/packages/app-shell/src/views/setup/publicForms.ts +++ b/ui/packages/app-shell/src/views/setup/publicForms.ts @@ -8,8 +8,8 @@ * * ## Which forms are listed, and which are on * - * A public form is a form view item whose form the server's one rule - * (`anonymousFormIntakeCandidates`, `@objectstack/spec/ui`) opens to anonymous + * A public form is a `form` item (ADR-0159) whose `sharing` the server's one + * rule (`anonymousFormIntakeSlug`, `@objectstack/spec/ui`) opens to anonymous * intake. The rule reads three keys of its `sharing`: the switch `enabled`, * `allowAnonymous` and the `publicLink` slug. This module reads none of them * itself (the routes and this page must never disagree, objectui#11545): @@ -20,9 +20,13 @@ * whose author never made it anonymous or gave it no address is an internal * form, and is not listed. * - * The list read is the effective one (`GET /meta/view`, ADR-0146 D8): an + * The list read is the effective one (`GET /meta/form`, ADR-0146 D8): an * installed app's form switched off in its customization package is served - * switched off, so it lists as off. + * switched off, so it lists as off. A form an app still ships as an old view + * shape is served there as its projection (ADR-0159 D5, marked + * `_formDefinedIn: 'view'`), and every read and write below names `form`: + * a switch saved over an old shape is a `form` item ({@link authorableForm}), + * which supersedes the old shape at that address (card ②'s write rule). * * ## Where a switch is saved * @@ -44,27 +48,39 @@ * * ## A form the app ships switched off * - * An installed app whose own document keeps a form's address but switches it - * off (`enabled: false` or `allowAnonymous: false`, matched by slot or by - * slug) WITHDRAWS it: the anonymous routes judge the app's own document as a - * kill switch that no override re-opens (`anonymousFormIntakeWithdrawnIn`, - * pinned in `packages/rest/src/public-form-withdrawal-effective-read.test.ts`). - * This page judges it with that same function, imported from the spec. A - * switch the app's document omits counts as off too, as the stack schema - * parses it (`enabled` defaults to `false`). Such a form is listed, never as - * on ({@link markShippedOff}), and switching it on writes nothing and says the + * An installed app whose own document of a form keeps its address but switches + * it off (`enabled: false` or `allowAnonymous: false`) WITHDRAWS it: the + * anonymous routes judge the app's own document as a kill switch that no + * override re-opens, by the form's name whatever slug either side declares + * (`formExplicitlyWithdraws` in the doors' layer, `formIntakeLayer`, ADR-0159 D6 + * rule 6). This page judges it with that same function, imported from the + * spec, on the app's own document as the `form` layered read serves it (its + * `code`, the projection of an old shape included). A switch the app's + * document omits counts as off too, as the stack schema parses it (`enabled` + * defaults to `false`). Such a form is listed, never as on + * ({@link markShippedOff}), and switching it on writes nothing and says the * app ships it switched off. * * A switch is refused, and nothing is written, over a draft already pending * where it would save: that draft is its saver's and is never published on * their behalf. * + * ## An address another form holds + * + * The server refuses a switch-on that would leave two forms open on one + * address (`409 FORM_ADDRESS_TAKEN`, ADR-0159 ruled question 3). The refusal + * carries the form that holds the address as data (`details.holder`), so the + * page names both forms, the one being switched on and the one that holds the + * address, from the server's answer ({@link refusedAddressHolderOf}), never + * from a second copy of the server's rule (objectstack#37087, #38626). + * * Not listed here: when a form last took a submission. A submission is an * ordinary record of the form's object and records no form, so there is * nothing to read. */ -import { anonymousFormIntakeCandidates, anonymousFormIntakeWithdrawnIn, anonymousFormObjectName } from '@objectstack/spec/ui'; +import { anonymousFormIntakeSlug, formExplicitlyWithdraws } from '@objectstack/spec/ui'; +import { errorCodeIs } from '@object-ui/types'; import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; import { resolveDashboardEditTarget, @@ -84,7 +100,7 @@ const isDoc = (v: unknown): v is FormDoc => !!v && typeof v === 'object' && !Arr /** One public form, as the list read serves it. */ export interface PublicFormRow { - /** The form view item's name: the metadata address every write names. */ + /** The `form` item's name: the metadata address every write names. */ name: string; /** What the page shows as its name ({@link shownName}). */ title: string; @@ -118,46 +134,45 @@ const text = (v: unknown): string | undefined => (typeof v === 'string' && v.tri /** * The name a form is shown by, in the words its author gave it: the served - * (translated) label, else the form's title or label, else the label of its - * first section (what the form's own page heads it with), else its name - * without the object prefix (`crm_lead.web_to_lead` → `web_to_lead`). + * (translated) label, else the form's title, else the label of its first + * section (what the form's own page heads it with), else its name without + * the object prefix (`crm_lead.web_to_lead` → `web_to_lead`). */ function shownName(item: FormDoc): string { - const config: FormDoc = isDoc(item.config) ? item.config : {}; - const first = Array.isArray(config.sections) ? config.sections.find(isDoc) : undefined; + const first = Array.isArray(item.sections) ? item.sections.find(isDoc) : undefined; const dot = item.name.lastIndexOf('.'); return ( text(item.label) ?? - text(config.title) ?? - text(config.label) ?? + text(item.title) ?? text(first?.label) ?? (dot >= 0 && dot < item.name.length - 1 ? item.name.slice(dot + 1) : item.name) ); } +/** The slug the rule opens `form` at, or `null`. */ +const openSlug = (form: FormDoc): string | null => anonymousFormIntakeSlug(form.sharing); + /** - * The public form a served view item carries, or `null` (module header): a - * `viewKind: 'form'` item whose `config` the rule opens once its switch is on. - * The list serves view ITEMS only, so a form is its item's `config`. + * The public form a served `form` item is, or `null` (module header): an item + * whose `sharing` the rule opens once its switch is on. A `form` item carries + * its body at the top level, the projection of an old shape included. */ export function publicFormRowOf(item: unknown): PublicFormRow | null { - if (!isDoc(item) || item.viewKind !== 'form' || !isDoc(item.config) || typeof item.name !== 'string') return null; - const switchedOn = anonymousFormIntakeCandidates({ ...item, config: withSwitch(item.config, true) }); - const listed = switchedOn.find((c) => c.key === item.name); - if (!listed) return null; - const on = anonymousFormIntakeCandidates(item).some((c) => c.key === item.name); + if (!isDoc(item) || typeof item.name !== 'string' || !item.name) return null; + const slug = openSlug(withSwitch(item, true)); + if (slug === null) return null; const packageId = typeof item._packageId === 'string' && item._packageId ? item._packageId : null; return { name: item.name, title: shownName(item), - object: anonymousFormObjectName(item, item.config), - slug: listed.slug, - on, + ...(typeof item.object === 'string' && item.object ? { object: item.object } : {}), + slug, + on: openSlug(item) !== null, packageId, }; } -/** Every public form of a `GET /meta/view` answer (`{ items }`, or a bare array), sorted by name shown. */ +/** Every public form of a `GET /meta/form` answer (`{ items }`, or a bare array), sorted by name shown. */ export function publicFormRowsOf(answer: unknown): PublicFormRow[] { const items: unknown[] = Array.isArray(answer) ? answer : isDoc(answer) && Array.isArray(answer.items) ? answer.items : []; const rows: PublicFormRow[] = []; @@ -168,6 +183,55 @@ export function publicFormRowsOf(answer: unknown): PublicFormRow[] { return rows.sort((a, b) => a.title.localeCompare(b.title) || a.name.localeCompare(b.name)); } +/** The server's code for a form left open on an address another form holds (`409`). */ +export const FORM_ADDRESS_TAKEN = 'FORM_ADDRESS_TAKEN'; + +/** Whether `err` is the server's refusal of an address another form holds. */ +export function isAddressTakenRefusal(err: unknown): boolean { + const e = err as { status?: unknown; statusCode?: unknown } | null | undefined; + return (e?.status === 409 || e?.statusCode === 409) && errorCodeIs(err, FORM_ADDRESS_TAKEN); +} + +/** The form that holds an address another form asked for. */ +export interface PublicAddressHolder { + /** The `form` item's name. */ + name: string; + /** What the page shows as its name ({@link shownName}). */ + title: string; + /** The package that serves it, or `null` when it names none. */ + packageId: string | null; +} + +/** A `{ name, packageId }` holder, or `null` when `v` is not one. */ +function holderOf(v: unknown): Pick | null { + if (!isDoc(v) || typeof v.name !== 'string' || !v.name) return null; + if (v.packageId !== null && typeof v.packageId !== 'string') return null; + return { name: v.name, packageId: v.packageId || null }; +} + +/** + * The form a `409 FORM_ADDRESS_TAKEN` names as holding the address, read from + * the refusal itself (`details.holder`, `{ name, packageId }`), or `null` when + * it carries none. The two doors that serve a metadata save spell the + * envelope apart, so both are read: `RestServer`'s flat body + * (`body.details.holder`) and the runtime dispatcher's nested one + * (`body.error.details.holder`). + * + * Its name on the page comes from `rows` (the list the page shows), matched by + * name and package, which stay put while a form's address moves; a holder the + * list does not show is named by its name without the object prefix, as + * {@link shownName} names a form with no label. + */ +export function refusedAddressHolderOf(err: unknown, rows: readonly PublicFormRow[]): PublicAddressHolder | null { + const body = (err as { body?: unknown } | null | undefined)?.body; + if (!isDoc(body)) return null; + const nested = isDoc(body.error) && isDoc(body.error.details) ? body.error.details.holder : undefined; + const holder = holderOf(isDoc(body.details) ? body.details.holder : undefined) ?? holderOf(nested); + if (!holder) return null; + const listed = rows.find((r) => r.name === holder.name && r.packageId === holder.packageId); + return { ...holder, title: listed ? listed.title : shownName({ name: holder.name }) }; +} + /** The metadata client calls {@link switchPublicForm} makes. */ export interface PublicFormSwitchClient { layered( @@ -198,10 +262,15 @@ export class PublicFormSwitchRefusal extends Error { } } -/** A document without the read's `_` decorations. */ -function authored(doc: FormDoc): FormDoc { +/** + * A served form as a `form` item a save takes: without the read's `_` + * decorations (the projection's `_formDefinedIn` included) and without + * `data`, the old shape's binding, which a `form` item never carries: it is + * bound by its `object` (ADR-0159 D2; the save refuses `data` by name). + */ +export function authorableForm(doc: FormDoc): FormDoc { const out: FormDoc = {}; - for (const [key, value] of Object.entries(doc)) if (!key.startsWith('_')) out[key] = value; + for (const [key, value] of Object.entries(doc)) if (!key.startsWith('_') && key !== 'data') out[key] = value; return out; } @@ -219,34 +288,26 @@ function canonical(value: unknown): string { */ export function overrideHoldsOnlySwitch(override: FormDoc, base: FormDoc): boolean { const strip = (doc: FormDoc) => { - const out = authored(doc); + const out = withSwitch(authorableForm(doc), true); delete out.overrides; - if (isDoc(out.config)) out.config = withSwitch(out.config, true); return out; }; return canonical(strip(override)) === canonical(strip(base)); } /** - * Whether an installed app's own document `base` of the form `name` ships it - * switched off (module header), judged by the routes' own rule: `base` - * withdraws the form `served` carries (the effective item, an override - * included; `base` itself when omitted), matched by slot or by slug - * (`anonymousFormIntakeWithdrawnIn`). The served form is judged with its switch - * on, the state a switch-on would leave it in. A switch the app's document - * omits counts as off as well, as the stack schema parses it, so the console - * fails closed where the routes do. + * Whether an installed app's own document `base` of a form ships it switched + * off (module header), judged by the routes' own rule: the doors close a form + * whose name's body explicitly withdraws it (`formExplicitlyWithdraws`), + * whatever slug the served form declares (ADR-0159 D6 rule 6). A switch the + * app's document omits counts as off as well, as the stack schema parses it, + * so the console fails closed where the routes do. */ -export function baseShipsFormOff(base: unknown, name: string, served?: unknown): boolean { - if (!isDoc(base) || !isDoc(base.config)) return false; - const named = { ...base, name }; - const view: FormDoc = isDoc(served) ? { ...served, name } : named; - const probe = isDoc(view.config) ? { ...view, config: withSwitch(view.config, true) } : view; - const candidates = anonymousFormIntakeCandidates(probe).filter((c) => c.key === name); - if (candidates.some((c) => anonymousFormIntakeWithdrawnIn([named], probe, c))) return true; +export function baseShipsFormOff(base: unknown): boolean { + if (!isDoc(base)) return false; + if (formExplicitlyWithdraws(base) !== undefined) return true; // An omitted switch: the app's document would open the form switched on, but does not as written. - const wouldOpen = anonymousFormIntakeCandidates({ ...named, config: withSwitch(base.config, true) }).some((c) => c.key === name); - return wouldOpen && !anonymousFormIntakeCandidates(named).some((c) => c.key === name); + return openSlug(withSwitch(base, true)) !== null && openSlug(base) === null; } type FormLayers = { code?: unknown; effective?: unknown; draft?: unknown }; @@ -264,10 +325,10 @@ async function readFormLayers(name: string, target: ResolvedTarget, client: Pick : target.kind === 'package' ? { packageId: target.packageId } : { packageId: target.pair ?? target.base }; - const layers = await client.layered('view', name, at); + const layers = await client.layered('form', name, at); // A listed pair that does not hold the form yet holds nothing: its base's document is read. if (target.kind === 'customization' && target.pair && !isDoc(layers.effective) && !isDoc(layers.code)) { - return client.layered('view', name, { packageId: target.base }); + return client.layered('form', name, { packageId: target.base }); } return layers; } @@ -296,8 +357,9 @@ export async function markShippedOff( if (target.kind !== 'customization') return row; try { const layers = await readFormLayers(row.name, target, client); - const served = isDoc(layers.effective) ? layers.effective : layers.code; - return baseShipsFormOff(layers.code, row.name, served) ? { ...row, on: false, shippedOff: true } : row; + // No document of the app's own: whether the routes serve the form is not known. + if (!isDoc(layers.code)) return { ...row, on: false, unknown: true }; + return baseShipsFormOff(layers.code) ? { ...row, on: false, shippedOff: true } : row; } catch { return { ...row, on: false, unknown: true }; } @@ -328,25 +390,27 @@ export async function switchPublicForm( throw new PublicFormSwitchRefusal('load-failed', err instanceof Error ? err.message : String(err)); } const effective = isDoc(layers.effective) ? layers.effective : isDoc(layers.code) ? layers.code : null; - if (!effective || !isDoc(effective.config)) throw new PublicFormSwitchRefusal('load-failed', row.name); - const switched = { ...authored(effective), config: withSwitch(effective.config, on) }; + if (!effective) throw new PublicFormSwitchRefusal('load-failed', row.name); + const switched = withSwitch(authorableForm(effective), on); - if (target.kind === 'unbound') return saveAndPublishRuntimeMetadata('view', row.name, switched, persist); - if (target.kind === 'package') return saveAndPublishInPackage('view', row.name, switched, target.packageId, persist); + if (target.kind === 'unbound') return saveAndPublishRuntimeMetadata('form', row.name, switched, persist); + if (target.kind === 'package') return saveAndPublishInPackage('form', row.name, switched, target.packageId, persist); // An installed app: this environment's customization, in the app's pair. const declared = declaredOverrideOf(effective, target.base); const override = declared ? effective : null; const base = isDoc(layers.code) ? layers.code : null; // The app ships the form switched off: no override re-opens it, so nothing is written. - if (on && baseShipsFormOff(base, row.name, effective)) throw new PublicFormSwitchRefusal('shipped-off', target.base); - if (on && override && base && isDoc(base.config)) { - const baseOn = anonymousFormIntakeCandidates({ ...base, name: row.name }).some((c) => c.key === row.name); + // No document of the app's own: nothing tells whether it ships the form switched off. + if (on && !base) throw new PublicFormSwitchRefusal('load-failed', row.name); + if (on && baseShipsFormOff(base)) throw new PublicFormSwitchRefusal('shipped-off', target.base); + if (on && override && base) { + const baseOn = openSlug(base) !== null; if (baseOn && overrideHoldsOnlySwitch(override, base) && target.pair) { // A draft pending over the override is its saver's: nothing is removed under it. if (isDoc(layers.draft)) return 'pending-draft'; // "Restore package original": the pair's row of the form is removed. - await client.reset('view', row.name, { packageId: target.pair }); + await client.reset('form', row.name, { packageId: target.pair }); if (row.object) persist.dataSource?.invalidateViewKeys?.(row.object, row.name); emitMetadataRefresh(); return 'restored'; @@ -356,7 +420,7 @@ export async function switchPublicForm( if (body === null) throw new PublicFormSwitchRefusal('no-version', target.base); const saveTarget = await ensureDashboardSaveTarget(target, doors); if (saveTarget.kind !== 'customization') throw new PublicFormSwitchRefusal('no-package', target.base); - const outcome = await saveAndPublishInPackage('view', row.name, body, saveTarget.packageId, persist); + const outcome = await saveAndPublishInPackage('form', row.name, body, saveTarget.packageId, persist); // Switched on over an override taken from an earlier version of the app: the form stays on that version. if (on && outcome === 'published' && declared && target.basedOn && declared.basedOn !== target.basedOn) { return { kind: 'earlier-version', basedOn: declared.basedOn }; diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.newSimilar-28567.test.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.newSimilar-28567.test.tsx index ab5129dca12..c140f9abc76 100644 --- a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.newSimilar-28567.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.newSimilar-28567.test.tsx @@ -14,8 +14,7 @@ * - a `409` (name taken) is the server's sentence, verbatim, the dialog stays * open on the names typed, and nothing opens; * - an answer that names no package opens nothing and says so; - * - without `manage_metadata` the item draws disabled, and nothing is sent; - * - the package-less scope draws no menu (no pair, no package to name). + * - without `manage_metadata` the item draws disabled, and nothing is sent. * * The harness is `AutomationsPillar.deleteFlow-27356`'s: the metadata server * doubled at the client, the `/automation` doors doubled at `fetch`, and the @@ -324,22 +323,9 @@ describe('Automations — New similar on a flow (#28567)', () => { expect(cloneCalls()).toHaveLength(0); }); - it('the package-less scope draws no menu', async () => { - mockClient.list.mockImplementation(async () => [{ name: 'approval', label: 'Approval' }]); - try { - render( - - - , - ); - expect(await screen.findByTestId('auto-canvas-caption', undefined, { timeout: 8000 })).toHaveTextContent('Approval'); - expect(screen.queryByTestId('studio-detail-more')).toBeNull(); - } finally { - mockClient.list.mockImplementation(async (_type: string, opts?: { packageId?: string }) => - opts?.packageId ? server.flows[opts.packageId] ?? [] : [], - ); - } - }); + // objectstack#38150 — "the package-less scope draws no menu" is removed: the flow designer is a + // package's now (`packageId` is a string), and the retired scope draws no page. That its + // addresses redirect is pinned in `StudioDesignSurface.packageLessFlows-11553.test.tsx`. }); /** diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx index 7608a4d6174..e453fed7d52 100644 --- a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx @@ -1,9 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * The flow designer — one flow, full-screen on its metadata address - * (`/studio//metadata/flow/`, or the package-less scope's - * `/studio/~org/metadata/flow/`; objectstack#36903, epic + * The flow designer — one flow of a package, full-screen on its metadata + * address (`/studio//metadata/flow/`; objectstack#36903, epic * objectstack#36890; ADR-0146 D1 as amended): the item header (× back to the * flow list, ‹ › through it), the designer's tabs with the item tools after * them (`flowDesignerTabs.ts`), the flow canvas and its inspectors — with the @@ -30,7 +29,7 @@ import { AUTOMATIONS_CONFIG_FOLD_WIDTH, useIsNarrowerThan } from './wideViewport import { STUDIO_FOLD_LABEL } from './studio-tokens.js'; import { StudioInspector } from './StudioInspector.js'; import { isAgentDraftSurface } from './StudioDraftMark.js'; -import { StudioAiDraftNotice } from './StudioAiDraftNotice.js'; +import { StudioAiDraftNotice, aiDraftDiscardConfirmUnsaved } from './StudioAiDraftNotice.js'; import { StudioTab } from './StudioItemHeader.js'; import { ResourceDetailHeader, detailListHref } from '../metadata-admin/ResourceDetailHeader.js'; import { ItemToolTabPanel, ItemToolTabStrip } from '../item-tools/ItemToolTabs.js'; @@ -104,7 +103,7 @@ import { loadPackageLessSurfaces, loadPackageSurfaces, } from './packageSurfaces.js'; -import { studioOrgScopePath } from './studioScope.js'; +import { packageLessItemPath } from './studioScope.js'; import { studioItemPath } from './studioAddress.js'; import { useCanAuthorMetadata, useCanReadAuthoringTrail } from '../../hooks/useCanAuthorMetadata.js'; import { useMetadataRefreshNonce } from './useMetadataRefreshNonce.js'; @@ -152,11 +151,11 @@ function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise, - scopes: ReadonlyArray, + scopes: ReadonlyArray, ): Promise | null> { try { const answers = await Promise.all( - scopes.map((packageId) => client.listResponse>('flow', packageId === null ? {} : { packageId })), + scopes.map((packageId) => client.listResponse>('flow', { packageId })), ); const names = new Set(); for (const answer of answers) { @@ -172,7 +171,7 @@ async function readPublishedFlowNames( /** * The flow designer (objectstack#36903): one flow, named by its address, read - * at its package (or the package-less scope), drawn full-screen. + * at its package, drawn full-screen. */ export function AutomationsPillar({ packageId: scopePackageId, @@ -184,11 +183,11 @@ export function AutomationsPillar({ onHeldEditChange, }: { /** - * The package whose flow this is, or `null` for the package-less scope - * (objectui#11553, `studioScope.ts`): a flow that belongs to no package, - * saved as a package-less draft. + * The package whose flow this is. The designer is a package's: a flow that + * belongs to no package opens on its item page on the cross-package leg + * (`packageLessItemPath`), never here. */ - packageId: string | null; + packageId: string; /** objectstack#36903 — the one flow this page designs: the name in its metadata address. */ flowName: string; publishNonce?: number; @@ -208,7 +207,7 @@ export function AutomationsPillar({ // objectstack#28572 (ADR-0146 D3) — on a read-only base its pair is read // too: a flow the pair adds opens here writable, at the pair. const railPackageId = scopePackageId; - const railPairId = packageReadOnly && railPackageId !== null && customization ? customization.pairId : null; + const railPairId = packageReadOnly && customization ? customization.pairId : null; // objectstack#28567 — "New similar" (`FlowItemMoreMenu`): the strip that // shows the copy the clone door saved, with the door's sentence that it is // switched off, as sent. The copy opens on its own address (objectstack#36903), @@ -219,7 +218,7 @@ export function AutomationsPillar({ readFlowCopiedArrival(location.state, railPackageId) ?? // objectstack#28572 — a copy that landed in the base's pair. Matched by // the spec's pairing rule: a read of where the copy went, never a write target. - (railPackageId !== null ? readFlowCopiedArrival(location.state, pairIdOf(railPackageId)) : null), + readFlowCopiedArrival(location.state, pairIdOf(railPackageId)), ); const canAuthorFlows = useCanAuthorMetadata(); // objectui#11795 — on a row too narrow for the Configuration aside to sit @@ -237,12 +236,10 @@ export function AutomationsPillar({ // objectstack#28572 — a flow the pair adds (`current.addedIn`) opens // writable, read and saved at the pair: every read and write of the OPEN // flow below names `packageId` and asks `readOnly`, the open flow's own. - const packageId: string | null = current?.addedIn ?? railPackageId; + const packageId: string = current?.addedIn ?? railPackageId; const readOnly = packageReadOnly && !current?.addedIn; - // The draft writes' package binding (objectui#11553): none in the - // package-less scope, so the draft row stays as package-less as the flow it - // edits. The client sends no `package=` for an absent id. - const draftPackageId = packageId ?? undefined; + // The draft writes' package binding: the open flow's own package. + const draftPackageId: string = packageId; // objectstack#28570 (ADR-0146 D9 items 1–3, D2) — Customize a flow. On a // read-only base its flow is edited in the base's paired customization // package under the flow's own name, as a declared override of the base's @@ -467,8 +464,8 @@ export function AutomationsPillar({ }, [publishNonce, statusNonce]); // objectstack#36903 — the scope's read: the flows of the package (with its - // pair's, on a read-only base) or of the package-less scope, the engine's - // registrations, and the published names. It names the open flow (its label, + // pair's, on a read-only base), the engine's registrations, and the + // published names. It names the open flow (its label, // and on a read-only base whether the pair adds it); the flow's own body is // the load below. Re-read on a publish and on the live pulse (the copilot's // edits): the open flow keeps its identity across those reads, so a re-read @@ -493,7 +490,7 @@ export function AutomationsPillar({ ? null : Promise.all([loadPackageSurfaces(client, 'flow', pairId, locale), readFlowRegistrations(client, pairId)]); const [baseItems, registrations, pair, publishedNames] = await Promise.all([ - scope === null ? loadPackageLessSurfaces(client, 'flow', locale) : loadPackageSurfaces(client, 'flow', scope, locale), + loadPackageSurfaces(client, 'flow', scope, locale), readFlowRegistrations(client, scope), readPair().catch(() => null), readPublishedFlowNames(client, [scope, ...(pairId === null ? [] : [pairId])]), @@ -503,14 +500,15 @@ export function AutomationsPillar({ setPublishedFlowNames(publishedNames); setFlowRegistrations(pair ? { ...pair[1], ...registrations } : registrations); const named = items.find((f) => f.name === flowName) ?? null; - // objectui#11553 — a package's address naming a package-less flow - // opens it in the package-less scope, once per mount. - if (!named && scope !== null && !deepLinkProbedRef.current) { + // objectui#11553 — a package's address naming a flow that belongs to + // no package opens that flow where such a flow opens: its item page on + // the cross-package leg (objectstack#38150). Once per mount. + if (!named && !deepLinkProbedRef.current) { deepLinkProbedRef.current = true; const packageLess = await loadPackageLessSurfaces(client, 'flow', locale).catch(() => []); if (cancelled) return; if (packageLess.some((f) => f.name === flowName)) { - navigate(studioOrgScopePath({ type: 'flow', name: flowName }), { replace: true }); + navigate(packageLessItemPath({ type: 'flow', name: flowName }), { replace: true }); return; } } @@ -801,10 +799,14 @@ export function AutomationsPillar({ // read at), back to the live version. Edits not yet saved go with it, asked first. const flowAiDraft = flowLoaded && hasDraft && (flowDraftChanges ?? []).some((change) => isAgentDraftSurface(change.by)); + // objectstack#38302 — a flow the published list does not hold has no live + // version: its discard deletes it, and the line and the confirm say so. + // `undefined` while that list is unread or its read failed. + const flowPublished = current && publishedFlowNames ? publishedFlowNames.has(current.name) : undefined; const [discardingFlowDraft, setDiscardingFlowDraft] = React.useState(false); const discardFlowDraft = React.useCallback(async () => { if (!current) return; - if (autoDirty && !window.confirm(t('engine.studio.aiDraft.discardConfirmUnsaved', locale))) return; + if (autoDirty && !window.confirm(aiDraftDiscardConfirmUnsaved(locale, flowPublished))) return; const at = flowReadAtRef.current?.key === `flow:${current.name}` ? flowReadAtRef.current.at : draftPackageId; setDiscardingFlowDraft(true); setError(null); @@ -823,7 +825,7 @@ export function AutomationsPillar({ } finally { setDiscardingFlowDraft(false); } - }, [autoDirty, client, current, draftPackageId, locale, reloadFlowDraft]); + }, [autoDirty, client, current, draftPackageId, flowPublished, locale, reloadFlowDraft]); // objectui#12725 — the header's draft line reads the badge's ledger. const flowDraftStatus = useStudioItemDraftStatus( current ? { type: 'flow', name: current.name } : null, @@ -879,7 +881,7 @@ export function AutomationsPillar({ { type: 'flow', name: flowName, - packageId: draftPackageId ?? null, + packageId: draftPackageId, // objectstack#37440 — and to the draft the flip just wrote (its receipt). draftVersion: heldFlowDraftVersion('flow', flowName, draftPackageId), }, @@ -919,7 +921,7 @@ export function AutomationsPillar({ // × opens it (the list's filters kept). A refusal shows the door's sentence // and keeps the flow open. const deleteOpenFlow = React.useCallback(async () => { - if (!current || packageId === null) return; + if (!current) return; const flow = current; setAutoDirty(false); setError(null); @@ -1016,7 +1018,7 @@ export function AutomationsPillar({ // door is pre-judged from the served posture facts; after any attempt the // server's refusal is shown as sent. const ledgerRow = - readOnly && packageId !== null && current && flowStatusRead ? flowStatus[current.name] : undefined; + readOnly && current && flowStatusRead ? flowStatus[current.name] : undefined; const ledgerOn = ledgerRow?.enabled; const ledgerWalled = useFlowLedgerWalledReadOnly(); const ledgerWalledReason = ledgerWalled ? t('engine.studio.auto.ledger.walled', locale) : undefined; @@ -1048,8 +1050,8 @@ export function AutomationsPillar({ ); }, [current, ledgerOn, ledgerWalled, locale]); // objectui#12725 — the surface's right slot hosts the Configuration - // (`useStudioRightSlot`); `null` in the package-less scope and under an - // injected `aiSlot`, where the aside beside the canvas (or, on a folded + // (`useStudioRightSlot`); `null` under an injected `aiSlot`, where the + // aside beside the canvas (or, on a folded // row, the drawer over it) stays. Held while there is a flow to select, as // the aside is drawn. A selection asks for the properties, keyed on its // identity; Esc drops it (the canvas's own background press already does), @@ -1274,11 +1276,11 @@ export function AutomationsPillar({ // link there truncated the flow's label; it sits at the tab row's right // end, the slot objectui#12456 gave the Access note for the same reason. const autoReadOnlyLinkEl = - editLocked && packageId !== null ? ( + editLocked ? ( ) : null; /** The flow's ⋯ menu is drawn (objectstack#28567): the header folds into it (objectstack#29693). */ - const flowMoreShown = !!current && flowLoaded && packageId !== null; + const flowMoreShown = !!current && flowLoaded; // objectstack#36903 — the tool tabs need the flow's own buffer (Source edits // it), so the row waits for the load, as the switch does; the designer's // sections need its canvas too. @@ -1330,9 +1332,9 @@ export function AutomationsPillar({ ) : undefined; // objectstack#28567 — New similar on a read-only package's flow and on a // writable one's (the door picks the pair for a read-only base; a writable - // package is the target); Delete on a writable package's flow only. The - // package-less scope has no pair and no package to name. objectstack#36903 — - // in the header's ⋯, which also takes what a narrow header folds. + // package is the target); Delete on a writable package's flow only. + // objectstack#36903 — in the header's ⋯, which also takes what a narrow + // header folds. const flowMenu = useFlowItemMenu({ name: current?.name ?? flowName, label: current?.label ?? flowName, @@ -1340,7 +1342,7 @@ export function AutomationsPillar({ disabled: !!saving, onDelete: readOnly ? undefined : () => void deleteOpenFlow(), newSimilar: { - target: readOnly ? undefined : (packageId ?? undefined), + target: readOnly ? undefined : packageId, blocked: canAuthorFlows ? null : t('engine.edit.capabilityReadOnly', locale), // The copy opens in place of this flow, which drops a held edit; asked // before the dialog. @@ -1386,7 +1388,7 @@ export function AutomationsPillar({ } apiName={flowName} typeLabel={translateMetadataType('flow', locale, 'Flow')} - packageLabel={packageId ?? undefined} + packageLabel={packageId} // Esc with a node selected deselects it first (the slot's own Esc, the aside's ✕). closeOnEscape={!selection} // objectstack#29691 (ADR-0146 D3) — a flow the pair adds, overrides @@ -1499,6 +1501,7 @@ export function AutomationsPillar({ {flowAiDraft && ( void discardFlowDraft() : undefined} busy={discardingFlowDraft || saving !== false} /> @@ -1599,7 +1602,7 @@ export function AutomationsPillar({ section, onSectionChange: setFlowSection, onProblemsChange: setProblemTally, - published: current && publishedFlowNames ? publishedFlowNames.has(current.name) : undefined, + published: flowPublished, // objectstack#34818 — in the right slot, Debug draws the simulator there. debugTarget: inSlot && section === 'debug' ? slot.propsTarget : null, }} diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.aiDraftNeverPublished-38302.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.aiDraftNeverPublished-38302.test.tsx new file mode 100644 index 00000000000..f89b7f92677 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.aiDraftNeverPublished-38302.test.tsx @@ -0,0 +1,174 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38302 — the Data pillar's own AI line over the object canvas. + * Its 「放弃 AI 的改动」 drops the object's draft: for an object with a + * published or code version that goes back to it; for an object the AI + * created and nobody published there is none, and the discard deletes it. + * The button's title and the confirm asked over an unsaved edit say which, + * from the pillar's own reading of the object's layers (`hasBaseline`: an + * effective or code version). Keys are named, never copy. + * + * The harness is the one of `DataPillar.aiDraftDiscard-36511.test.tsx`, with + * the layers read able to serve an object that holds no layer. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; + +const PACKAGE = 'com.example.showcase'; +const live = { + name: 'showcase_task', + label: 'Task', + fields: { + priority: { name: 'priority', label: 'Priority', type: 'text' }, + }, +}; +/** The AI's version: one field added. */ +const aiVersion = { + ...live, + fields: { ...live.fields, renewal_count: { name: 'renewal_count', label: 'Renewals', type: 'number' } }, +}; + +const minutesAgo = (n: number) => new Date(Date.now() - n * 60_000 - 5_000).toISOString(); + +/** What the next draft read serves: `null` for no draft. */ +let draftEnvelope: Record | null = null; +/** Whether the object has a version beyond its draft. */ +let published = true; + +const mockClient = { + save: vi.fn(async () => ({})), + publish: vi.fn(async () => ({})), + reset: vi.fn(async () => { + draftEnvelope = null; + return {}; + }), + list: vi.fn(async (type: string) => (type === 'object' ? [{ name: 'showcase_task', label: 'Task' }] : [])), + listDrafts: vi.fn(async () => []), + // objectstack#38302 — `published` false serves an object with no layer + // beyond its draft: no published row and no code baseline. + layered: vi.fn(async () => + published + ? { effective: live, code: live, draft: draftEnvelope?.item ?? null } + : { effective: null, code: null, overlay: null, draft: draftEnvelope?.item ?? null }, + ), + getDraft: vi.fn(async () => draftEnvelope), + get: vi.fn(async () => null), + withPreviewDrafts() { + return this; + }, +}; + +vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; +}); + +vi.mock('./packages-io', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, fetchPackages: vi.fn(async () => []) }; +}); + +vi.mock('@object-ui/react', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useAdapter: () => dataSource }; +}); + +import '@objectstack/lint'; +import '@object-ui/plugin-detail'; +import { DataPillar } from './StudioDesignSurface'; +import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; +import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; +import { StudioSaveHarness } from './__tests__/studioSaveHarness'; +import { t } from '../metadata-admin/i18n'; + +const discardDrafts = vi.fn(async () => ({ success: true, failedCount: 0, failed: [], discarded: [] })); +const dataSource = Object.assign(createEmptyDataSource(), { + getClient: () => ({ packages: { discardDrafts } }), +}); +failOnAbsorbedFetchError(); + +const L = (key: string) => t(key, 'en-US'); + +const confirmSpy = vi.fn((_message?: string) => true); +beforeEach(() => { + draftEnvelope = null; + published = true; + confirmSpy.mockReset(); + confirmSpy.mockReturnValue(true); + window.confirm = confirmSpy as unknown as typeof window.confirm; +}); +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +function serveDraft(by: string) { + draftEnvelope = { + type: 'object', + name: 'showcase_task', + item: { ...aiVersion, _draft: true }, + version: 'v1', + draftChanges: [{ path: ['fields', 'renewal_count'], by, actor: 'usr_1', at: minutesAgo(2) }], + }; +} + +function renderPillar(onDraftSaved = vi.fn()): { onDraftSaved: ReturnType } { + render( + + + + + , + ); + return { onDraftSaved }; +} + +async function openForm(): Promise { + fireEvent.click(await screen.findByRole('button', { name: L('engine.studio.data.tab.form') })); + await screen.findByTestId('form-toolbar'); +} + +const LIVE_TITLE = 'engine.studio.aiDraft.discardTitle'; +const DELETE_TITLE = 'engine.studio.aiDraft.discardTitleUnpublished'; +const LIVE_CONFIRM = 'engine.studio.aiDraft.discardConfirmUnsaved'; +const DELETE_CONFIRM = 'engine.studio.aiDraft.discardConfirmUnsavedUnpublished'; + +describe('the Data pillar AI line on an object never published (objectstack#38302)', () => { + it('an object the AI created and nobody published: the discard title says it deletes it', async () => { + published = false; + serveDraft('copilot'); + renderPillar(); + const line = await screen.findByTestId('studio-copilot-changes'); + await waitFor(() => expect(within(line).getByTestId('studio-ai-draft-discard')).toHaveAttribute('title', L(DELETE_TITLE))); + }); + + it('…and over an unsaved edit the confirm says so too; declined, nothing is sent', async () => { + published = false; + serveDraft('copilot'); + renderPillar(); + await openForm(); + await addFieldFromFormToolbar(undefined, { label: 'Due' }); + await screen.findByTestId('studio-save'); + confirmSpy.mockReturnValueOnce(false); + fireEvent.click(screen.getByTestId('studio-ai-draft-discard')); + expect(confirmSpy).toHaveBeenCalledWith(L(DELETE_CONFIRM)); + expect(mockClient.reset).not.toHaveBeenCalled(); + }); + + it('CONTROL: an object with a published version keeps the live-version wording on the title and the confirm', async () => { + serveDraft('copilot'); + renderPillar(); + const line = await screen.findByTestId('studio-copilot-changes'); + await waitFor(() => expect(within(line).getByTestId('studio-ai-draft-discard')).toHaveAttribute('title', L(LIVE_TITLE))); + await openForm(); + await addFieldFromFormToolbar(undefined, { label: 'Due' }); + await screen.findByTestId('studio-save'); + confirmSpy.mockReturnValueOnce(false); + fireEvent.click(screen.getByTestId('studio-ai-draft-discard')); + expect(confirmSpy).toHaveBeenCalledWith(L(LIVE_CONFIRM)); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.tsx index 07f37ff9d1f..4f88e43cc41 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.tsx @@ -137,6 +137,7 @@ import { useMetadataRefreshNonce } from './useMetadataRefreshNonce.js'; import { type Surface } from './navSurface.js'; import { useSurfaceActionDeepLink } from './useSurfaceDeepLink.js'; import { t, tFormat, translateMetadataType, useMetadataLocale } from '../metadata-admin/i18n.js'; +import { aiDraftDiscardConfirmUnsaved, aiDraftDiscardTitle } from './StudioAiDraftNotice.js'; import { InspectorShellHostProvider } from '../metadata-admin/inspectors/_shared.js'; import type { DestructiveChangeIssue } from '@objectstack/spec/api'; import { @@ -1463,7 +1464,9 @@ export function DataPillar({ const [discardingItemDraft, setDiscardingItemDraft] = React.useState(false); const discardItemDraft = React.useCallback(async () => { if (!current) return; - if (dirty && !window.confirm(t('engine.studio.aiDraft.discardConfirmUnsaved', locale))) return; + // objectstack#38302 — an object with no baseline (no published or code + // version) was never published: the discard deletes it, and the confirm says so. + if (dirty && !window.confirm(aiDraftDiscardConfirmUnsaved(locale, hasBaseline))) return; setDiscardingItemDraft(true); setError(null); try { @@ -1480,7 +1483,7 @@ export function DataPillar({ } finally { setDiscardingItemDraft(false); } - }, [client, current, dirty, locale, packageId, reloadObjDraft]); + }, [client, current, dirty, hasBaseline, locale, packageId, reloadObjDraft]); // 放弃全部未发布改动 — the package's discard door (`packages.discardDrafts`), // which drops every pending draft of the package, the author's own too; the // confirm says so. There is no per-turn undo. @@ -2154,7 +2157,7 @@ export function DataPillar({ data-testid="studio-ai-draft-discard" onClick={() => void discardItemDraft()} disabled={discardingItemDraft || discardingDrafts || saving !== false} - title={t('engine.studio.aiDraft.discardTitle', locale)} + title={aiDraftDiscardTitle(locale, hasBaseline)} className="font-medium text-amber-700 hover:underline disabled:opacity-50 dark:text-amber-300" > {t('engine.studio.aiDraft.discard', locale)} diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.tsx index 61e7a3251d8..a4406072cf6 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.tsx @@ -96,7 +96,6 @@ import { StudioEmptyState, StudioEmptyStateAction } from './StudioEmptyState.js' import type { PairActionsDoor, PairObjectActions } from './pairObjectActions.js'; import { RailCustomizationFilter, RailCustomizationMark, useRailCustomizationsOnly } from './StudioRailCustomizations.js'; import { FlowLedgerSwitch } from './FlowLedgerSwitch.js'; -import { isStudioOrgScope } from './studioScope.js'; import { StudioAiDraftNotice } from './StudioAiDraftNotice.js'; import { useActionLedger } from '../setup/packagedActionLedger.js'; @@ -255,8 +254,7 @@ export function ObjectActionsPanel({ // the draft's: the console draws no ledger switch there (the card's item 1 // offers it on a read-only app's vendor actions only), so nothing is read. const routePackage = useParams<{ packageId?: string }>().packageId ?? null; - const ledgerPackage = - disabled && routePackage && !isStudioOrgScope(routePackage) ? routePackage : null; + const ledgerPackage = disabled && routePackage ? routePackage : null; const ledger = useActionLedger(ledgerPackage); const vendorNames = React.useMemo(() => new Set(actions.map((a) => String(a.name ?? ''))), [actions]); // A listed action the switch is for: one of the vendor's, once the ledger answered. @@ -829,6 +827,7 @@ export function ObjectActionsPanel({ {selRow?.aiDraft && ( added.discardAiDraft(selRow.name) : undefined} busy={added.discardingAiDraft !== null || added.saving} className="m-2 mb-0" diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx index f8dfb2155a8..fde33c32885 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx @@ -82,6 +82,7 @@ export function ObjectHooksPanel({ addHook, reportCel, aiDraft, + aiDraftPublished, discardAiDraft, discardingAiDraft, } = buffer; @@ -213,6 +214,7 @@ export function ObjectHooksPanel({ {aiDraft && ( expect(rows()).toHaveLength(1)); fireEvent.click(within(rows()[0]).getByRole('link')); expect(await screen.findByTestId('where')).toHaveTextContent(`/studio/${APP}/metadata/object/account`); diff --git a/ui/packages/app-shell/src/views/studio-design/PackageCustomizationsPanel.tsx b/ui/packages/app-shell/src/views/studio-design/PackageCustomizationsPanel.tsx index 2d78c7f86c1..2d0a3077d00 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageCustomizationsPanel.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageCustomizationsPanel.tsx @@ -23,7 +23,8 @@ * gives one), what kind of item it is and how it changed, and opens the item * in Studio. Tabs narrow by kind and a search by text; the first rows show, * the rest behind "Show all". A read that fails says so, never "0". - * "Customize in Studio" opens the app there, the home card's Customize door. + * "Customize in Studio" opens the app there, on its 概览 Overview, where every + * door into a package lands (objectstack#38392). */ import * as React from 'react'; @@ -39,7 +40,7 @@ import { loadCustomizationLabels, type CustomizationRow, } from './packageCustomizationRows.js'; -import { studioHomePath } from './studioAddress.js'; +import { studioPackageOverviewPath } from './studioOverviewAddress.js'; /** How many rows the section shows before "Show all". */ export const PACKAGE_CUSTOMIZATION_ROWS_SHOWN = 6; @@ -163,7 +164,7 @@ export function PackageCustomizationsPanel({

{t(`${K}.heading`, locale)}

{ const own = rowState.find((s) => s.row.name === name); if (!own?.row.aiDraft) return; - if (own.dirty && !window.confirm(t('engine.studio.owd.aiDraftDiscardConfirmUnsaved', locale))) return; + // objectstack#38302 — an object the published list did not hold is + // deleted by the discard; the other rows keep their edits either way. + const ask = t( + own.row.saved + ? 'engine.studio.owd.aiDraftDiscardConfirmUnsaved' + : 'engine.studio.owd.aiDraftDiscardConfirmUnsavedUnpublished', + locale, + ); + if (own.dirty && !window.confirm(ask)) return; const others = rowState.filter((s) => s.dirty && s.row.name !== name); setDiscardingAiDraft(name); setSaveError(null); @@ -937,6 +945,7 @@ export function PackageOwdOverviewPanel({ void discardAiDraft(row.name)} busy={discardingAiDraft !== null || saving} className="mt-1" diff --git a/ui/packages/app-shell/src/views/studio-design/StudioAiDraftNotice.neverPublished-38302.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioAiDraftNotice.neverPublished-38302.test.tsx new file mode 100644 index 00000000000..5fa84b47220 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/StudioAiDraftNotice.neverPublished-38302.test.tsx @@ -0,0 +1,438 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38302 — the AI-draft line's discard (「放弃 AI 的改动」) drops the + * item's draft. For an item with a published version that goes back to the + * live version; for an item that was never published there is none, and the + * discard deletes it. The button's title and the confirm asked over an unsaved + * edit say which, from the host's own reading of "has a published version". + * + * Pinned on the line itself, and on one host per distinct reader: + * + * - the published-list reader (the open item's name in the type's published + * `list()`): the object designer's Hooks tab, whose buffer keeps those + * names. The Access, Automations, pair-actions and sharing-overview hosts + * read the same list membership, each through its own load; + * - the layers reader (an item whose `/layers` read holds no layer at all): + * the generic item page. + * + * And the sharing overview's own confirm: its discard keeps every other row's + * unsaved edit, so a never-published object is asked about with the OWD + * wording (only this row's change goes), never the page-wide one. + * + * Copy is never pinned: each assertion names the key the text must come from. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { z } from 'zod'; +import { ComponentRegistry } from '@object-ui/core'; +import { DocSchema } from '@objectstack/spec/system'; +import { MetadataClient } from '@object-ui/data-objectstack'; + +const toasts = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() })); +vi.mock('sonner', () => ({ toast: toasts })); + +vi.mock('../metadata-admin/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataLocale: () => 'en-US', +})); + +/** Which client the mocked `useMetadataClient` answers with, set per suite. */ +const client = vi.hoisted(() => ({ current: null as unknown, docTypes: false })); + +vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { + const mod = await importOriginal(); + return { + ...mod, + useMetadataClient: () => client.current, + useMetadataTypes: (...args: Parameters) => + client.docTypes + ? { + loading: false, + entries: [ + { + type: 'doc', + label: 'Documentation', + domain: 'system', + allowEnvironmentOverlay: false, + allowRuntimeCreate: true, + schema: DOC_JSON_SCHEMA, + }, + ], + } + : mod.useMetadataTypes(...args), + }; +}); + +import { StudioAiDraftNotice, aiDraftDiscardConfirmUnsaved } from './StudioAiDraftNotice'; +import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel'; +import { StudioSaveHarness } from './__tests__/studioSaveHarness'; +import { HooksPanelHost } from './__tests__/hooksPanelHost'; +import { MetadataResourceEditPage } from '../metadata-admin/ResourceEditPage'; +import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; +import { registerDefaultMetadataSchemas } from '../metadata-admin/default-schemas'; +import { registerBuiltinPreviews } from '../metadata-admin/previews'; +import { t } from '../metadata-admin/i18n'; +// The source reaches a dynamic `import('@objectstack/lint')`: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; +import { __setCelFormulaLoader } from '../metadata-admin/celAuthoring'; + +const DOC_JSON_SCHEMA = z.toJSONSchema(DocSchema as unknown as z.ZodType) as Record; + +registerBuiltinInspectors(); +registerDefaultMetadataSchemas(); +registerBuiltinPreviews(); + +const LIVE_TITLE = 'engine.studio.aiDraft.discardTitle'; +const DELETE_TITLE = 'engine.studio.aiDraft.discardTitleUnpublished'; +const LIVE_CONFIRM = 'engine.studio.aiDraft.discardConfirmUnsaved'; +const DELETE_CONFIRM = 'engine.studio.aiDraft.discardConfirmUnsavedUnpublished'; +const en = (key: string) => t(key, 'en-US'); + +const confirmSpy = vi.fn((_message?: string) => false); + +beforeEach(() => { + for (const fn of Object.values(toasts)) fn.mockClear(); + confirmSpy.mockReset(); + confirmSpy.mockReturnValue(false); + Object.defineProperty(window, 'confirm', { configurable: true, writable: true, value: confirmSpy }); +}); +afterEach(() => { + cleanup(); +}); + +async function settle() { + await act(async () => { + for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0)); + }); +} + +describe('the line: its discard title follows "has a published version"', () => { + it('the two keys exist in both locales the namespace carries, and differ from the live-version ones', () => { + for (const locale of ['en-US', 'zh-CN']) { + for (const key of [DELETE_TITLE, DELETE_CONFIRM]) expect(t(key, locale)).not.toBe(key); + expect(t(DELETE_TITLE, locale)).not.toBe(t(LIVE_TITLE, locale)); + expect(t(DELETE_CONFIRM, locale)).not.toBe(t(LIVE_CONFIRM, locale)); + } + }); + + it.each([ + [false, DELETE_TITLE], + [true, LIVE_TITLE], + [undefined, LIVE_TITLE], + ] as const)('published=%s titles the discard with %s', (published, key) => { + render( {}} />); + expect(screen.getByTestId('studio-ai-draft-discard')).toHaveAttribute('title', en(key)); + }); + + it.each([ + [false, DELETE_CONFIRM], + [true, LIVE_CONFIRM], + [undefined, LIVE_CONFIRM], + ] as const)('published=%s confirms an unsaved edit with %s', (published, key) => { + expect(aiDraftDiscardConfirmUnsaved('en-US', published)).toBe(en(key)); + }); +}); + +// --------------------------------------------------------------------------- +// The published-list reader: the object designer's Hooks tab. +// --------------------------------------------------------------------------- + +const PKG = 'com.example.showcase'; +const GUARD = { name: 'guard_hook', label: 'Guard', object: 'invoice', events: ['beforeInsert'], handler: 'guard_fn' }; +const AI_GUARD = { ...GUARD, label: 'Guard (AI)', condition: "record.status == 'held'" }; + +const hookDoor = { published: [] as Array>, aiDraft: false }; +const hookClient = { + list: vi.fn(async () => hookDoor.published), + listDrafts: vi.fn(async () => (hookDoor.aiDraft ? [{ type: 'hook', name: 'guard_hook' }] : [])), + getDraft: vi.fn(async (_type: string, name: string) => + hookDoor.aiDraft && name === 'guard_hook' + ? { + type: 'hook', + name, + item: { ...AI_GUARD }, + version: 'hmac-sha256:ai', + draftChanges: [{ path: ['condition'], by: 'copilot', actor: 'u1', at: '2026-11-27T10:00:00.000Z' }], + } + : null, + ), + get: vi.fn(async () => null), + withPreviewDrafts() { + return this; + }, + save: vi.fn(async () => ({ success: true, version: 'hmac-sha256:receipt', state: 'draft' })), + publish: vi.fn(async () => ({ success: true })), + reset: vi.fn(async () => ({ success: true })), +}; + +describe('the Hooks tab (published-list reader)', () => { + beforeEach(() => { + client.current = hookClient; + client.docTypes = false; + hookDoor.published = []; + hookDoor.aiDraft = true; + for (const fn of [hookClient.list, hookClient.listDrafts, hookClient.getDraft, hookClient.reset]) fn.mockClear(); + __setCelFormulaLoader(() => + Promise.resolve({ + validateExpression: () => ({ ok: true, errors: [], warnings: [] }), + introspectScope: () => ({ fields: ['status'], roots: ['record'], functions: ['has'] }), + inferExpressionType: () => 'boolean' as const, + }), + ); + }); + afterEach(() => { + __setCelFormulaLoader(undefined); + }); + + async function openGuard() { + render(); + fireEvent.click(await screen.findByText('Guard (AI)', undefined, { timeout: 8000 })); + } + + async function editCondition(value: string) { + fireEvent.click(await screen.findByText('Expression')); + const box = screen.getAllByRole('combobox').find((el) => el.tagName === 'TEXTAREA') as HTMLTextAreaElement; + fireEvent.change(box, { target: { value } }); + } + + it('a hook the AI created and nobody published: the discard says it deletes it, and so does the unsaved-edit confirm', async () => { + await openGuard(); + expect(await screen.findByTestId('studio-ai-draft-discard')).toHaveAttribute('title', en(DELETE_TITLE)); + await editCondition("record.status == 'unsaved'"); + fireEvent.click(screen.getByTestId('studio-ai-draft-discard')); + expect(confirmSpy).toHaveBeenCalledWith(en(DELETE_CONFIRM)); + // Declined: nothing is dropped. + expect(hookClient.reset).not.toHaveBeenCalled(); + }); + + it('a published hook with the AI\'s draft: the live-version wording, on the title and the confirm', async () => { + hookDoor.published = [GUARD]; + await openGuard(); + expect(await screen.findByTestId('studio-ai-draft-discard')).toHaveAttribute('title', en(LIVE_TITLE)); + await editCondition("record.status == 'unsaved'"); + fireEvent.click(screen.getByTestId('studio-ai-draft-discard')); + expect(confirmSpy).toHaveBeenCalledWith(en(LIVE_CONFIRM)); + expect(hookClient.reset).not.toHaveBeenCalled(); + }); +}); + +// --------------------------------------------------------------------------- +// The layers reader: the generic item page, over a real MetadataClient whose +// transport answers as the framework's `/meta` doors do. +// --------------------------------------------------------------------------- + +interface Row { + body: Record; + version: string; + draftChanges?: Array<{ path: string[]; by: string; actor: string; at: string }>; +} + +const server = { active: new Map(), drafts: new Map(), deletes: 0 }; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + +async function serve(input: RequestInfo | URL, init?: RequestInit): Promise { + const method = (init?.method ?? 'GET').toUpperCase(); + const url = new URL(String(input), 'http://console.test'); + const meta = url.pathname.match(/^\/api\/v1\/meta\/(.+)$/); + if (!meta) return json(200, []); + const seg = meta[1].split('/').map(decodeURIComponent); + if (seg[0] === '_drafts') { + return json(200, { drafts: [...server.drafts.keys()].map((k) => ({ type: k.split('/')[0], name: k.split('/')[1] })) }); + } + if (seg.length === 1) return json(200, { items: [{ name: 'guide' }] }); + const key = `${seg[0]}/${seg[1]}`; + if (seg.length === 3 && seg[2] === 'layers') { + const row = server.active.get(key); + return row + ? json(200, { + code: null, + overlay: row.body, + overlayScope: 'env', + effective: row.body, + draft: server.drafts.get(key)?.body ?? null, + overlayVersion: row.version, + editable: true, + deletable: true, + resettable: false, + lock: 'none', + }) + : json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); + } + if (seg.length === 3 && seg[2] === 'references') return json(200, []); + if (method === 'DELETE') { + server.deletes += 1; + return json(200, { success: true }); + } + if (url.searchParams.get('state') === 'draft') { + const row = server.drafts.get(key); + if (!row) return json(404, { error: { code: 'NO_DRAFT', message: 'absent' } }); + return json(200, { + type: seg[0], + name: seg[1], + item: row.body, + version: row.version, + ...(row.draftChanges ? { draftChanges: row.draftChanges } : {}), + }); + } + const row = server.active.get(key); + return row + ? json(200, { type: seg[0], name: seg[1], item: row.body }) + : json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); +} + +const metadataClient = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch }); + +const STUB_NS = 'ai-draft-never-published-38302'; +function StubMarkdown({ schema }: { schema: { content?: string } }) { + return
{schema.content}
; +} + +describe('the generic item page (layers reader)', () => { + beforeAll(() => { + ComponentRegistry.register('markdown', StubMarkdown as never, { namespace: STUB_NS }); + }); + afterAll(() => { + ComponentRegistry.unregister('markdown', STUB_NS); + }); + beforeEach(() => { + client.current = metadataClient; + client.docTypes = true; + server.active.clear(); + server.drafts.clear(); + server.deletes = 0; + server.drafts.set('doc/guide', { + body: { name: 'guide', label: 'Guide', content: '# From the AI', group: 'reference' }, + version: 'draft:ai', + draftChanges: [{ path: ['content'], by: 'copilot', actor: 'u1', at: '2026-11-24T10:00:00.000Z' }], + }); + window.history.replaceState(null, '', '/metadata/doc/guide'); + }); + afterEach(() => { + window.history.replaceState(null, '', '/'); + }); + + const source = () => screen.findByRole('textbox', { name: /Markdown source|Markdown/ }, { timeout: 8000 }); + + async function openGuide() { + render( + + + } /> + } /> + + , + ); + await source(); + await settle(); + } + + async function discardOverAnEdit() { + fireEvent.change(await source(), { target: { value: '# unsaved' } }); + await settle(); + fireEvent.click(screen.getByTestId('studio-ai-draft-discard')); + } + + it('an item the AI created and nobody published: the title and the in-app confirm say the discard deletes it', async () => { + await openGuide(); + expect(screen.getByTestId('studio-ai-draft-discard')).toHaveAttribute('title', en(DELETE_TITLE)); + await discardOverAnEdit(); + expect(await screen.findByTestId('resource-edit-confirm-body')).toHaveTextContent(en(DELETE_CONFIRM)); + fireEvent.click(screen.getByTestId('resource-edit-confirm-cancel')); + await settle(); + expect(server.deletes).toBe(0); + }); + + it('a published item with the AI\'s draft: the live-version wording, on the title and the confirm', async () => { + server.active.set('doc/guide', { + body: { name: 'guide', label: 'Guide', content: '# Live', group: 'reference' }, + version: 'pub:v0', + }); + await openGuide(); + await waitFor(() => + expect(screen.getByTestId('studio-ai-draft-discard')).toHaveAttribute('title', en(LIVE_TITLE)), + ); + await discardOverAnEdit(); + expect(await screen.findByTestId('resource-edit-confirm-body')).toHaveTextContent(en(LIVE_CONFIRM)); + expect(confirmSpy).not.toHaveBeenCalled(); + }); +}); + +// --------------------------------------------------------------------------- +// The sharing overview (OWD): a never-published object's row, over its own +// unsaved edit. The client is the panel's prop, not the mocked hook. +// --------------------------------------------------------------------------- + +describe('the sharing overview: a never-published object with a dirty row', () => { + type Body = Record; + const account = { name: 'crm_account', label: 'Account', sharingModel: 'private', fields: { name: { type: 'text' } } }; + const contact = { name: 'crm_contact', label: 'Contact', sharingModel: 'private' }; + const owd = { published: new Map(), drafts: new Map(), resets: [] as string[] }; + const owdClient = { + list: vi.fn(async (type: string) => + type === 'object' ? [...owd.published.values()].map((b) => ({ name: b.name, label: b.label })) : [], + ), + listDrafts: vi.fn(async () => [...owd.drafts.keys()].map((name) => ({ type: 'object', name }))), + layered: vi.fn(async (_type: string, name: string) => { + const pub = owd.published.get(name) ?? null; + return { effective: pub, code: null, overlay: pub }; + }), + getDraft: vi.fn(async (_type: string, name: string) => { + const body = owd.drafts.get(name); + return body + ? { + type: 'object', + name, + item: structuredClone(body), + version: `draft:${name}`, + draftChanges: [{ path: ['fields', 'notes'], by: 'copilot', actor: 'u1', at: '2026-11-27T10:00:00.000Z' }], + } + : null; + }), + save: vi.fn(async () => ({ success: true, version: 'draft:2', state: 'draft' })), + publish: vi.fn(async () => ({ success: true })), + reset: vi.fn(async (_type: string, name: string) => { + owd.resets.push(name); + owd.drafts.delete(name); + return { success: true }; + }), + }; + + beforeEach(() => { + Element.prototype.scrollIntoView = vi.fn(); + owd.published = new Map([['crm_contact', contact]]); + // The AI created Account; nobody published it. + owd.drafts = new Map([['crm_account', { ...account, fields: { ...account.fields, notes: { type: 'textarea' } } }]]); + owd.resets = []; + owdClient.reset.mockClear(); + }); + + async function pickOwd(testId: string, label: string): Promise { + fireEvent.keyDown(screen.getByTestId(testId), { key: 'ArrowDown' }); + const listbox = await screen.findByRole('listbox'); + fireEvent.click(within(listbox).getByRole('option', { name: label })); + } + + it('the title says the discard deletes it, and the confirm names only this row\'s unsaved change', async () => { + render( + + + , + ); + const row = await screen.findByTestId('owd-row-crm_account', undefined, { timeout: 8000 }); + expect(within(row).getByTestId('studio-ai-draft-discard')).toHaveAttribute('title', en(DELETE_TITLE)); + await pickOwd('owd-internal-crm_account', en('engine.studio.settings.sharingPublicRead')); + fireEvent.click(within(screen.getByTestId('owd-row-crm_account')).getByTestId('studio-ai-draft-discard')); + expect(confirmSpy).toHaveBeenCalledWith(en('engine.studio.owd.aiDraftDiscardConfirmUnsavedUnpublished')); + expect(confirmSpy).not.toHaveBeenCalledWith(en(DELETE_CONFIRM)); + // Declined: nothing is dropped, and the row keeps its edit. + expect(owdClient.reset).not.toHaveBeenCalled(); + expect(screen.getByTestId('owd-dirty-crm_account')).toBeInTheDocument(); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioAiDraftNotice.tsx b/ui/packages/app-shell/src/views/studio-design/StudioAiDraftNotice.tsx index f6c4e4dfed4..dc5d04e35a4 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioAiDraftNotice.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioAiDraftNotice.tsx @@ -6,6 +6,13 @@ * Save makes it live together with the page's own edits, and 「放弃 AI 的改动」 * drops that one item's draft, back to the live version. * + * objectstack#38302 — an item that was never published has no live version to + * go back to: dropping its draft deletes it. The host says which it is + * (`published`), and the button's title and the confirm the host asks over an + * unsaved edit ({@link aiDraftDiscardConfirmUnsaved}) say "deletes it" for an + * item that has none. A host that cannot tell passes nothing and keeps the + * live-version wording, as before. + * * The object page carries the same sentence and button inside its own AI line * (with its change count and Review); this is the line for the other item * pages, drawn the same way. @@ -16,9 +23,33 @@ import { Sparkles } from 'lucide-react'; import { cn } from '@object-ui/components'; import { t } from '../metadata-admin/i18n.js'; +/** + * The confirm a host asks before the discard drops an unsaved edit with the + * draft: the live-version wording when the item has a published version (or + * the host cannot tell), the delete wording when it has none. + */ +export function aiDraftDiscardConfirmUnsaved(locale: string, published: boolean | undefined): string { + return t( + published === false ? 'engine.studio.aiDraft.discardConfirmUnsavedUnpublished' : 'engine.studio.aiDraft.discardConfirmUnsaved', + locale, + ); +} + +/** + * The discard button's title: the live-version wording when the item has a + * published version (or the host cannot tell), the delete wording when it has none. + */ +export function aiDraftDiscardTitle(locale: string, published: boolean | undefined): string { + return t( + published === false ? 'engine.studio.aiDraft.discardTitleUnpublished' : 'engine.studio.aiDraft.discardTitle', + locale, + ); +} + export function StudioAiDraftNotice({ locale, text, + published, onDiscard, busy = false, className, @@ -26,6 +57,11 @@ export function StudioAiDraftNotice({ locale: string; /** The sentence, where the page names what the draft covers; else the item line's own. */ text?: string; + /** + * Whether the item has a published version: `false` = never published, so + * the discard deletes it; `undefined` = the host cannot tell, read as `true`. + */ + published?: boolean; /** Drop the item's draft; `undefined` draws no button (a read-only item). */ onDiscard?: () => void; busy?: boolean; @@ -50,7 +86,7 @@ export function StudioAiDraftNotice({ data-testid="studio-ai-draft-discard" onClick={onDiscard} disabled={busy} - title={t('engine.studio.aiDraft.discardTitle', locale)} + title={aiDraftDiscardTitle(locale, published)} className="ml-auto font-medium text-amber-700 hover:underline disabled:opacity-50 dark:text-amber-300" > {t('engine.studio.aiDraft.discard', locale)} diff --git a/ui/packages/app-shell/src/views/studio-design/StudioBackToApp.tsx b/ui/packages/app-shell/src/views/studio-design/StudioBackToApp.tsx index 372803e8ecb..cbbcf50f9c5 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioBackToApp.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioBackToApp.tsx @@ -17,10 +17,9 @@ * navigation, and `ConsoleLayout` records every app page * (`utils/appReturnPage.ts`); * 2. otherwise the package's own published app, on its first screen; - * 3. a package with no published app, the package-less scope (`~org`) and - * the cross-package leg (`~all`): the console's apps home - * (`useHomePath`), with no app name. A draft app has no running - * front-end yet, so it counts as none. + * 3. a package with no published app, and the cross-package leg (`~all`): + * the console's apps home (`useHomePath`), with no app name. A draft app + * has no running front-end yet, so it counts as none. * * Leaving asks first when a pillar holds unsaved work (`beforeNavigate`). */ diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.backToApp-36501.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.backToApp-36501.test.tsx index 8d4e8d61c64..ec84ea73ec8 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.backToApp-36501.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.backToApp-36501.test.tsx @@ -262,7 +262,7 @@ describe('studioBackTarget — the order of the three answers (objectstack#36501 appLabel: 'Service', }); }); - it('no app, or the package-less scope: the apps home, unnamed, whatever is recorded', () => { + it('no app, or no package open: the apps home, unnamed, whatever is recorded', () => { const foreign = { path: '/apps/x/y', app: 'x', label: 'X app' }; expect(studioBackTarget({ ...base, remembered: foreign, apps: [] })).toEqual({ path: '/landing', appLabel: null }); expect(studioBackTarget({ ...base, remembered: null, apps: [] })).toEqual({ path: '/landing', appLabel: null }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.designerRegistryMissing.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.designerRegistryMissing.test.tsx index 7b616c9febd..55cd4dc99de 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.designerRegistryMissing.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.designerRegistryMissing.test.tsx @@ -287,8 +287,8 @@ describe('Automations pillar — the fourth site, found by sweeping (#6795 C, si mockClient.layered.mockClear(); render( - - + + , ); @@ -297,7 +297,9 @@ describe('Automations pillar — the fourth site, found by sweeping (#6795 C, si 'No metadata designers are registered in this session, so this flow cannot be designed here.', ); // The header's chip; objectstack#36903 — no Configuration aside is drawn - // beside a flow the scope does not hold, so the chip is the one site. + // beside a flow the package does not hold, so the chip is the one site. + // objectstack#38150 — mounted on a package: the designer is a package's + // now (it was the retired package-less scope's here). expect(hits.length).toBe(1); expect(mockClient.layered).not.toHaveBeenCalledWith('flow', expect.anything()); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.homeLoop-12513.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.homeLoop-12513.test.tsx index 8968e49466d..12c96ae0355 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.homeLoop-12513.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.homeLoop-12513.test.tsx @@ -4,15 +4,12 @@ * objectui#12513 — the Studio home loop. Inside a package the header's first * button and the package switcher's first row both returned to the Studio * landing (`/studio`); objectstack#36501 replaced both with 「‹ Back to app」 (since objectstack#36899 right after the menu toggle), - * and the first case below now says so. The Organization flows empty block's way out to - * Setup › Packaged automation retired with that page's flows half (objectstack - * ADR-0146 D11, N-28): the block now says where a packaged flow is changed, - * and links nowhere. + * and the first case below now says so. The Organization flows empty block went with the + * package-less scope it was drawn on, which is retired (objectstack#38150). * * Rendered through the REAL `StudioDesignSurface` on the REAL route shape, on * the server double objectui#11553's file uses: a read-only showcase package - * with two packaged flows, and no package-less flow (so the Organization - * flows scope is empty). + * with two packaged flows, and no package-less flow. */ import '@testing-library/jest-dom/vitest'; @@ -134,7 +131,7 @@ const dataSource = createEmptyDataSource(); failOnAbsorbedFetchError(); // The two global-`fetch` reads on this surface: the pending-drafts feed -// (`/meta/_drafts`, the header count and the package-less publish) and the +// (`/meta/_drafts`, the header count) and the // rail's `/automation/_status` probe (answered "absent", so no dots). vi.stubGlobal( 'fetch', @@ -224,6 +221,5 @@ describe('Studio home loop (objectui#12513)', () => { expect(within(screen.getByTestId('studio-brand-row')).getByTestId('studio-menu-toggle')).toBeTruthy(); expect(screen.queryByRole('button', { name: 'App Studio home' })).toBeNull(); }); - // objectstack#36903 — the Automations rail's empty blocks went with the rail: - // the package-less scope's list offers no create (StudioDesignSurface.packageLessFlows-11553). + // objectstack#36903 — the Automations rail's empty blocks went with the rail. }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx index 7ab3846727c..271785e235c 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx @@ -306,7 +306,9 @@ describe('⌘K on the builder (objectstack#36900)', () => { await waitFor(() => expect(overlay()).not.toBeNull()); expect(new URL(where(), 'http://x').searchParams.get('palette')).toBe('1'); await waitFor(() => expect(paletteItem('studio-entry type:flow')).not.toBeNull()); - expect(paletteItem('studio-entry orgFlows')).not.toBeNull(); + // objectstack#38150 — the organization's flows left the menu with their scope: no entry for them. + expect(paletteItem('studio-entry owd')).not.toBeNull(); + expect(paletteItem('studio-entry orgFlows')).toBeNull(); fireEvent.click(paletteItem('studio-entry type:flow')!); expect((await areaPage()).page).toBe('list'); @@ -324,7 +326,10 @@ describe('⌘K on the builder (objectstack#36900)', () => { fireEvent.keyDown(document, { key: 'k', ctrlKey: true }); await waitFor(() => expect(overlay()).not.toBeNull()); - await waitFor(() => expect(paletteItem('studio-entry orgFlows')).not.toBeNull()); + // The environment's menu is the environment catalog's types; objectstack#38150 — the + // organization's flows, the entry this waited on, retired with the package-less scope. + await waitFor(() => expect(paletteItem('studio-entry type:permission')).not.toBeNull()); + expect(paletteItem('studio-entry orgFlows')).toBeNull(); expect(paletteItem('studio-entry environment')).toBeNull(); expect(paletteItem('studio-entry diagnostics')).toBeNull(); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx index 6d01cf11141..e93abe87fa5 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx @@ -114,10 +114,10 @@ function SetupPackages() { return
{search}
; } -/** Studio's package-less scope (`~org`), with the address it was opened at. */ -function OrgScope() { +/** Studio's cross-package leg (`~all`), with the address it was opened at. */ +function CrossPackageLeg() { const { pathname, search } = useLocation(); - return
{`${pathname}${search}`}
; + return
{`${pathname}${search}`}
; } /** Holds the two capabilities Setup → Packages is shown under. */ @@ -139,7 +139,7 @@ function renderAt( } /> - } /> + } /> {/* objectstack#36904, objectstack#36903 — `/data` and `/automations` land on the area's object and flow lists. */} , { area: 'metadata' })} /> {surface}} /> @@ -204,7 +204,9 @@ describe('Studio: a package id no package has renders "package not found" (objec expect(screen.queryByTestId('studio-menu-toggle')).toBeNull(); expect(screen.queryByTestId('studio-mobile-strip')).toBeNull(); expect(screen.queryByRole('button', { name: new RegExp(t('engine.studio.publish', 'en')) })).toBeNull(); - expect(screen.queryByRole('button', { name: new RegExp(t('engine.studio.changes', 'en')) })).toBeNull(); + // objectstack#38150 — the Changes row retired with the package-less scope; none is drawn here either. + expect(screen.queryByRole('button', { name: /^Changes/ })).toBeNull(); + expect(screen.queryByTestId('studio-scope-changes')).toBeNull(); expect(screen.queryByTitle(t('engine.studio.app.noneTitle', 'en'))).toBeNull(); // The one list read the builder already makes — no second request. expect(packageListReads(fetchMock)).toBe(1); @@ -218,14 +220,16 @@ describe('Studio: a package id no package has renders "package not found" (objec expect(await screen.findByTestId('setup-packages')).toHaveTextContent('?face=admin'); }); - // objectstack#37565 — the cross-package directory moved to Setup; the way out is the package-less scope, for now. - it('for a principal who may enter Studio but not Setup → Packages, it opens the package-less scope, never Setup (objectstack#36908)', async () => { + // objectstack#37565 — the cross-package directory moved to Setup. objectstack#38150 — the + // package-less scope the way out opened next is retired: it opens the Loose list of flows, + // where that scope's addresses land. + it('for a principal who may enter Studio but not Setup → Packages, it opens the Loose list of flows, never Setup (objectstack#36908)', async () => { servePackages(); renderAt(`/studio/${PHANTOM}/data`, , STUDIO_ONLY); const notFound = await screen.findByTestId('studio-package-not-found'); expect(within(notFound).queryByRole('button', { name: t('engine.studio.notFound.packageList', 'en') })).toBeNull(); within(notFound).getByRole('button', { name: t('engine.studio.notFound.allMetadata', 'en') }).click(); - expect(await screen.findByTestId('org-scope')).toHaveTextContent('/studio/~org/metadata/flow?source=runtime'); + expect((await screen.findByTestId('cross-package-leg')).textContent).toBe('/studio/~all/metadata/flow?source=loose'); expect(screen.queryByTestId('setup-packages')).toBeNull(); }); @@ -235,13 +239,17 @@ describe('Studio: a package id no package has renders "package not found" (objec await listAnswered(fetchMock); expect(screen.queryByTestId('studio-package-not-found')).toBeNull(); // objectstack#36899 — the left menu drawn. objectstack#37201 — the 常用 groups of the served - // types (object, flow, permission), and the 「高级」 fold holding the four entries that are not a type. + // types (object, flow, permission), and the 「高级」 fold holding the entries that are not a type. + // objectstack#38150 — two of them now, diagnostics and the sharing overview: the organization's + // flows retired with the package-less scope, and the fold's 自动化 Automation group with it. for (const group of ['data', 'automation', 'security']) { expect(within(menu()).getByTestId(`studio-menu-group-${group}`)).toBeInTheDocument(); } - for (const group of ['automation', 'system', 'security']) { + for (const group of ['system', 'security']) { expect(within(menu()).getByTestId(`studio-menu-advanced-group-${group}`)).toBeInTheDocument(); } + expect(within(menu()).queryByTestId('studio-menu-advanced-group-automation')).toBeNull(); + expect(within(menu()).queryByTestId('studio-menu-entry-orgFlows')).toBeNull(); }); it('CONTROL — a kernel package the Studio landing hides is installed, never "not found"', async () => { diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageLessFlows-11553.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageLessFlows-11553.test.tsx index 0ee71e12e92..22ead62b97a 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageLessFlows-11553.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageLessFlows-11553.test.tsx @@ -3,7 +3,7 @@ /** * objectui#11553 — a package-less flow (a clone of a packaged flow, which * ADR-0126 §7.1 makes "an ordinary org/install-owned flow") is reachable in - * Studio, editable, and its deep link opens it and no other flow. + * Studio, and a deep link naming it opens it and no other flow. * * Measured on objectstack 17.6.0 with the console at the pin: the clone's row * names no package; the package-scoped flow list omits it and the bare list @@ -11,25 +11,35 @@ * rail read the package-scoped list, and a deep link naming the clone as the * surface opened the package's first flow instead. * - * Rendered through the REAL `StudioDesignSurface` on the REAL route shape, with - * the real registered `FlowPreview` / `FlowInspector`, so "opens editable" is - * what the canvas and the switch actually offer. The server double answers the - * metadata reads the way the platform does: a `packageId` list keeps only rows - * whose `_packageId` equals it, and the unscoped list returns every row. Each - * package-less case has its packaged control (the read-only package below - * stays read-only, as objectui#11124 pins at the pillar). + * objectstack#38150 — the package-less scope that answered this + * (`/studio/~org/…`) is retired (ADR-0084, amended 2026-11-26, + * `#amendment-2026-11-26-org`). What this file pins now: + * + * - every address of the retired scope lands on the Loose list of flows on + * the cross-package leg, `/studio/~all/metadata/flow?source=loose`, which + * lists the clone and none of a package's flows; + * - the clone's row there opens its item page on that leg; a package's + * address that names the clone lands on that page too, and still opens no + * other flow; + * - that item page opens writable, and an edit saved there writes a draft + * naming no package; a draft of the clone is published, or discarded, from + * that page; + * - no menu row, no Changes row and no changes sheet is drawn for the + * retired scope; a package keeps its own. * - * objectstack#36903 — the scope's flows live in its own leg of the "All - * metadata" area: the list at `/studio/~org/metadata/flow?source=runtime`, a - * flow full-screen at `/studio/~org/metadata/flow/?source=runtime`; the - * old `/studio/~org/automations` addresses redirect there. + * Rendered through the REAL `StudioDesignSurface` on the REAL route shape, with + * the real registered `FlowPreview` / `FlowInspector`. The server double + * answers the metadata reads the way the platform does: a `packageId` list + * keeps only rows whose `_packageId` equals it, and the unscoped list returns + * every row. The packaged control (the read-only package below stays + * read-only, as objectui#11124 pins at the pillar) is unchanged. */ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react'; -import { MemoryRouter, Route, Routes, useLocation, useNavigate } from 'react-router-dom'; +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; const SHOWCASE = 'com.example.showcase'; /** objectstack#36903 — the showcase's paired customization package, listed only where a case says so. */ @@ -55,6 +65,9 @@ const server = vi.hoisted(() => ({ saves: [] as Array<{ type: string; name: string; options: Record | undefined; body: Record }>, publishedByRef: [] as Array<{ type: string; name: string }>, packageBatches: [] as string[], + /** The item page's own publish and discard, as the client was called. */ + itemPublishes: [] as Array<{ type: string; name: string; options: Record | undefined }>, + itemResets: [] as Array<{ type: string; name: string; options: Record | undefined }>, })); const mockClient = vi.hoisted(() => ({ @@ -78,6 +91,12 @@ const mockClient = vi.hoisted(() => ({ return { code: null, overlay: row ? eff : null, overlayScope: row ? 'env' : null, effective: row ? eff : null }; }), getDraft: vi.fn(async (type: string, name: string) => { + // A pending draft's stored body, where the ledger holds a row for the item. + const row = server.active.get(`${type}/${name}`); + if (row && server.drafts.some((d) => d.type === type && d.name === name)) { + const { __type: _t, ...item } = row; + return { item: { ...item, label: `${String(item.label)} (draft)` } }; + } throw Object.assign(new Error(`No pending draft exists for ${type}/${name}.`), { code: 'NO_DRAFT', status: 404 }); }), save: vi.fn(async (type: string, name: string, item: unknown, options?: Record) => { @@ -92,8 +111,16 @@ const mockClient = vi.hoisted(() => ({ server.packageBatches.push(packageId); return { success: true, failed: [] }; }), - publish: vi.fn(async () => ({ success: true })), - reset: vi.fn(async () => ({})), + publish: vi.fn(async (type: string, name: string, options?: Record) => { + server.itemPublishes.push({ type, name, options }); + server.drafts = server.drafts.filter((d) => !(d.type === type && d.name === name)); + return { success: true, version: 2 }; + }), + reset: vi.fn(async (type: string, name: string, options?: Record) => { + server.itemResets.push({ type, name, options }); + server.drafts = server.drafts.filter((d) => !(d.type === type && d.name === name)); + return {}; + }), })); /** Whether the package list serves the showcase's pair (objectstack#36903, the pair's bookmarks). */ @@ -104,9 +131,16 @@ const panel = vi.hoisted(() => ({ props: null as null | Record /** Read through a call, so a reset between renders does not narrow it away. */ const panelProps = (): Record | null => panel.props; +/** + * The type registry the surface is served. Empty by default, as this file has + * always run; the item-page cases serve the platform's own `flow` row, because + * the item page's Publish and Discard are offered by that row's flags. + */ +const registry = vi.hoisted(() => ({ entries: [] as Array> })); + vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { const mod = await importOriginal(); - return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; + return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: registry.entries }) }; }); vi.mock('./packages-io', async (importOriginal) => { @@ -156,8 +190,11 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.f // The console's preview and authoring code loads `@objectstack/lint` lazily; // warmed here so its first load is paid at import, not inside a test's clock. import '@objectstack/lint'; +import { DEFAULT_METADATA_TYPE_REGISTRY } from '@objectstack/spec/kernel'; import { StudioDesignSurface } from './StudioDesignSurface'; import { StudioPillarRedirect } from './StudioPillarRedirect'; +import { StudioEntryPermissionsProvider, studioEntryFallbackPath } from './studioEntryPermissions'; +import { packageLessItemPath } from './studioScope'; import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; import { getMetadataPreview, registerMetadataPreview } from '../metadata-admin/preview-registry'; import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; @@ -219,7 +256,10 @@ beforeEach(() => { server.saves.length = 0; server.publishedByRef.length = 0; server.packageBatches.length = 0; + server.itemPublishes.length = 0; + server.itemResets.length = 0; panel.props = null; + registry.entries = []; listing.pair = false; for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear(); // Two packaged flows on the read-only showcase, and the clone, which names no package. @@ -235,30 +275,34 @@ function LocationProbe() { return
{`${pathname}${search}`}
; } -/** A route change into the package-less scope, the surface left mounted. */ -function OrgScopeDoor() { - const navigate = useNavigate(); - return
); } - if (opens.designer && type === 'flow') { - // objectstack#36903 — the flow designer, full-screen on the flow's - // address. The package-less scope's flows are the organization's own and - // open writable (its area is read-only to the list's create alone). + if (opens.designer && host?.packageId && type === 'flow') { + // objectstack#36903 — the flow designer, full-screen on the flow's address. return (
); } + // objectstack#37087 — a form opens Studio's form editor (its registered + // `EditPage`), handed what only the area's surface holds: a read-only base's + // customization, where a form the app ships is saved as a declared override. + if (type === 'form' && host?.packageId) { + return ( + + ); + } return ; } @@ -407,12 +412,6 @@ export interface StudioMetadataAreaProps { * at the item it refused. */ publishRefusalFor?: (type: string, name: string) => StudioRefusal | null; - /** - * objectstack#36903 — the area of the package-less scope (`~org`, with no - * `packageId`): its flows, listed and opened full-screen. It creates nothing - * (`studioScope.ts`), so its host is read-only to the list's create. - */ - orgScope?: boolean; /** objectstack#36904, objectstack#36903 — handed to the object and flow designers (`AreaEditorProps`). */ onHeldEditChange?: (clause: string | null) => void; onReviewChanges?: () => void; @@ -424,7 +423,6 @@ export function StudioMetadataArea({ publishNonce = 0, onDraftSaved, publishRefusalFor, - orgScope = false, onHeldEditChange, onReviewChanges, }: StudioMetadataAreaProps): React.ReactElement { @@ -432,39 +430,31 @@ export function StudioMetadataArea({ const locale = useMetadataLocale(); // objectstack#37565 — whoever may open Setup has the leg's directory there. const toSetup = holdsSetupAccess(useStudioEntryPermissions()); - const segment = packageId ?? (orgScope ? STUDIO_ORG_SCOPE_SEGMENT : STUDIO_ALL_PACKAGES_SEGMENT); + const segment = packageId ?? STUDIO_ALL_PACKAGES_SEGMENT; const basePath = studioMetadataAreaPath(segment); // The courtesy gate the pillars apply, read for the area from the listed // manifests (see the hook). Unknown stays ungated, as on the pillars: the // server's write gate is the authority, and a failed probe must not lock an // author out of a writable package. const { writable, kernel } = useListedPackageWritable(packageId); - // objectstack#36903 — the package-less scope creates nothing: read-only to - // the list's create (its designer opens writable, `AreaItemOpen`). - const readOnly = orgScope || (packageId !== null && writable === false); + const readOnly = packageId !== null && writable === false; // objectstack#36897 — the list offers a create exactly where `AreaCreate` // opens one in the pair; never on a kernel package, which has none. const pairCreate = readOnly && !kernel && !!customization && !customization.walled; - // objectstack#36903 — the scope's empty flow list keeps the guidance its - // pillar's empty state gave: a packaged flow is changed in its package, with - // New similar (ADR-0146 D11). - const emptyListHint = orgScope ? t('engine.studio.org.none', locale) : undefined; const host = React.useMemo( () => ({ packageId, readOnly, basePath, ...(pairCreate ? { pairCreate } : {}), - ...(emptyListHint ? { emptyListHint } : {}), }), - [packageId, readOnly, basePath, pairCreate, emptyListHint], + [packageId, readOnly, basePath, pairCreate], ); const editor: AreaEditorProps = { customization, publishNonce, onDraftSaved, publishRefusalFor, - orgScope, onHeldEditChange, onReviewChanges, }; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu-37139.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu-37139.test.tsx index 86b10801b65..2c8efc71336 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu-37139.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu-37139.test.tsx @@ -15,12 +15,16 @@ * (`StudioPackageOverview-37454.test.tsx`); case 5 still holds both to the * development face's one copy. * + * objectstack#38150 — "Adopt loose items" retired with its door + * (`POST /packages/:id/adopt-orphans`), so the menu holds three rows; loose + * items move by an explicit selection now (`POST /packages/:id/move-in`). + * * 1. A `manage_metadata` holder on a package's overview sees it, at the end - * of the header, with its four items in their order, in en and zh-CN. - * 2. Each item's greyed state: on a read-only package Edit package info, - * Duplicate and Adopt are greyed (the server refuses each there). Manage - * in Setup… is never greyed. - * 3. No 「⋯」 on `~org` or `~all` (no current package): its one home, a + * of the header, with its three items in their order, in en and zh-CN. + * 2. Each item's greyed state: on a read-only package Edit package info and + * Duplicate are greyed (the server refuses each there). Manage in Setup… + * is never greyed. + * 3. No 「⋯」 on `~all` (no current package), where the retired `~org` lands too: its one home, a * package's overview, is not drawn there at its own address. None for a * user without `manage_metadata`. * 4. Each item does what the development face's action does: the same door, @@ -145,7 +149,6 @@ beforeEach(() => { const method = (init?.method ?? 'GET').toUpperCase(); if (method !== 'GET') { srv.writes.push({ method, path, body: init?.body ? JSON.parse(String(init.body)) : null }); - if (path.endsWith('/adopt-orphans')) return json({ success: true, data: { success: true, reassignedCount: 3, reassigned: [] } }); if (path.endsWith('/duplicate')) return json({ success: true, data: { success: true, copiedCount: 2, failedCount: 0 } }); return json({ success: true, data: {} }); } @@ -245,11 +248,11 @@ async function pendingRead(count: number) { // --------------------------------------------------------------------------- const LABELS: Record<'en-US' | 'zh-CN', string[]> = { - 'en-US': ['Edit package info', 'Duplicate as a new package', 'Adopt loose items', 'Manage in Setup…'], - 'zh-CN': ['编辑软件包信息', '复制为新软件包', '收编散落项', '在设置中管理…'], + 'en-US': ['Edit package info', 'Duplicate as a new package', 'Manage in Setup…'], + 'zh-CN': ['编辑软件包信息', '复制为新软件包', '在设置中管理…'], }; -describe('the 「⋯」 package menu: in the overview header, four items in their order (objectstack#37139, objectstack#37454, objectstack#37958)', () => { +describe('the 「⋯」 package menu: in the overview header, three items in their order (objectstack#37139, objectstack#37454, objectstack#37958, objectstack#38150)', () => { it.each(['en-US', 'zh-CN'] as const)('%s: a manage_metadata holder sees it in the overview header, and not in the left column', async (locale) => { localeFixture = locale; renderAt(`/studio/${OWN}/overview`); @@ -271,7 +274,7 @@ describe('the 「⋯」 package menu: in the overview header, four items in thei ); expect(items.map((i) => i.textContent?.trim())).toEqual(LABELS[locale]); // objectstack#37958 — Export and the revert are the page's own now. - expect(STUDIO_PACKAGE_MENU_ITEMS).toEqual(['edit', 'duplicate', 'adopt', 'manage']); + expect(STUDIO_PACKAGE_MENU_ITEMS).toEqual(['edit', 'duplicate', 'manage']); // No 「发布全部草稿」: the top bar's Changes / Publish already do it. expect(content.textContent).not.toMatch(locale === 'zh-CN' ? /发布全部|草稿/ : /Publish all|draft/i); }); @@ -291,7 +294,7 @@ describe('which items are greyed (objectstack#37139)', () => { for (const id of STUDIO_PACKAGE_MENU_ITEMS) expect(isGreyed(id), id).toBe(false); }); - it.each(['en-US', 'zh-CN'] as const)('%s: a read-only installed package greys Edit, Duplicate and Adopt, and says why', async (locale) => { + it.each(['en-US', 'zh-CN'] as const)('%s: a read-only installed package greys Edit and Duplicate, and says why', async (locale) => { localeFixture = locale; renderAt(`/studio/${INSTALLED}/overview`); await settledOn('Vendor CRM'); @@ -302,11 +305,10 @@ describe('which items are greyed (objectstack#37139)', () => { expect({ edit: isGreyed('edit'), duplicate: isGreyed('duplicate'), - adopt: isGreyed('adopt'), manage: isGreyed('manage'), - }).toEqual({ edit: true, duplicate: true, adopt: true, manage: false }); + }).toEqual({ edit: true, duplicate: true, manage: false }); const reason = t('engine.studio.pkg.readonlyHint', locale); - for (const id of ['edit', 'duplicate', 'adopt']) { + for (const id of ['edit', 'duplicate']) { expect(menuItem(id)).toHaveAttribute('data-disabled-reason', reason); } }); @@ -330,10 +332,13 @@ describe('no 「⋯」 without a current package or without manage_metadata (obj // check asks for the overview's own address on the two scopes: neither draws // it, so neither draws the menu. (Asked on their other pages it would pass // whatever the scopes did, the overview being absent there anyway.) + // objectstack#38150 — `~org` is retired: its overview address redirects to + // the Loose list of flows on the cross-package leg, which the leg's + // switcher names; the page it used to draw is gone. it.each(['en-US', 'zh-CN'] as const)('%s: none on ~org/overview and none on ~all/overview', async (locale) => { localeFixture = locale; renderAt('/studio/~org/overview'); - await waitFor(() => expect(within(header()).getByTestId('studio-pkg-switcher-name')).toHaveTextContent(t('engine.studio.pkg.orgScope', locale)), { + await waitFor(() => expect(within(header()).getByTestId('studio-pkg-switcher-name')).toHaveTextContent(t('engine.studio.menu.environment', locale)), { timeout: 8000, }); expect(screen.queryByTestId('studio-package-overview')).toBeNull(); @@ -379,20 +384,6 @@ describe('no 「⋯」 without a current package or without manage_metadata (obj // --------------------------------------------------------------------------- describe('each item runs the development face’s action (objectstack#37139)', () => { - it('Adopt loose items asks first, then adopts and says how many moved', async () => { - renderAt(`/studio/${OWN}/overview`); - await settledOn('Sales'); - await openMenu(); - fireEvent.click(menuItem('adopt')); - const dialog = await screen.findByTestId('pkg-detail-adopt-dialog'); - expect(srv.writes).toEqual([]); - fireEvent.click(within(dialog).getByTestId('pkg-detail-adopt-confirm')); - await waitFor(() => - expect(toast.success).toHaveBeenCalledWith(tFormat('engine.packages.detail.adoptedOther', 'en-US', { count: 3 })), - ); - expect(srv.writes.map((w) => `${w.method} ${w.path}`)).toEqual([`POST /api/v1/packages/${OWN}/adopt-orphans`]); - }); - it('Duplicate opens the development face’s form on 「Copy of NAME」 and `-copy`, and sends the duplicate', async () => { renderAt(`/studio/${OWN}/overview`); await settledOn('Sales'); @@ -451,8 +442,6 @@ describe('the menu, the overview page and the development face share one copy of const shared: Array<[string, string]> = [ ['revertPackage', overview], ['exportPackageFile', overview], - ['adoptLooseItems', menu], - ['AdoptLooseItemsDialog', menu], ['DuplicatePackageForm', menu], ['EditPackageDialog', menu], ]; @@ -464,7 +453,7 @@ describe('the menu, the overview page and the development face share one copy of } }); - it('no surface spells the revert or adopt door itself, and Studio does not spell the export door', () => { + it('no surface spells the revert door, nor the retired adopt door (objectstack#38150), itself, and Studio does not spell the export door', () => { for (const source of [menu, overview, page]) { // A request spelled in place: `${…}/revert` in a template literal. expect(source).not.toMatch(/\}\/revert`|\}\/adopt-orphans`/); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu.tsx b/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu.tsx index 6357edf4f4b..d388754ec59 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu.tsx @@ -14,15 +14,15 @@ * a dialog. The server refuses to duplicate a read-only package * (`DUPLICATE_SOURCE_NOT_A_BASE`) and the development face does not offer * it there, so it is greyed there too. - * 3. Adopt loose items — the development face's confirmation, then its - * adoption; greyed on a read-only package. - * 4. Manage in Setup… — Setup → Packages on this package's row, where it is + * 3. Manage in Setup… — Setup → Packages on this package's row, where it is * enabled, disabled or deleted. * * Export and Revert to last publish were rows here until objectstack#37958: * Export is now a button of the overview's header and the revert stands on its * Publish history tab (`StudioPackageOverviewPage`), where both act on the - * package's customizations when it has them. + * package's customizations when it has them. Adopt loose items retired with + * its door (objectstack#38150): loose items move by an explicit selection now + * (`POST /packages/:id/move-in`). * * Every request, dialog and form is the development face's own, imported from * `metadata-admin/packageActions.tsx`; ⛔ never a second copy. What differs is @@ -33,7 +33,7 @@ * B), reached by Manage in Setup…. * * The host draws the menu only where there is a current package (never on - * `~org` or `~all`) and only for a `manage_metadata` holder + * `~all`) and only for a `manage_metadata` holder * (`useCanAuthorMetadata`). Writability the host has not learned yet (still * reading, or the read failed) greys nothing: the server's write gate stays the * authority, the same courtesy posture as the rest of Studio. @@ -41,7 +41,7 @@ import * as React from 'react'; import { toast } from 'sonner'; -import { Copy, Inbox, MoreHorizontal, Pencil, Settings } from 'lucide-react'; +import { Copy, MoreHorizontal, Pencil, Settings } from 'lucide-react'; import { Dialog, DialogContent, @@ -56,21 +56,18 @@ import { } from '@object-ui/components'; import { t, tFormat } from '../metadata-admin/i18n.js'; import { - AdoptLooseItemsDialog, DuplicatePackageForm, EditPackageDialog, - adoptLooseItems, - adoptedText, } from '../metadata-admin/packageActions.js'; import type { PackageManifestRow } from '../metadata-admin/PackagesPage.js'; import { setupPackagePath } from '../metadata-admin/packageSource.js'; import { duplicatePackage, fetchListedPackageManifests } from './packages-io.js'; /** The menu's items, in their order; each `data-testid` is `studio-package-menu-`. */ -export const STUDIO_PACKAGE_MENU_ITEMS = ['edit', 'duplicate', 'adopt', 'manage'] as const; +export const STUDIO_PACKAGE_MENU_ITEMS = ['edit', 'duplicate', 'manage'] as const; export type StudioPackageMenuItem = (typeof STUDIO_PACKAGE_MENU_ITEMS)[number]; -type Busy = 'edit' | 'duplicate' | 'adopt' | null; +type Busy = 'edit' | 'duplicate' | null; const failureText = (e: unknown, locale: string): string => e instanceof Error && e.message ? e.message : t('engine.packages.detail.actionFailed', locale); @@ -80,7 +77,6 @@ export function StudioPackageMenu({ packageName, writable, locale, - onChanged, onRenamed, beforeNavigate, navigate, @@ -92,8 +88,6 @@ export function StudioPackageMenu({ /** The server's verdict; `null` / `undefined` while unknown greys nothing. */ writable: boolean | null | undefined; locale: string; - /** An adoption changed what the package holds: the host re-reads it. */ - onChanged: () => void; /** The package info was saved under this name. */ onRenamed: (name: string) => void; /** The host's unsaved-work veto: return false to stay. */ @@ -105,23 +99,10 @@ export function StudioPackageMenu({ const [editOpen, setEditOpen] = React.useState(false); const [dupOpen, setDupOpen] = React.useState(false); const [dupRefusal, setDupRefusal] = React.useState(null); - const [adoptOpen, setAdoptOpen] = React.useState(false); const readOnly = writable === false; const readOnlyReason = t('engine.studio.pkg.readonlyHint', locale); - /** One action from start to answer: busy while it runs, a toast with its answer. */ - async function run(action: Exclude, fn: () => Promise) { - setBusy(action); - try { - toast.success(await fn()); - } catch (e) { - toast.error(failureText(e, locale)); - } finally { - setBusy(null); - } - } - // The Edit dialog reads the package's manifest as `/api/v1/packages` lists // it, the row the development face's sheet opens it on. const openEdit = () => @@ -206,13 +187,6 @@ export function StudioPackageMenu({ }, readOnly ? readOnlyReason : null, )} - {item( - 'adopt', -