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/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 index c4f0111e975..68beb2b9aeb 100644 --- a/.changeset/37815-body-capabilities-every-gate.md +++ b/.changeset/37815-body-capabilities-every-gate.md @@ -11,12 +11,12 @@ Skills-docs: follow-up #38655 -**BREAKING** for the publish of an action, an object or a hook whose authored 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. +**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 authored 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. Only a body the author wrote is judged: a hook body `os build` / `os verify` lowered from an inline `handler` is not, since its grant is the build's inference (the lowered reading is #38653). Runs on the runtime `hook` door. -- `action-body-capability-undeclared` (new): an authored 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 not judged for these tokens, since its grant is the build's inference (the lowered reading is #38653); its writes are still judged under `action-body-write-capability-undeclared`. Runs on the runtime `action` and `object` doors. +- `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 @@ -25,6 +25,6 @@ The gates are the sandbox runner's own, token by token, and the rule's list is p - 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 whose body was lowered from an inline `handler` is unchanged: FROM and TO alike, it is not judged by this rule. So is an action whose body was lowered from an inline `target` function, for every token but `api.write`: FROM, `actions: [{ …, target: async (ctx) => { await ctx.api.transaction(…) } }]` built clean; TO, it still builds clean, and its writes are judged as before. +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/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/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/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-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/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/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/AGENTS.md b/AGENTS.md index 59ae98a6890..dc248ee2e3c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -545,16 +545,16 @@ Even inside your own worktree, operate defensively: 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; 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)): + `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. - - **Full `pnpm typecheck && pnpm test` again only when** the incoming commits touch the packages or behavior your - diff does, or a conflict occurred outside trivially-mechanical files. + - **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 @@ -1012,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/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 9e88a9beea9..5e0223f82e4 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -131,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'); diff --git a/content/docs/deployment/stored-forms-upgrade.mdx b/content/docs/deployment/stored-forms-upgrade.mdx index 676dd87ddf7..4e3d63b6bd3 100644 --- a/content/docs/deployment/stored-forms-upgrade.mdx +++ b/content/docs/deployment/stored-forms-upgrade.mdx @@ -14,7 +14,7 @@ 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. +command ([below](#what-the-upgrade-command-writes)). ```bash os migrate stored-forms @@ -35,12 +35,21 @@ 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. Older rows of the same form 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. Older rows of the same form fold into it. | +| **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). | +| **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 @@ -73,6 +82,44 @@ 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 | @@ -82,6 +129,7 @@ that is closed today. | 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 diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index b47aa3aa6f5..39306d40c23 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -524,9 +524,9 @@ orthogonal to both, and no cell here can carry it; it is written out in | 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`, `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 authored L2 action body (one `os build` lowered from a `target` function is judged for its writes only) 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) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | +| 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 authored L2 hook body (one `os build` lowered from a `handler` is not judged) 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) | ✓ | ✓ | ✓ | ✓ʰ | +| 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`) | ✓ | ✓ | ✓ | ✓ᵒᵖᵉᵇᵖᵒᵃᵒˣ | diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 80c896266a8..b5fd954319a 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -182,12 +182,32 @@ that name (ADR-0161 K4): 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 +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`). The -mode is read by search alone: it enters neither the index fingerprint nor the -recipe hash, so changing it rebuilds nothing. +(`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 @@ -260,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. @@ -788,7 +809,10 @@ an exact scan. [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 @@ -865,7 +889,10 @@ large source of one organization, through an approximate index. 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 diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index dddfea3227b..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); @@ -180,6 +180,7 @@ const result = ApiMethod.parse(data); | **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) | @@ -408,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 | @@ -1037,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/index.mdx b/content/docs/references/index.mdx index c3b14606ade..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 — 1749 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/. */} @@ -25,7 +25,7 @@ counts are sums of the rows they head. Regenerate with | [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. | @@ -36,7 +36,7 @@ counts are sums of the rows they head. Regenerate with | [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 | 188 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **224** | **1749** | 14 protocol modules | +| **Total** | **224** | **1750** | 14 protocol modules | --- @@ -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` | diff --git a/content/docs/ui/pages.mdx b/content/docs/ui/pages.mdx index cf4534baeee..2dc5859f33b 100644 --- a/content/docs/ui/pages.mdx +++ b/content/docs/ui/pages.mdx @@ -318,6 +318,40 @@ export const Policy = ObjectSchema.create({ }); ``` +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/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/0084-application-builder-information-architecture.md b/docs/adr/0084-application-builder-information-architecture.md index f9cfd10691a..e7979f5f464 100644 --- a/docs/adr/0084-application-builder-information-architecture.md +++ b/docs/adr/0084-application-builder-information-architecture.md @@ -218,6 +218,8 @@ Every type the spec registers, enumerated at `origin/main` `151e8123` from `pack *(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).)* @@ -449,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. 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/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 e628906788e..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 @@ -285,7 +285,8 @@ 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 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. It 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: +- 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. 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/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 index 16c92dfd8a9..51a30db2db7 100644 --- a/packages/cli/src/commands/migrate/stored-forms.ts +++ b/packages/cli/src/commands/migrate/stored-forms.ts @@ -2,7 +2,7 @@ import { Command, Flags } from '@oclif/core'; import chalk from 'chalk'; -import { STACK_TIER_PRESETS } from '@objectstack/core'; +import { STACK_TIER_PRESETS, engineCanRollBack } from '@objectstack/core'; import { printHeader, printSuccess, @@ -37,6 +37,21 @@ const EMPTY: StoredFormCensus = { 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'; @@ -120,6 +135,8 @@ function storedFormPlanSentence(plan: StoredFormAddressPlan): string { 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`; } } } @@ -266,6 +283,7 @@ export default class MigrateStoredForms extends Command { 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); @@ -273,6 +291,7 @@ export default class MigrateStoredForms extends Command { database: stack.dbLabel, hostConfig: stack.composition.hostConfigPath, canSwitch: precheck.canSwitch, + ...(runRefused !== undefined ? { runRefused } : {}), counts: precheck.counts, holds: precheck.holds, forms: census.forms, @@ -312,7 +331,9 @@ export default class MigrateStoredForms extends Command { } 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 (precheck.canSwitch) { + 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). diff --git a/packages/cli/src/utils/extract-hook-body.ts b/packages/cli/src/utils/extract-hook-body.ts index ef1bbd64b49..095db930d1a 100644 --- a/packages/cli/src/utils/extract-hook-body.ts +++ b/packages/cli/src/utils/extract-hook-body.ts @@ -506,6 +506,67 @@ const FORBIDDEN_PATTERNS: Array<{ rx: RegExp; reason: string; face?: LoweringFac }, ]; +/** + * [#38690] The step from a receiver to its member as the publish rule + * (`validate-action-body-capabilities`) reads it: `?.` or `.`, whitespace + * allowed on either side. `ctx.log.info`, `ctx?.log.info`, `ctx.log?.info` and + * `ctx . log . info` reach the same sandbox gate, so each infers its token. + */ +const MEMBER_STEP = String.raw`\s*\??\.\s*`; + +/** + * [#38690] A `ctx`-anchored member-leaf gate: `RECEIVER.MEMBER.LEAF` through + * {@link MEMBER_STEP} on both steps. No call is required (`\b` after the leaf, + * as before): `ctx.log.info?.(…)` and `ctx.log.info (…)` match, and so does a + * bare read of the leaf, which over-infers a grant the sandbox never checks. + */ +function memberLeafRx(receiver: string, member: string, leaves: string): RegExp { + return new RegExp(String.raw`${receiver}${MEMBER_STEP}${member}${MEMBER_STEP}(?:${leaves})\b`); +} + +/** + * [#38690] The source with each comment blanked to spaces (offsets and newlines + * kept), strings and template literals left as they are. The publish rule reads + * a body with its comments blanked, so `ctx./* … *\/log.info(…)` and a member + * step broken by a line comment are a gated call to it; the patterns below read + * this copy as well as the source itself, so a comment between the steps does + * not hide the call, and a spelling inside a comment still infers what it + * inferred before. The walk is the rule's own (`maskBodySource` in + * `@objectstack/lint`) minus its blanking of strings. + */ +function blankComments(source: string): string { + const out = source.split(''); + const blank = (from: number, to: number): void => { + for (let k = from; k < to; k++) if (out[k] !== '\n') out[k] = ' '; + }; + let i = 0; + while (i < source.length) { + const ch = source[i]; + if (ch === '/' && source[i + 1] === '/') { + const nl = source.indexOf('\n', i); + const end = nl === -1 ? source.length : nl; + blank(i, end); + i = end; + } else if (ch === '/' && source[i + 1] === '*') { + const close = source.indexOf('*/', i + 2); + const end = close === -1 ? source.length : close + 2; + blank(i, end); + i = end; + } else if (ch === '"' || ch === "'" || ch === '`') { + let j = i + 1; + while (j < source.length && source[j] !== ch) { + if (source[j] === '\\') j++; + else if (ch !== '`' && source[j] === '\n') break; + j++; + } + i = j + 1; + } else { + i++; + } + } + return out.join(''); +} + const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append' }> = [ // Match `ctx.api.object(...)` directly OR a local alias like // `const api = ctx.api;` then `api.object(...)`. We accept any @@ -540,12 +601,12 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | ' // A read of a `transaction` FIELD (`ctx.input.transaction`) is no call and // infers nothing. { rx: /\.\s*transaction\s*(?:\?\.\s*)?\(|\{[^{}]*\btransaction\b[^{}]*\}(?:\s*\})*\s*=(?![=>])/, cap: 'api.transaction' }, - { rx: /ctx\.crypto\.randomUUID\b/, cap: 'crypto.uuid' }, + { rx: memberLeafRx('ctx', 'crypto', 'randomUUID'), cap: 'crypto.uuid' }, // NO `ctx.crypto.hash` pattern: the `crypto.hash` token was removed in spec 17 // (#4391) because the sandbox never installed the function. Inferring a // capability from a call that always threw is what let `os build` bless a // dead body — the inference was the amplifier, not the safety net. - { rx: /ctx\.log\.(?:info|warn|error|debug)\b/, cap: 'log' }, + { rx: memberLeafRx('ctx', 'log', 'info|warn|error|debug'), cap: 'log' }, // [#11293] `ctx.title(field)` — the RELATED-record form, and only that form. // `ctx.title()` resolves this record's title (formula included) from the // state the hook is already firing on — no read over its own columns, and @@ -556,12 +617,14 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | ' // `ctx.api.object(...).findOne()` would do and gets the same token. // // `[^)\s]` after the paren is what distinguishes the two: `ctx.title()` and - // `ctx.title( )` do not match, `ctx.title('account_id')` does. Receiver-loose + // `ctx.title( )` do not match, `ctx.title('account_id')` does, and [#38690] + // so do the optional call `ctx.title?.('account_id')` and `ctx?.title(…)`, + // which the publish rule reads as the same call. Receiver-loose // like the `.object(...)` patterns above, for the same reason — a local alias // (`const t = ctx.title`) must not silently UNDER-infer, since that failure // arrives as a sandbox refusal at run time, far from its cause. Over-inferring // grants a token the body may not use, which the sandbox simply never checks. - { rx: /\.\s*title\s*\(\s*[^)\s]/, cap: 'api.read' }, + { rx: /\.\s*title\s*(?:\?\.\s*)?\(\s*[^)\s]/, cap: 'api.read' }, // The two platform doors: a call to the door is what its token grants. // // ⛔ An over-inferred `email.send` is NOT harmless on a hook. A hook body may @@ -574,8 +637,11 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | ' // to take the spelling out of the hook handler, and mail on a record change // goes through an action, a job or a flow. An action or a job body is // granted the token as before. - { rx: /ctx\.email\.send\b/, cap: 'email.send' }, - { rx: /ctx\.activity\.append\b/, cap: 'activity.append' }, + // [#38690] Every spelling the publish rule reads counts here too, so + // `ctx?.email.send(…)` and `ctx.email?.send(…)` on a hook are refused at + // build like `ctx.email.send(…)`. + { rx: memberLeafRx('ctx', 'email', 'send'), cap: 'email.send' }, + { rx: memberLeafRx('ctx', 'activity', 'append'), cap: 'activity.append' }, ]; /** The read leaves the `api.read` pattern above names, as one alternation. */ @@ -747,18 +813,22 @@ export function extractLoweredBody( ); } - // Infer capabilities from API surface usage. + // Infer capabilities from API surface usage, [#38690] over the source and + // over its comment-blanked copy (see blankComments). const inferred = new Set(); - for (const { rx, cap } of CAPABILITY_PATTERNS) { - if (rx.test(source)) inferred.add(cap); + const aliases = bodyMemberAliases(parsed, face); + for (const scanned of new Set([source, blankComments(source)])) { + for (const { rx, cap } of CAPABILITY_PATTERNS) { + if (rx.test(scanned)) inferred.add(cap); + } + // [#35143] [#38653] The `.object(...)` write and read shapes one regex cannot read; see the helper. + if (callsObjectWriteThroughHandle(scanned)) inferred.add('api.write'); + if (callsObjectReadThroughHandle(scanned)) inferred.add('api.read'); + // [#22837] The ctx-anchored patterns above spell `ctx.`; a rebound body + // reaches the same members through the handler's own names, and [#38690] + // any body through a local bound to `ctx.MEMBER` or destructured off `ctx`. + for (const cap of reboundCapabilities(scanned, rebind, aliases)) inferred.add(cap); } - // [#35143] [#38653] The `.object(...)` write and read shapes one regex cannot read; see the helper. - if (callsObjectWriteThroughHandle(source)) inferred.add('api.write'); - if (callsObjectReadThroughHandle(source)) inferred.add('api.read'); - // [#22837] The ctx-anchored patterns above spell `ctx.`; a rebound body - // reaches the same members through the handler's own names, and [#38690] - // any body through a local bound to `ctx.MEMBER` or destructured off `ctx`. - for (const cap of reboundCapabilities(source, rebind, bodyMemberAliases(parsed, face))) inferred.add(cap); return { source, @@ -1172,26 +1242,21 @@ function reboundCapabilities( for (const l of aliases.title) { if (new RegExp(String.raw`${aliasRoot(l)}\s*(?:\?\.\s*)?\(\s*[^)\s]`).test(source)) out.push('api.read'); } + // [#38690] Each step through MEMBER_STEP, like the ctx-anchored patterns. for (const r of rebind.contextRoots) { - if (new RegExp(String.raw`${root(r)}\.log\.(?:info|warn|error|debug)\b`).test(source)) out.push('log'); - if (new RegExp(String.raw`${root(r)}\.crypto\.randomUUID\b`).test(source)) out.push('crypto.uuid'); - if (new RegExp(String.raw`${root(r)}\.email\.send\b`).test(source)) out.push('email.send'); - if (new RegExp(String.raw`${root(r)}\.activity\.append\b`).test(source)) out.push('activity.append'); - } - for (const l of rebind.memberLocals.log) { - if (new RegExp(String.raw`${root(l)}\.(?:info|warn|error|debug)\b`).test(source)) out.push('log'); - } - for (const l of rebind.memberLocals.crypto) { - if (new RegExp(String.raw`${root(l)}\.randomUUID\b`).test(source)) out.push('crypto.uuid'); - } - for (const l of rebind.memberLocals.email) { - if (new RegExp(String.raw`${root(l)}\.send\b`).test(source)) out.push('email.send'); + for (const member of ['log', 'crypto', 'email', 'activity'] as const) { + const { leaves, cap } = MEMBER_LEAVES[member]; + if (memberLeafRx(root(r), member, leaves).test(source)) out.push(cap); + } } - for (const l of rebind.memberLocals.activity) { - if (new RegExp(String.raw`${root(l)}\.append\b`).test(source)) out.push('activity.append'); + for (const member of ['log', 'crypto', 'email', 'activity'] as const) { + const { leaves, cap } = MEMBER_LEAVES[member]; + for (const l of rebind.memberLocals[member]) { + if (new RegExp(String.raw`${root(l)}${MEMBER_STEP}(?:${leaves})\b`).test(source)) out.push(cap); + } } for (const l of rebind.memberLocals.title) { - if (new RegExp(String.raw`${root(l)}\s*\(\s*[^)\s]`).test(source)) out.push('api.read'); + if (new RegExp(String.raw`${root(l)}\s*(?:\?\.\s*)?\(\s*[^)\s]`).test(source)) out.push('api.read'); } return out; } diff --git a/packages/cli/test/extract-hook-body-local-alias-38690.test.ts b/packages/cli/test/extract-hook-body-local-alias-38690.test.ts index b89a69e3653..717cb30b310 100644 --- a/packages/cli/test/extract-hook-body-local-alias-38690.test.ts +++ b/packages/cli/test/extract-hook-body-local-alias-38690.test.ts @@ -14,12 +14,23 @@ * shipped without the token and the sandbox refused it at the call. * * These pin each member through each alias shape (refused before, inferred - * now), the controls that infer nothing, and an enumeration of every gate - * whose member is a `ctx.MEMBER` receiver. + * now), the controls that infer nothing, an enumeration of every gate of the + * rule's own census through every receiver, and the parity the rule now leans + * on: it judges a lowered body, so no call it reads may go ungranted. */ import { describe, expect, it } from 'vitest'; +import { + ACTION_BODY_CAPABILITY_UNDECLARED, + ACTION_BODY_WRITE_CAPABILITY_UNDECLARED, + HOOK_BODY_CAPABILITY_UNDECLARED, + SANDBOX_CAPABILITY_GATES, + runAuthoringRules, + type SandboxCapabilityGate, +} from '@objectstack/lint'; +import { HookSchema } from '@objectstack/spec/data'; import { extractLoweredBody, type ExtractedBody } from '../src/utils/extract-hook-body.js'; +import { lowerCallables } from '../src/utils/lower-callables.js'; type Token = ExtractedBody['capabilities'][number]; type Face = 'hook' | 'action'; @@ -80,27 +91,13 @@ describe('CONTROL: what is not a gated call through a ctx.MEMBER alias infers no }); /** - * Every capability gate the sandbox installs whose member is a `ctx.MEMBER` - * receiver, with one gated call spelled through that receiver. - * - * This mirrors `SANDBOX_CAPABILITY_GATES` in `@objectstack/lint`'s - * `validate-action-body-capabilities.ts`, which no entry of that package - * exports, so this file cannot import it. It is pinned to this package's own - * token list instead: `EVERY_TOKEN` must name each token of the published - * `ExtractedBody['capabilities']` union (a missing or extra key is a type - * error) and every token must have a gate row here. + * Every capability gate the sandbox installs, read straight off the publish + * rule's own census (`SANDBOX_CAPABILITY_GATES` in `@objectstack/lint`), so a + * gate the rule learns is a gate this enumeration spells through every + * receiver the next time it runs. `EVERY_TOKEN` must name each token of the + * published `ExtractedBody['capabilities']` union (a missing or extra key is a + * type error), and the census must cover every one of them. */ -const CTX_MEMBER_GATES: ReadonlyArray<{ token: Token; member: string; call: (receiver: string) => string; kinds: readonly Face[] }> = [ - { token: 'api.read', member: 'api', call: (r) => `await ${r}.object('x').find({});`, kinds: ['action', 'hook'] }, - { token: 'api.write', member: 'api', call: (r) => `await ${r}.object('x').update('1', {});`, kinds: ['action', 'hook'] }, - { token: 'api.transaction', member: 'api', call: (r) => `await ${r}.transaction(async () => {});`, kinds: ['action', 'hook'] }, - { token: 'log', member: 'log', call: (r) => `${r}.debug('x');`, kinds: ['action', 'hook'] }, - { token: 'crypto.uuid', member: 'crypto', call: (r) => `ctx.input.id = ${r}.randomUUID();`, kinds: ['action', 'hook'] }, - { token: 'email.send', member: 'email', call: (r) => `await ${r}.send({});`, kinds: ['action', 'hook'] }, - { token: 'activity.append', member: 'activity', call: (r) => `await ${r}.append({});`, kinds: ['action', 'hook'] }, - { token: 'api.read', member: 'title', call: (r) => `ctx.input.label = await ${r}('account_id');`, kinds: ['hook'] }, -]; - const EVERY_TOKEN = { 'api.read': true, 'api.write': true, @@ -111,25 +108,201 @@ const EVERY_TOKEN = { 'activity.append': true, } as const satisfies Record; +/** + * Each gated call a gate names, spelled through `receiver` in every way the + * publish rule reads a call (`memberLeafCalls`, `objectLeafCalls`, + * `calledWithArgument`): plain, `?.` before the leaf, the optional call + * `LEAF?.(…)` where the rule reads one, whitespace around the dot and before + * the paren, and a comment between the steps (the rule blanks comments). + */ +function gatedCalls(gate: SandboxCapabilityGate, receiver: string): string[] { + if (gate.shape === 'object-leaf') { + return gate.leaves.flatMap((leaf) => [ + `await ${receiver}.object('x').${leaf}({});`, + `await ${receiver}?.object('x')?.${leaf}({});`, + `await ${receiver} . object('x') . ${leaf} ({});`, + `await ${receiver}.object('x')/* c */.${leaf}({});`, + ]); + } + if (gate.shape === 'member-leaf') { + return gate.leaves.flatMap((leaf) => [ + `ctx.input.v = await ${receiver}.${leaf}({});`, + `ctx.input.v = await ${receiver}?.${leaf}({});`, + `ctx.input.v = await ${receiver}.${leaf}?.({});`, + `ctx.input.v = await ${receiver} . ${leaf} ({});`, + `ctx.input.v = await ${receiver}/* c */.${leaf}({});`, + `ctx.input.v = await ${receiver} // c\n .${leaf}({});`, + ]); + } + return [ + `ctx.input.label = await ${receiver}('account_id');`, + `ctx.input.label = await ${receiver}?.('account_id');`, + `ctx.input.label = await ${receiver} ( 'account_id');`, + `ctx.input.label = await ${receiver}/* c */('account_id');`, + ]; +} + +/** Every receiver of `ctx.MEMBER` the publish rule reads (`memberReceivers`). */ +const RECEIVERS: Array<{ shape: string; spell: (member: string) => { decl: string; receiver: string } }> = [ + { shape: 'ctx.MEMBER', spell: (m) => ({ decl: '', receiver: `ctx.${m}` }) }, + { shape: 'ctx?.MEMBER', spell: (m) => ({ decl: '', receiver: `ctx?.${m}` }) }, + { shape: 'ctx . MEMBER (whitespace)', spell: (m) => ({ decl: '', receiver: `ctx . ${m}` }) }, + { shape: 'ctx/* c */.MEMBER (a comment)', spell: (m) => ({ decl: '', receiver: `ctx/* c */.${m}` }) }, + { shape: 'a local bound once to ctx.MEMBER', spell: (m) => ({ decl: `const alias_${m} = ctx.${m};`, receiver: `alias_${m}` }) }, + { shape: 'a destructure off ctx', spell: (m) => ({ decl: `const { ${m} } = ctx;`, receiver: m }) }, + { shape: 'a renamed destructure off ctx', spell: (m) => ({ decl: `const { ${m}: local_${m} } = ctx;`, receiver: `local_${m}` }) }, +]; + describe('ENUMERATION: every ctx.MEMBER gate is inferred through each receiver shape', () => { - it('the gate table covers every token of the published capability union', () => { - expect([...new Set(CTX_MEMBER_GATES.map((g) => g.token))].sort()).toEqual(Object.keys(EVERY_TOKEN).sort()); + it('the census covers every token of the published capability union', () => { + expect([...new Set(SANDBOX_CAPABILITY_GATES.map((g) => g.token))].sort()).toEqual(Object.keys(EVERY_TOKEN).sort()); }); - const receivers: Array<{ shape: string; spell: (member: string) => { decl: string; receiver: string } }> = [ - { shape: 'ctx.MEMBER', spell: (m) => ({ decl: '', receiver: `ctx.${m}` }) }, - { shape: 'a local bound once to ctx.MEMBER', spell: (m) => ({ decl: `const alias_${m} = ctx.${m};`, receiver: `alias_${m}` }) }, - { shape: 'a destructure off ctx', spell: (m) => ({ decl: `const { ${m} } = ctx;`, receiver: m }) }, - { shape: 'a renamed destructure off ctx', spell: (m) => ({ decl: `const { ${m}: local_${m} } = ctx;`, receiver: `local_${m}` }) }, - ]; - for (const gate of CTX_MEMBER_GATES) { + for (const gate of SANDBOX_CAPABILITY_GATES) { + for (const face of gate.kinds) { + for (const { shape, spell } of RECEIVERS) { + it(`${gate.token} via ctx.${gate.member} through ${shape} (${face} face)`, () => { + const { decl, receiver } = spell(gate.member); + for (const call of gatedCalls(gate, receiver)) { + expect(infer(`${decl} ${call}`, face), call).toContain(gate.token); + } + }); + } + } + } +}); + +/** + * PARITY: the publish rule judges a lowered body like an authored one, so + * every gated call it reads must be one the build granted. Each spelling of + * each call of the census, through each receiver, is judged by the rule twice + * over `runAuthoringRules`: ungranted, it must draw the gate's finding (so the + * rule reads that spelling and the pin is not vacuous); lowered through + * `extractLoweredBody`, with the grant the build inferred, it must draw none. + * A hook body calling `email.send` is the one exception by design (a hook body + * is never granted it, and the hook's parse refuses the inferred grant at + * build; the ENUMERATION above holds that the build infers it). + */ +describe('PARITY: a lowered body draws no capability finding from the publish rule', () => { + // The body record the build writes beside the string ref: `lowerCallables` + // stores `{ language: 'js', source, capabilities }`. + const findings = (face: Face, extracted: Pick): string[] => { + const body = { language: 'js', source: extracted.source, capabilities: extracted.capabilities }; + const stack = + face === 'hook' + ? { hooks: [{ name: 'h', object: 'x', events: ['beforeUpdate'], handler: 'h_fn', body }] } + : { actions: [{ name: 'a', label: 'A', objectName: 'x', type: 'script', target: 'x_a', body }] }; + const run = { normalized: stack, parsed: stack, loweredHookRefs: new Set(['h_fn']) }; + return runAuthoringRules('build', run) + .filter((f) => [HOOK_BODY_CAPABILITY_UNDECLARED, ACTION_BODY_CAPABILITY_UNDECLARED, ACTION_BODY_WRITE_CAPABILITY_UNDECLARED].includes(f.rule)) + .map((f) => `${f.rule}: ${f.message}`); + }; + + for (const gate of SANDBOX_CAPABILITY_GATES) { for (const face of gate.kinds) { - for (const { shape, spell } of receivers) { + if (face === 'hook' && gate.token === 'email.send') continue; + for (const { shape, spell } of RECEIVERS) { it(`${gate.token} via ctx.${gate.member} through ${shape} (${face} face)`, () => { const { decl, receiver } = spell(gate.member); - expect(infer(`${decl} ${gate.call(receiver)}`, face)).toContain(gate.token); + for (const call of gatedCalls(gate, receiver)) { + const body = extractLoweredBody(handler(`async (ctx) => { ${decl} ${call} }`), `${face} 'h'`, face); + const ungranted = findings(face, { ...body, capabilities: [] }); + expect(ungranted.some((f) => f.includes(`'${gate.token}'`)), `the rule reads ${call}`).toBe(true); + expect(findings(face, body), call).toEqual([]); + } }); } } } }); + +/** + * The rebound siblings (#22837): a hook handler that names its context + * parameter something else, or destructures it, reaches the same gates through + * its own names, and the build rebinds them (`var hookCtx = ctx;`, + * `var { log } = ctx;`). Every spelling of every call of the census through + * each rebound shape infers its token. Where the publish rule reads the + * rebound receiver (a destructure off `ctx`, which the prologue spells), the + * ungranted body draws the gate's finding and the lowered one draws none; the + * rule does not read a renamed root (`hookCtx.log`), so there the lowered body + * draws none and the over-inference is the build's own margin. The hook face + * alone: the action face runs `(input, ctx)` and is not rebound. + */ +const REBOUND: Array<{ shape: string; spell: (member: string) => { param: string; receiver: string }; ruleReads: boolean }> = [ + { shape: 'a renamed context parameter', spell: (m) => ({ param: 'hookCtx', receiver: `hookCtx.${m}` }), ruleReads: false }, + { shape: 'a renamed context parameter, ?.', spell: (m) => ({ param: 'hookCtx', receiver: `hookCtx?.${m}` }), ruleReads: false }, + { shape: 'a renamed context parameter, whitespace', spell: (m) => ({ param: 'hookCtx', receiver: `hookCtx . ${m}` }), ruleReads: false }, + { shape: 'a destructured parameter', spell: (m) => ({ param: `{ ${m} }`, receiver: m }), ruleReads: true }, + { shape: 'a renamed destructured parameter', spell: (m) => ({ param: `{ ${m}: p_${m} }`, receiver: `p_${m}` }), ruleReads: true }, +]; + +describe('REBOUND: every gate is inferred through the handler’s own names, and the rule draws nothing on the lowered body', () => { + const lower = (param: string, body: string, face: Face): ExtractedBody => + extractLoweredBody(handler(`async (${param}) => { ${body} }`), `${face} 'h'`, face); + const judged = (face: Face, extracted: Pick): string[] => { + const body = { language: 'js', source: extracted.source, capabilities: extracted.capabilities }; + const stack = + face === 'hook' + ? { hooks: [{ name: 'h', object: 'x', events: ['beforeUpdate'], handler: 'h_fn', body }] } + : { actions: [{ name: 'a', label: 'A', objectName: 'x', type: 'script', target: 'x_a', body }] }; + return runAuthoringRules('build', { normalized: stack, parsed: stack, loweredHookRefs: new Set(['h_fn']) }) + .filter((f) => [HOOK_BODY_CAPABILITY_UNDECLARED, ACTION_BODY_CAPABILITY_UNDECLARED, ACTION_BODY_WRITE_CAPABILITY_UNDECLARED].includes(f.rule)) + .map((f) => `${f.rule}: ${f.message}`); + }; + + for (const gate of SANDBOX_CAPABILITY_GATES) { + for (const face of gate.kinds.filter((k): k is 'hook' => k === 'hook')) { + for (const { shape, spell, ruleReads } of REBOUND) { + it(`${gate.token} via ctx.${gate.member} through ${shape} (${face} face)`, () => { + const { param, receiver } = spell(gate.member); + // The body's own `ctx.input` is the context only where the parameter is named for it. + for (const call of gatedCalls(gate, receiver).map((c) => (param === 'hookCtx' ? c.replace(/^ctx\.input\./, 'hookCtx.input.') : c.replace(/^ctx\.input\.\w+ = /, 'void ')))) { + const body = lower(param, call, face); + expect(body.capabilities, call).toContain(gate.token); + if (face === 'hook' && gate.token === 'email.send') continue; + if (ruleReads) { + expect(judged(face, { ...body, capabilities: [] }).some((f) => f.includes(`'${gate.token}'`)), `the rule reads ${call}`).toBe(true); + } + expect(judged(face, body), call).toEqual([]); + } + }); + } + } + } +}); + +/** + * The one over-inference that is not harmless stays a refusal in every + * spelling: a hook handler that calls `ctx.email.send` lowers to a body granted + * `email.send`, and the hook parse every build runs after lowering refuses + * that grant (#32004), however the call is spelled. + */ +describe('a hook handler that sends mail is refused at build in every spelling the rule reads', () => { + const spellings = [ + 'await ctx.email.send({});', + 'await ctx?.email.send({});', + 'await ctx.email?.send({});', + 'await ctx.email.send?.({});', + 'await ctx . email . send ({});', + 'const { email } = ctx; await email?.send({});', + 'const e = ctx.email; await e?.send?.({});', + ]; + for (const call of spellings) { + it(call, () => { + const out = lowerCallables({ + hooks: [{ name: 'h', object: 'x', events: ['afterInsert'], handler: handler(`async (ctx) => { ${call} }`) }], + }); + const lowered = (out.lowered.hooks as Array<{ body: { capabilities: string[] } }>)[0]; + expect(lowered.body.capabilities).toContain('email.send'); + const r = HookSchema.safeParse(lowered); + expect(r.success).toBe(false); + expect(r.success ? '' : r.error.issues[0].message).toContain('A hook body cannot be granted `email.send`'); + }); + } + it('rebound: a renamed context parameter', () => { + const out = lowerCallables({ + hooks: [{ name: 'h', object: 'x', events: ['afterInsert'], handler: handler('async (hookCtx) => { await hookCtx?.email?.send({}); }') }], + }); + expect(HookSchema.safeParse((out.lowered.hooks as unknown[])[0]).success).toBe(false); + }); +}); diff --git a/packages/cli/test/lower-callables.test.ts b/packages/cli/test/lower-callables.test.ts index c7ef05dc706..1c9325e3e0a 100644 --- a/packages/cli/test/lower-callables.test.ts +++ b/packages/cli/test/lower-callables.test.ts @@ -499,14 +499,12 @@ describe('[#33214] lowerCallables — a handler hook\'s refusal catalogue', () = }); }); -// [#38653] `@objectstack/lint` tells an action body the build lowered from an -// inline `target` function apart from an authored one by its shape alone — a -// non-empty string `target` beside a body record (`isLoweredTargetBody` in -// `validate-action-body-capabilities.ts`) — and judges only the first for -// `api.write`. Its own pins build that shape by hand; this one holds it to what -// `lowerActionCallable` really emits, top-level and object-owned, so a lowering -// that stopped leaving the string ref would surface here, not as lint judging -// inferred grants as authored ones. +// [#38653] An action the build lowered from an inline `target` function keeps +// that shape — a non-empty string `target` beside a body record carrying the +// inferred grant. `@objectstack/lint`'s capability pins build the shape by +// hand (since #38690 the rule judges such a body like an authored one); this +// one holds it to what `lowerActionCallable` really emits, top-level and +// object-owned. describe('[#38653] lowerCallables — a lowered action keeps a string `target` beside its minted body', () => { const target = async (ctx: any) => { await ctx.api.object('doc').updateById(ctx.input.id, { stamped: true }); diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 6ff98f56cbd..7e71759c93a 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -3420,7 +3420,7 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // the sandbox gates (`hook-body-capability-undeclared`); no object write // carries a hook. runtimeTypes: ['action', 'object', 'hook'], - run: (stack, ctx) => validateActionBodyCapabilities(stack, ctx), + run: (stack) => validateActionBodyCapabilities(stack), }, // The same compile check over an L2 hook body and an L2 job body, in the // wrapper the runtime runs both in (`(async (ctx) => { SOURCE })`, built from diff --git a/packages/lint/src/data-model-rules.field-tabs-37802.test.ts b/packages/lint/src/data-model-rules.field-tabs-37802.test.ts new file mode 100644 index 00000000000..017aca6718c --- /dev/null +++ b/packages/lint/src/data-model-rules.field-tabs-37802.test.ts @@ -0,0 +1,74 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37802 — `object/field-tabs-empty-overview`: an object whose + * `fieldTabs` move every field out of the record page's overview is warned + * (the overview stays its first tab, with no field). CONTROL: the same object + * with one group, or one ungrouped field, left in the overview is silent, and + * so is an object without `fieldTabs`. Membership is the page's: a group's own + * `fields` list first, then a field's `group`; hidden fields and ungrouped + * system fields are not drawn, so they do not count. + */ + +import { describe, expect, it } from 'vitest'; +import { lintDataModel } from './data-model-rules.js'; + +const RULE = 'object/field-tabs-empty-overview'; + +const policy = (fieldTabs: unknown, extraFields: Record = {}) => ({ + name: 'policy', + nameField: 'title', + fieldGroups: [ + { key: 'basic', label: 'Basic' }, + { key: 'content', label: 'Content' }, + ], + fields: { + title: { type: 'text', group: 'basic' }, + body: { type: 'textarea', group: 'content' }, + ...extraFields, + }, + ...(fieldTabs === undefined ? {} : { fieldTabs }), +}); + +const findings = (obj: unknown) => lintDataModel([obj]).filter((i) => i.rule === RULE); + +describe(`${RULE} (objectstack#37802)`, () => { + it('warns when every field is moved into a field tab, at the object\'s fieldTabs', () => { + const [finding, ...rest] = findings(policy([{ key: 'all', groups: ['basic', 'content'] }])); + expect(rest).toEqual([]); + expect(finding.severity).toBe('warning'); + expect(finding.path).toBe('objects[0].fieldTabs'); + expect(finding.message).toContain('"policy"'); + }); + + it('two tabs that together take every group warn too', () => { + expect(findings(policy([{ key: 'a', groups: ['basic'] }, { key: 'b', groups: ['content'] }]))).toHaveLength(1); + }); + + it('membership spelled by the groups\' own `fields` lists is read as the page reads it', () => { + const listed = { + name: 'policy', + nameField: 'title', + fieldGroups: [ + { key: 'basic', label: 'Basic', fields: ['title'] }, + { key: 'content', label: 'Content', fields: ['body'] }, + ], + fields: { title: { type: 'text' }, body: { type: 'textarea' } }, + }; + expect(findings({ ...listed, fieldTabs: [{ key: 'all', groups: ['basic', 'content'] }] })).toHaveLength(1); + // CONTROL: the same lists with one group left in the overview. + expect(findings({ ...listed, fieldTabs: [{ key: 'content', groups: ['content'] }] })).toEqual([]); + }); + + it('a field the overview would not draw does not keep it from being empty: hidden, or an ungrouped system field', () => { + const all = [{ key: 'all', groups: ['basic', 'content'] }]; + expect(findings(policy(all, { secret: { type: 'text', hidden: true } }))).toHaveLength(1); + expect(findings(policy(all, { created_at: { type: 'datetime' } }))).toHaveLength(1); + }); + + it('CONTROL: a group left in the overview, an ungrouped field, or no fieldTabs is silent', () => { + expect(findings(policy([{ key: 'content', groups: ['content'] }]))).toEqual([]); + expect(findings(policy([{ key: 'all', groups: ['basic', 'content'] }], { status: { type: 'text' } }))).toEqual([]); + expect(findings(policy(undefined))).toEqual([]); + }); +}); diff --git a/packages/lint/src/data-model-rules.ts b/packages/lint/src/data-model-rules.ts index 4a1b325cc1b..8895de88b28 100644 --- a/packages/lint/src/data-model-rules.ts +++ b/packages/lint/src/data-model-rules.ts @@ -23,7 +23,9 @@ import { REFERENCE_VALUE_TYPES, isAggregateCompatibleWithFieldType, isApiOperationAllowed, + FIELD_GROUP_SYSTEM_FIELDS, fieldGroupsPlaceRelationship, + readFieldGroupMembership, isGroupPlaceableRelationship, masterDetailRequiredOmitted, referenceCarrierOf, @@ -1455,6 +1457,40 @@ export function lintDataModel(objects: any[]): LintIssue[] { }); } + // objectstack#37802 — `fieldTabs` (ADR-0085's Note of 2026-11-27) moves + // field groups out of the record page's overview into tabs of their own. + // The overview always exists (the body tables, the approval band and the + // meta line stay there), so a declaration that moves out every field + // leaves it a tab with no field: legal, and almost never meant. + const fieldTabGroups = new Set(); + for (const tab of Array.isArray(obj.fieldTabs) ? obj.fieldTabs : []) { + for (const group of Array.isArray(tab?.groups) ? tab.groups : []) { + if (typeof group === 'string') fieldTabGroups.add(group); + } + } + // Membership is read the way the page reads it — a group's own `fields` + // list first, then a field's `group` (`readFieldGroupMembership`) — and + // only a field the overview would draw counts: not hidden, and, when + // ungrouped, not one of the system fields the layout never lists. + const membership = fieldTabGroups.size > 0 ? readFieldGroupMembership(obj) : undefined; + const drawn = fields.filter(({ name, def }) => + def?.hidden !== true && (membership?.groupOf.has(name) || !FIELD_GROUP_SYSTEM_FIELDS.has(name))); + if ( + membership !== undefined + && drawn.length > 0 + && drawn.every(({ name }) => fieldTabGroups.has(membership.groupOf.get(name) ?? '')) + ) { + issues.push({ + severity: 'warning', + rule: 'object/field-tabs-empty-overview', + message: + `Object "${obj.name}" moves every field into its \`fieldTabs\` — the record page's overview, still its ` + + 'first tab, draws no field', + path: `${objPath}.fieldTabs`, + fix: 'Leave at least one field group out of `fieldTabs` (the overview draws the groups no tab names and the ungrouped fields).', + }); + } + for (const { name: fieldName, def } of fields) { if (!def || typeof def !== 'object') continue; const fieldPath = `${objPath}.fields.${fieldName}`; diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index d4a788a5e3b..38204a5eb04 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -1180,6 +1180,11 @@ export { ACTION_BODY_CAPABILITY_UNDECLARED, HOOK_BODY_CAPABILITY_UNDECLARED, } from './validate-action-body-capabilities.js'; +// [#38690] The sandbox's gate census the capability rule judges by, exported so +// the CLI's hook-body extractor pins its inference against this table itself +// rather than a copy: the rule judges a lowered body, so every gate it reads +// must be one the build infers. +export { SANDBOX_CAPABILITY_GATES, type SandboxCapabilityGate } from './validate-action-body-capabilities.js'; export { SEED_RECORD_UNKNOWN_FIELD } from './validate-seed-record-keys.js'; // [#35143] The Views, dashboards and app shell family's app-shell ids, all // advisory, exported for `os explain` as the two above; the rules run through diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index f2fd9f70776..45e3a5912d1 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -1552,9 +1552,8 @@ const ACTION_BODY_CAPABILITY_UNDECLARED_EXPLANATION: RuleExplanation = { 'reaches the call. A write without `api.write` has its own id, `action-body-write-capability-undeclared`.', BODY_GATES_READING, 'To fix it, add the token the message names to the action\'s `body.capabilities` (Studio\'s action ' + - 'inspector draws the list), or remove the call. Only a body the author wrote is judged: an action body ' + - 'the build lowered from an inline `target` function is not, since its grant is the build\'s inference ' + - '(its writes are still judged under `action-body-write-capability-undeclared`).', + 'inspector draws the list), or remove the call. An action body the build lowered from an inline ' + + '`target` function is judged the same way: its grant is the one the build inferred from its calls.', ], }; @@ -1570,7 +1569,8 @@ const HOOK_BODY_CAPABILITY_UNDECLARED_EXPLANATION: RuleExplanation = { 'To fix it, add the token the message names to the hook\'s `body.capabilities`, or remove the call. A hook ' + 'body is never granted `email.send`, because a message cannot be taken back if the write that runs the ' + 'hook rolls back: remove the `ctx.email.send` call and send the mail from an action, a job or a flow. ' + - 'Only a body the author wrote is judged: a hook body the build lowered from an inline `handler` is not.', + 'A hook body the build lowered from an inline `handler` is judged the same way: its grant is the one the ' + + 'build inferred from its calls.', ], }; diff --git a/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts b/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts index 666930ba65d..0b699b52426 100644 --- a/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts +++ b/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts @@ -17,8 +17,6 @@ import { SANDBOX_CAPABILITY_GATES, SANDBOX_LOG_LEVELS, bodyGatedCalls, - isLoweredHandlerBody, - isLoweredTargetBody, validateActionBodyCapabilities, } from './validate-action-body-capabilities.js'; import { runAuthoringRules } from './authoring-rules.js'; @@ -148,41 +146,8 @@ describe('arm (a): a hook body is judged like an action body (#37815)', () => { } }); - describe('authored hook bodies only: a body lowered from a handler is not judged (#37815 route C)', () => { - // A read through a bound handle: a shape the build's inference does not read (#38653). - const READ = "const repo = ctx.api.object('cb_ticket');\nreturn repo.findOne({});"; - const lowered = { ...hook(READ, []), handler: 'cb_stamp_fn' }; - - it('an authored body with the call is refused', () => { - const fs = validateActionBodyCapabilities({ hooks: [hook(READ, [])] }, { loweredHookRefs: new Set(['cb_stamp_fn']) }); - expect(fs.map((f) => [f.rule, f.path])).toEqual([[HOOK_BODY_CAPABILITY_UNDECLARED, 'hooks[0].body.capabilities']]); - expect(fs[0].message).toContain("'api.read'"); - }); - - it('the same body lowered by os build / os validate / os verify is not judged', () => { - expect(isLoweredHandlerBody(lowered, { loweredHookRefs: new Set(['cb_stamp_fn']) })).toBe(true); - expect(validateActionBodyCapabilities({ hooks: [lowered] }, { loweredHookRefs: new Set(['cb_stamp_fn']) })).toEqual([]); - const stack = { objects: [TICKET], hooks: [lowered] }; - for (const command of ['validate', 'build', 'lint'] as const) { - const run = { normalized: stack, parsed: stack, loweredHookRefs: new Set(['cb_stamp_fn']) }; - expect(ofRule(runAuthoringRules(command, run), HOOK_BODY_CAPABILITY_UNDECLARED), command).toEqual([]); - } - }); - - it('a string handler the build did not lower leaves the authored body judged', () => { - const fs = validateActionBodyCapabilities({ hooks: [lowered] }, { loweredHookRefs: new Set(['other_fn']) }); - expect(fs.map((f) => f.path)).toEqual(['hooks[0].body.capabilities']); - }); - - it('the save door, which hands no lowered refs, does not judge a build artifact’s lowered body', () => { - const artifact = runRuntimeAuthoringRules({ type: 'hook', item: lowered, context: { objects: [TICKET] } }); - expect(ofRule(artifact.errors, HOOK_BODY_CAPABILITY_UNDECLARED)).toEqual([]); - const authored = runRuntimeAuthoringRules({ type: 'hook', item: hook(READ, []), context: { objects: [TICKET] } }); - expect(ofRule(authored.errors, HOOK_BODY_CAPABILITY_UNDECLARED).map((e) => e.path)).toEqual([ - 'hooks[0].body.capabilities', - ]); - }); - }); + // [#38690] A body the build lowered is judged like an authored one: the + // pins live in `validate-action-body-capabilities.lowered-38690.test.ts`. it('a hook body’s ctx.email.send is refused with the remedy that works: no grant can fix it', () => { const fs = validateActionBodyCapabilities({ hooks: [hook("await ctx.email.send({ to: ['a@b.c'] });", [])] }); @@ -251,51 +216,6 @@ describe('arm (b): the tokens besides api.write (#37815)', () => { expect(ofRule(granted.errors, ACTION_BODY_CAPABILITY_UNDECLARED)).toEqual([]); }); - describe('authored action bodies only past the writes: a body lowered from a target is judged for api.write alone (#37815 M1)', () => { - // A transaction the build's inference does not read (#38653): the extractor grants the write only. - const TX = "await ctx.api.transaction(async () => { await ctx.api.object('cb_ticket').insert({ name: 'x' }); });"; - const authored = action(TX, ['api.write']); - const lowered = { ...authored, target: 'cb_ticket_cb_close' }; - - it('an authored body with the call is refused', () => { - expect(isLoweredTargetBody(authored)).toBe(false); - const fs = validateActionBodyCapabilities({ actions: [authored] }); - expect(fs.map((f) => [f.rule, f.path])).toEqual([[ACTION_BODY_CAPABILITY_UNDECLARED, 'actions[0].body.capabilities']]); - expect(fs[0].message).toContain("'api.transaction'"); - }); - - it('the same body lowered from a target is not judged by os validate / build / lint, top level or inline', () => { - expect(isLoweredTargetBody(lowered)).toBe(true); - expect(validateActionBodyCapabilities({ actions: [lowered] })).toEqual([]); - const top = { objects: [TICKET], actions: [lowered] }; - const inline = { objects: [{ ...TICKET, actions: [lowered] }] }; - for (const stack of [top, inline]) { - for (const command of ['validate', 'build', 'lint'] as const) { - const fs = runAuthoringRules(command, { normalized: stack, parsed: stack, loweredHookRefs: new Set() }); - expect(ofRule(fs, ACTION_BODY_CAPABILITY_UNDECLARED), command).toEqual([]); - } - } - const fs = validateActionBodyCapabilities({ objects: [{ ...TICKET, actions: [authored] }] }); - expect(fs.map((f) => f.path)).toEqual(['objects[0].actions[0].body.capabilities']); - }); - - it('the action and object doors do not judge it either, and do judge the authored body', () => { - const door = runRuntimeAuthoringRules({ type: 'action', item: lowered, context: { objects: [TICKET] } }); - expect(ofRule(door.errors, ACTION_BODY_CAPABILITY_UNDECLARED)).toEqual([]); - const objectDoor = runRuntimeAuthoringRules({ type: 'object', item: { ...TICKET, actions: [lowered] }, context: { objects: [] } }); - expect(ofRule(objectDoor.errors, ACTION_BODY_CAPABILITY_UNDECLARED)).toEqual([]); - const refused = runRuntimeAuthoringRules({ type: 'action', item: authored, context: { objects: [TICKET] } }); - expect(ofRule(refused.errors, ACTION_BODY_CAPABILITY_UNDECLARED).map((e) => e.path)).toEqual(['actions[0].body.capabilities']); - const objectRefused = runRuntimeAuthoringRules({ type: 'object', item: { ...TICKET, actions: [authored] }, context: { objects: [] } }); - expect(ofRule(objectRefused.errors, ACTION_BODY_CAPABILITY_UNDECLARED)).toHaveLength(1); - }); - - it('a lowered body still answers for its writes, under the write id and words', () => { - const fs = validateActionBodyCapabilities({ actions: [{ ...lowered, body: { ...lowered.body, capabilities: [] } }] }); - expect(fs.map((f) => f.rule)).toEqual([ACTION_BODY_WRITE_CAPABILITY_UNDECLARED]); - }); - }); - it('os explain has a page for the action id', () => { expect(explainRule(ACTION_BODY_CAPABILITY_UNDECLARED)?.paragraphs.join('\n')).toContain('api.transaction'); }); diff --git a/packages/lint/src/validate-action-body-capabilities.lowered-38690.test.ts b/packages/lint/src/validate-action-body-capabilities.lowered-38690.test.ts new file mode 100644 index 00000000000..faf15586561 --- /dev/null +++ b/packages/lint/src/validate-action-body-capabilities.lowered-38690.test.ts @@ -0,0 +1,164 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A body the build lowered is judged like one the author wrote. + * + * `validate-action-body-capabilities` used to skip a hook body lowered from an + * inline `handler` (a string `handler` the build registered, or any string + * `handler` at a door that hands no lowered refs) and to judge an action body + * lowered from an inline `target` function for `api.write` alone. The grant on + * such a body is the build's inference, and that inference did not yet read + * every shape the rule reads, so a finding there would have named a grant the + * build forgot. The extractor now infers every gate through every receiver the + * rule reads (`ctx.MEMBER`, a local bound once to it, a destructure off `ctx`, + * a handle bound once to `.object(…)`), pinned in `@objectstack/cli` against + * this rule's own `SANDBOX_CAPABILITY_GATES`. So a lowered body that calls a + * gate without its token is one the sandbox refuses at the call, and the rule + * says so where it used to stay quiet. + * + * Each removed skip has its red-before cases (a lowered body calling a gate + * ungranted, spelled directly and through an alias), and the controls: the + * same lowered body granted is not refused. + */ + +import { describe, expect, it } from 'vitest'; + +import { + ACTION_BODY_CAPABILITY_UNDECLARED, + ACTION_BODY_WRITE_CAPABILITY_UNDECLARED, + HOOK_BODY_CAPABILITY_UNDECLARED, + validateActionBodyCapabilities, +} from './validate-action-body-capabilities.js'; +import { runAuthoringRules } from './authoring-rules.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; + +const TICKET = { + name: 'cb_ticket', + label: 'Ticket', + sharingModel: 'private', + fields: { name: { type: 'text', label: 'Name' }, done: { type: 'boolean', label: 'Done' } }, +}; + +/** A hook as `os build` leaves it: the string ref it registered, and the body it minted beside it. */ +const loweredHook = (source: string, capabilities: string[]) => ({ + name: 'cb_stamp', + object: 'cb_ticket', + events: ['beforeUpdate'], + handler: 'cb_stamp_fn', + body: { language: 'js', source, capabilities }, +}); + +/** An action as `os build` leaves it: the string `target` it registered, and the body it minted beside it. */ +const loweredAction = (source: string, capabilities: string[]) => ({ + name: 'cb_close', + label: 'Close', + objectName: 'cb_ticket', + type: 'script', + locations: ['record_page'], + target: 'cb_ticket_cb_close', + body: { language: 'js', source, capabilities }, +}); + +const REFS = new Set(['cb_stamp_fn']); +const ofRule = (fs: readonly T[], rule: string): T[] => fs.filter((f) => f.rule === rule); + +/** One gated call per token, spelled directly and through an alias. */ +const CALLS: ReadonlyArray<{ token: string; shape: 'direct' | 'alias'; source: string; faces: ReadonlyArray<'hook' | 'action'> }> = [ + { token: 'log', shape: 'direct', source: "ctx.log.info('x');", faces: ['hook', 'action'] }, + { token: 'log', shape: 'alias', source: "const l = ctx.log; l.info('x');", faces: ['hook', 'action'] }, + { token: 'crypto.uuid', shape: 'direct', source: 'var id = ctx.crypto.randomUUID();', faces: ['hook', 'action'] }, + { token: 'crypto.uuid', shape: 'alias', source: 'const { crypto } = ctx; var id = crypto.randomUUID();', faces: ['hook', 'action'] }, + { token: 'activity.append', shape: 'direct', source: "await ctx.activity.append({ text: 'x' });", faces: ['hook', 'action'] }, + { token: 'activity.append', shape: 'alias', source: "const { activity: a } = ctx; await a.append({ text: 'x' });", faces: ['hook', 'action'] }, + { token: 'api.transaction', shape: 'direct', source: 'await ctx.api.transaction(async () => {});', faces: ['hook', 'action'] }, + { token: 'api.transaction', shape: 'alias', source: 'const api = ctx.api; await api.transaction(async () => {});', faces: ['hook', 'action'] }, + { token: 'api.read', shape: 'direct', source: "var n = await ctx.api.object('cb_ticket').count({});", faces: ['hook', 'action'] }, + { token: 'api.read', shape: 'alias', source: "const repo = ctx.api.object('cb_ticket');\nreturn repo.findOne({});", faces: ['hook', 'action'] }, + { token: 'api.read', shape: 'direct', source: "ctx.input.label = await ctx.title('account_id');", faces: ['hook'] }, + { token: 'api.read', shape: 'alias', source: "const t = ctx.title; ctx.input.label = await t('account_id');", faces: ['hook'] }, +]; + +describe('a hook body lowered from a handler is judged (the isLoweredHandlerBody skip is gone)', () => { + for (const { token, shape, source, faces } of CALLS) { + if (!faces.includes('hook')) continue; + it(`${token}, ${shape}: refused ungranted under os validate / build / lint, and passes granted`, () => { + const refused = validateActionBodyCapabilities({ hooks: [loweredHook(source, [])] }); + expect(refused.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [HOOK_BODY_CAPABILITY_UNDECLARED, 'error', 'hooks[0].body.capabilities'], + ]); + expect(refused[0].message).toContain(`'${token}'`); + const stack = { objects: [TICKET], hooks: [loweredHook(source, [])] }; + for (const command of ['validate', 'build', 'lint'] as const) { + const run = { normalized: stack, parsed: stack, loweredHookRefs: REFS }; + expect(ofRule(runAuthoringRules(command, run), HOOK_BODY_CAPABILITY_UNDECLARED).map((f) => f.path), command).toEqual([ + 'hooks[0].body.capabilities', + ]); + } + // CONTROL: the same lowered body, granted. + expect(validateActionBodyCapabilities({ hooks: [loweredHook(source, [token])] })).toEqual([]); + }); + } + + it('the hook save door judges a build artifact’s lowered body, and admits it granted', () => { + const source = "const l = ctx.log; l.info('x');"; + const refused = runRuntimeAuthoringRules({ type: 'hook', item: loweredHook(source, []), context: { objects: [TICKET] } }); + expect(ofRule(refused.errors, HOOK_BODY_CAPABILITY_UNDECLARED).map((e) => e.path)).toEqual(['hooks[0].body.capabilities']); + const granted = runRuntimeAuthoringRules({ type: 'hook', item: loweredHook(source, ['log']), context: { objects: [TICKET] } }); + expect(ofRule(granted.errors, HOOK_BODY_CAPABILITY_UNDECLARED)).toEqual([]); + }); + + it('a lowered hook body’s ctx.email.send is refused like an authored one’s: no grant fixes it', () => { + const fs = validateActionBodyCapabilities({ hooks: [loweredHook("await ctx.email.send({ to: ['a@b.c'] });", [])] }); + expect(fs.map((f) => f.rule)).toEqual([HOOK_BODY_CAPABILITY_UNDECLARED]); + expect(fs[0].message).toContain("never granted 'email.send'"); + }); +}); + +describe('an action body lowered from a target is judged for every token (the non-write isLoweredTargetBody skip is gone)', () => { + for (const { token, shape, source, faces } of CALLS) { + if (!faces.includes('action')) continue; + it(`${token}, ${shape}: refused ungranted, top level and inline, and passes granted`, () => { + const top = validateActionBodyCapabilities({ actions: [loweredAction(source, [])] }); + expect(top.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [ACTION_BODY_CAPABILITY_UNDECLARED, 'error', 'actions[0].body.capabilities'], + ]); + expect(top[0].message).toContain(`'${token}'`); + const inline = validateActionBodyCapabilities({ objects: [{ ...TICKET, actions: [loweredAction(source, [])] }] }); + expect(inline.map((f) => f.path)).toEqual(['objects[0].actions[0].body.capabilities']); + // CONTROL: the same lowered body, granted. + expect(validateActionBodyCapabilities({ actions: [loweredAction(source, [token])] })).toEqual([]); + }); + } + + it('os validate / build / lint and the action and object doors refuse it the same way', () => { + const source = 'await ctx.api.transaction(async () => { await ctx.api.object(\'cb_ticket\').insert({ name: \'x\' }); });'; + const lowered = loweredAction(source, ['api.write']); + const top = { objects: [TICKET], actions: [lowered] }; + const inline = { objects: [{ ...TICKET, actions: [lowered] }] }; + for (const [stack, path] of [ + [top, 'actions[0].body.capabilities'], + [inline, 'objects[0].actions[0].body.capabilities'], + ] as const) { + for (const command of ['validate', 'build', 'lint'] as const) { + const fs = runAuthoringRules(command, { normalized: stack, parsed: stack, loweredHookRefs: new Set() }); + expect(ofRule(fs, ACTION_BODY_CAPABILITY_UNDECLARED).map((f) => f.path), command).toEqual([path]); + } + } + const door = runRuntimeAuthoringRules({ type: 'action', item: lowered, context: { objects: [TICKET] } }); + expect(ofRule(door.errors, ACTION_BODY_CAPABILITY_UNDECLARED).map((e) => e.path)).toEqual(['actions[0].body.capabilities']); + const objectDoor = runRuntimeAuthoringRules({ type: 'object', item: { ...TICKET, actions: [lowered] }, context: { objects: [] } }); + expect(ofRule(objectDoor.errors, ACTION_BODY_CAPABILITY_UNDECLARED)).toHaveLength(1); + // CONTROL: granted both tokens, every door admits it. + const granted = loweredAction(source, ['api.write', 'api.transaction']); + expect(validateActionBodyCapabilities({ actions: [granted] })).toEqual([]); + const grantedDoor = runRuntimeAuthoringRules({ type: 'action', item: granted, context: { objects: [TICKET] } }); + expect(ofRule(grantedDoor.errors, ACTION_BODY_CAPABILITY_UNDECLARED)).toEqual([]); + }); + + it('a lowered body’s write keeps its own id and words, beside the other tokens', () => { + const source = "await ctx.api.object('cb_ticket').insert({ name: 'x' }); ctx.log.warn('w');"; + const fs = validateActionBodyCapabilities({ actions: [loweredAction(source, [])] }); + expect(fs.map((f) => f.rule)).toEqual([ACTION_BODY_WRITE_CAPABILITY_UNDECLARED, ACTION_BODY_CAPABILITY_UNDECLARED]); + expect(fs[1].message).toContain("'log'"); + }); +}); diff --git a/packages/lint/src/validate-action-body-capabilities.ts b/packages/lint/src/validate-action-body-capabilities.ts index 8a2414f71d5..a95537eac99 100644 --- a/packages/lint/src/validate-action-body-capabilities.ts +++ b/packages/lint/src/validate-action-body-capabilities.ts @@ -25,9 +25,9 @@ * (`packages/cli/src/utils/extract-hook-body.ts`) reads each shape listed * below — a direct chain, `?.` before the leaf, an argument holding a call, a * handle bound to `.object(…)` — so a lowered body's writes are not refused by - * the next step of the same build; its pins hold that shape by shape. For the - * other tokens it does not yet read every shape this rule reads, so a lowered - * body is judged for `api.write` only (see the last section). + * the next step of the same build; its pins hold that shape by shape. It reads + * every other gate through the same receivers too, so a lowered body is judged + * like an authored one (see the last section). * * ## How the source is read * @@ -86,16 +86,25 @@ * back), so a hook's `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. * - * Authored bodies only, past the writes. A hook body `os build` / `os verify` - * lowered from an inline handler is not judged, and an action body lowered - * from an inline `target` function is judged for `api.write` only - * ({@link ACTION_BODY_WRITE_CAPABILITY_UNDECLARED}, unchanged). Such a grant - * is the build's inference, which does not yet read every gated shape (no - * `api.transaction`; `api.read` only on a direct chain; the other members only - * as a literal `ctx.MEMBER.LEAF`), so a finding there would name a grant the - * author never wrote and cannot write. {@link isLoweredHandlerBody} and - * {@link isLoweredTargetBody} tell the two apart; the lowered reading waits on - * the extractor (#38653). + * Lowered bodies are judged like authored ones (#38690). The rule does not + * tell them apart: a body beside a string `handler` or `target` is judged + * whether `os build` / `os verify` lowered it from an inline function or the + * author wrote it by hand. A lowered body carries the grant the build inferred + * from its calls, and the cli extractor reads each gated call the way this + * rule reads it: every gate of {@link SANDBOX_CAPABILITY_GATES}, through each + * receiver (`ctx.MEMBER`, a local bound once to it, a destructure off `ctx`, a + * handle bound once to `.object(…)`, a hook handler's destructured context, + * which the build rebinds to a destructure off `ctx`), with `?.` or whitespace + * on either side of a step, the optional call `LEAF?.(…)`, and a comment + * between steps; it reads more besides (a renamed context root, a spelling + * inside a string). Its parity pin in + * `@objectstack/cli` judges each of those spellings through this rule twice, + * ungranted (a finding) and lowered (none). So a fresh build of an inline + * handler draws no finding here, and a lowered body this rule refuses is one + * whose grant was lost after the build, which the sandbox refuses at the call. + * The build's reading covers this rule's by that enumeration, not by proof: a + * spelling outside it may still diverge, and the finding then names the token + * the build missed. */ import { collectActionBodies } from './validate-action-body-writes.js'; @@ -376,68 +385,16 @@ function refusalClause(token: string, kind: BodyKind): string { return `so the sandbox refuses the call (403 INSUFFICIENT_PRIVILEGES) every time the ${kind} reaches it${lost}.`; } -/** - * Whether a hook's body is one the build lowered from its handler rather than - * one the author wrote (#37815, authored bodies only). Lowering replaces an - * inline handler with the string ref it registers and adds the body beside it, - * so the body was lowered when the hook carries a string `handler`: under - * `os build` / `os validate` / `os verify` exactly when `ctx.loweredHookRefs` - * holds that ref, and at a door that hands no `loweredHookRefs` (the runtime - * publish doors) whenever a string `handler` sits beside the body, the shape - * a build artifact carries. A missed finding, never a false one. - */ -export function isLoweredHandlerBody( - hook: AnyRec, - ctx: { loweredHookRefs?: ReadonlySet } | undefined, -): boolean { - const ref = hook.handler; - if (typeof ref !== 'string' || ref === '') return false; - return ctx?.loweredHookRefs ? ctx.loweredHookRefs.has(ref) : true; -} - -/** - * Whether an action's body is one the build lowered from its `target` - * function rather than one the author wrote (#37815). Lowering replaces an - * inline `target` function with the string ref it registers and adds the body - * beside it, and the CLI hands no lowered-action ref set, so on every door the - * body was lowered when a string `target` sits beside it: the shape a build - * artifact carries. A JS body runs only on a `script` action, where `target` - * is kept for legacy `functions` references alone, so an authored body beside - * a string `target` is not judged either: a missed finding, never a false one. - */ -export function isLoweredTargetBody(action: AnyRec): boolean { - return typeof action.target === 'string' && action.target !== '' && isRecord(action.body); -} - -/** The `…body.source` paths `collectActionBodies` reports for an action {@link isLoweredTargetBody} reads as lowered. */ -function loweredActionBodyPaths(stack: AnyRec): Set { - const paths = new Set(); - const walk = (actions: unknown, prefix: string): void => { - recordsOf(actions).forEach((action, index) => { - if (isLoweredTargetBody(action)) paths.add(`${prefix}[${index}].body.source`); - }); - }; - walk(stack.actions, 'actions'); - recordsOf(stack.objects).forEach((obj, objIndex) => walk(obj.actions, `objects[${objIndex}].actions`)); - return paths; -} - /** * Every L2 action body, and every L2 hook body, that calls a member the * sandbox gates without granting itself the member's token (the header lists - * the gates and the ids). A hook body lowered from an inline `handler` is - * skipped ({@link isLoweredHandlerBody}); an action body lowered from a - * `target` function is judged for `api.write` only ({@link isLoweredTargetBody}). + * the gates and the ids), whether the author wrote the body or the build + * lowered it from a handler or a `target` function (#38690). */ -export function validateActionBodyCapabilities( - stack: AnyRec, - ctx?: { loweredHookRefs?: ReadonlySet }, -): ActionBodyCapabilityFinding[] { +export function validateActionBodyCapabilities(stack: AnyRec): ActionBodyCapabilityFinding[] { const findings: ActionBodyCapabilityFinding[] = []; if (!stack || typeof stack !== 'object') return findings; - const loweredActions = loweredActionBodyPaths(stack); for (const site of collectActionBodies(stack)) { - const lowered = loweredActions.has(site.path); for (const { token, calls } of bodyGatedCalls(site.source, 'action')) { if (site.capabilities.includes(token)) continue; const path = site.path.replace(/\.source$/, '.capabilities'); @@ -456,7 +413,6 @@ export function validateActionBodyCapabilities( }); continue; } - if (lowered) continue; findings.push({ severity: 'error', rule: ACTION_BODY_CAPABILITY_UNDECLARED, @@ -473,7 +429,6 @@ export function validateActionBodyCapabilities( const source = body.source; if (typeof source !== 'string' || source.trim() === '') return; const granted: readonly unknown[] = Array.isArray(body.capabilities) ? body.capabilities : []; - if (isLoweredHandlerBody(hook, ctx)) return; const name = typeof hook.name === 'string' && hook.name ? hook.name : `#${index}`; for (const { token, calls } of bodyGatedCalls(source, 'hook')) { if (granted.includes(token)) continue; diff --git a/packages/metadata-core/src/object-schema-fls-references.ts b/packages/metadata-core/src/object-schema-fls-references.ts index 37300446bd5..4efb8515321 100644 --- a/packages/metadata-core/src/object-schema-fls-references.ts +++ b/packages/metadata-core/src/object-schema-fls-references.ts @@ -824,6 +824,8 @@ export const OBJECT_REFERENCE_POSITIONS: Readonly> = { requiredPermissions: keep, fileAccessDelegate: keep, schemaReadDelegate: keep, editMode: keep, enable: keep, // The record page layout switch (ADR-0085's Note of 2026-11-27): a boolean, no field name. pinOverview: keep, + // The record page's field tabs (the same Note): tab keys and field GROUP keys, no field name. + fieldTabs: keep, sharingModel: keep, externalSharingModel: keep, protection: keep, // [#25760] The per-object sharing opt-ins (`sharing.controlledByParent.ownerMayEdit`, // ADR-0055 §3 amendment): a block of booleans that names no field. diff --git a/packages/metadata-protocol/src/index.ts b/packages/metadata-protocol/src/index.ts index cd2b235af93..3d9fee13a40 100644 --- a/packages/metadata-protocol/src/index.ts +++ b/packages/metadata-protocol/src/index.ts @@ -364,6 +364,9 @@ export type { StoredFormPrecheck, StoredFormRowRef, } from './protocol-stored-form-migration.js'; +// [ADR-0159 D7, card ⑤a] The ceremony's write half (`--apply`): the major's upgrade command calls it, ⛔ nothing else. +export { applyStoredFormsOf } from './protocol-stored-form-apply.js'; +export type { StoredFormApplyResult, StoredFormRemoved, StoredFormRowKey, StoredFormWritten } from './protocol-stored-form-apply.js'; // [#28412, ADR-0146 D9 item 1] The `package_id` column of the stored row a // registry body was hydrated from, recorded by the protocol's hydration and diff --git a/packages/metadata-protocol/src/protocol-stored-form-apply.ts b/packages/metadata-protocol/src/protocol-stored-form-apply.ts new file mode 100644 index 00000000000..edc305d6542 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-stored-form-apply.ts @@ -0,0 +1,456 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * # The stored-form ceremony, its write half (ADR-0159 D7, card ⑤a) + * + * `--apply` of the ceremony whose read-only half is + * `protocol-stored-form-migration.ts`: the move, the fold and the removal of + * every stored old-shape form row, as the census plans them. ⛔ Reached only + * from the major's upgrade command (the sequencing ruling, record + * `7142585849` on #36868: convert first, then switch): the standalone + * `os migrate stored-forms` stays read-only, so no administrator moves rows + * on a deployment that then stays on its pre-upgrade release. + * + * ## All or nothing with the switch + * + * The plan is computed whole first ({@link listStoredForms}). Where the + * precheck still counts a row (`canSwitch` false: a pair that cannot be + * ensured, a body the projection cannot read, a contested slot, a row served + * apart), {@link applyStoredForms} writes nothing: no row is moved, no + * internal record form is removed, no pair is ensured, every stored row stays + * byte-equal, and both public doors answer as before. A deployment that does + * not switch holds every stored row as it was (ruled question 4: no withdrawn + * public form may re-open), so a switch-off is never left in a `form` row the + * pre-upgrade release does not read. + * + * ## The writes + * + * 1. The pairs the moves land in are ensured through the ensure door, the + * only creation path (ADR-0146 D3), before anything else is written. + * 2. Each destination row is written: a `form` row with the served body as + * written (D7-a, D7-b), the withdrawal a folded row carries switched off + * on it (D7-d), and, at a base, the declared override of the base + * (`overrides: { package, basedOn }`); the pair's own `form` item + * (`pair_form`, maintainer ruling `7250977204`) declares none. A stored + * `form` row already at its destination that takes a carried withdrawal + * is written again with its switch off. + * 3. Every written row is read back at its address, and must be the row the + * write put there; one copy per address of a row read at several. + * 4. Only then are the old-shape rows taken away: a row whose every form + * goes (moved, folded or removed) and that holds no list is deleted; a + * container that also holds lists, or a form the ceremony leaves as + * stored, is re-saved without the members that go, the rest byte-equal + * (`oldShapeFormRowRemovals`, the `form` write door's own removal). + * + * Writes go through the repository beneath the doors: a move is not a save. + * ⛔ The `form` save door's address-clash refusal is not asked (ADR-0159 D7: + * a retired form and its successor on one address are both moved as written, + * and what the doors serve does not change). Steps 2 to 4 are one + * transaction, so a failure leaves every row as it was. The pairs of step 1 + * are ensured before it and stay after a rollback: an empty pair changes no + * door's answer, and the next run reuses it. On an engine that cannot roll + * back, a run that would write or take a row is refused before anything is + * written (the pairs included), naming the driver: a run cut short there + * could leave a deployment that does not switch without a row it reads. A + * second run finds nothing to move (idempotent): every moved row is then a + * stored `form` row at its destination (`keep`). + * + * `sys_metadata_history` rows are never rewritten: each write appends its own. + * The registry follows the store after the commit, as the doors heal it. + */ + +import { engineCanRollBack } from '@objectstack/core'; +import { isAggregatedViewContainer, PROJECTED_FORM_SOURCE_KEY } from '@objectstack/spec/ui'; +import { retireOverlayCacheOnRollback } from './meta-overlay-cache.js'; +import { oldShapeFormRowRemovals } from './protocol-form-writes.js'; +import { storedFormPlaces, storedViewRowHoldings, type StoredFormPlace } from './protocol-form-reads.js'; +import { protocolHost, type ProtocolHost } from './protocol-host.js'; +import { + listStoredForms, + type StoredFormAddressPlan, + type StoredFormCensus, + type StoredFormCensusHost, + type StoredFormDestination, + type StoredFormRowRef, +} from './protocol-stored-form-migration.js'; +import type { ObjectStackProtocolImplementation } from './protocol.js'; + +/** A stored row the ceremony wrote, re-saved or deleted, by its key. */ +export interface StoredFormRowKey { + readonly type: string; + readonly name: string; + readonly packageId?: string; +} + +/** One `form` row the ceremony wrote (a move, or a carried withdrawal on a row already in place). */ +export interface StoredFormWritten { + readonly form: string; + readonly row: StoredFormRowKey; + readonly destination: StoredFormDestination; + /** The stored row whose body it holds. */ + readonly from: StoredFormRowRef; + /** The slug switched off on it, carried from a folded row (D7-d). */ + readonly switchedOff?: string; +} + +/** One internal record form the ceremony removed (ruling record `7142585849`, item 3). */ +export interface StoredFormRemoved { + readonly form: string; + readonly row: StoredFormRowRef; + readonly object?: string; + /** Whether the object declares field groups: New and Edit of it follow them from now on. */ + readonly objectHasFieldGroups: boolean; + /** The removed form's body, as it was stored. */ + readonly body: Record; +} + +/** What {@link applyStoredForms} did. */ +export interface StoredFormApplyResult { + /** `false` when the precheck held the upgrade: nothing was written. */ + readonly applied: boolean; + /** The census the run computed before any write. */ + readonly census: StoredFormCensus; + /** The pairs the ensure door created for the moves. */ + readonly pairsEnsured: readonly string[]; + readonly written: readonly StoredFormWritten[]; + readonly removed: readonly StoredFormRemoved[]; + /** The old-shape rows taken away: deleted, or re-saved without the members that went. */ + readonly rowsChanged: readonly (StoredFormRowKey & { readonly change: 'deleted' | 'resaved' })[]; +} + +/** The host members the write half reads, beside the census's. */ +export type StoredFormApplyHost = StoredFormCensusHost + & Pick + & { + /** The ensure door ({@link ObjectStackProtocolImplementation.ensureCustomizationPackage}). */ + readonly ensurePair: (base: string) => Promise; + }; + +const isRecord = (value: unknown): value is Record => + !!value && typeof value === 'object' && !Array.isArray(value); + +const rowKeyOf = (type: string, name: string, packageId: string | undefined): string => `${type}\u0000${name}\u0000${packageId ?? ''}`; + +/** The stored row a reference names, among the places the census read. */ +function placeOf(places: readonly StoredFormPlace[], ref: StoredFormRowRef): StoredFormPlace { + const place = places.find((p) => p.entry.type === ref.type && p.entry.name === ref.name + && p.packageId === ref.packageId && p.grain === ref.grain && p.holds.has(ref.form)); + if (place === undefined) { + throw new Error(`The stored ${ref.type} row '${ref.name}' the plan for '${ref.form}' names was not found again; nothing was written.`); + } + return place; +} + +/** + * The form body a row holds at `form`, as the read serves it, cleaned of the + * read's envelope: the projection's source marker, and the provenance a + * container's expansion wears from the package that ships the container + * (`_packageId`, `_packageVersion`, `_provenance`). The destination row's + * package is its own provenance; a base's stamp written into a pair's or a + * package-less row would read as that base's shipped code. + */ +function formBodyOf(place: StoredFormPlace, form: string): Record { + const holding = place.holds.get(form); + if (holding?.kind !== 'form') throw new Error(`The stored ${place.entry.type} row '${place.entry.name}' holds no form at '${form}'.`); + const { + _packageId: _pkg, _packageVersion: _version, _provenance: _prov, + [PROJECTED_FORM_SOURCE_KEY]: _source, ...body + } = holding.item as Record; + return { ...body, name: form }; +} + +/** The row a destination is, and the body written there. */ +function destinationRow( + destination: StoredFormDestination, + form: string, + body: Record, +): { key: StoredFormRowKey; packageId: string | null; body: Record } { + const { overrides: _declared, ...undeclared } = body; + switch (destination.kind) { + case 'pair_override': + return { + key: { type: 'form', name: form, packageId: destination.pair }, + packageId: destination.pair, + body: { ...undeclared, overrides: { package: destination.base, basedOn: destination.basedOn } }, + }; + case 'pair_form': + // [maintainer ruling 7250977204] The pair's own item: no `overrides`. + return { key: { type: 'form', name: form, packageId: destination.pair }, packageId: destination.pair, body: undeclared }; + case 'package_form': + return { key: { type: 'form', name: form, packageId: destination.packageId }, packageId: destination.packageId, body: undeclared }; + case 'environment_form': + return { key: { type: 'form', name: form }, packageId: null, body: undeclared }; + } +} + +/** The body with its `sharing` switched off, its link kept (the carried withdrawal, D7-d). */ +function switchedOff(body: Record): Record { + return { ...body, sharing: { ...(isRecord(body.sharing) ? body.sharing : {}), enabled: false } }; +} + +/** + * [ADR-0159 D7; rulings 7142585849 (items 2 and 3), 7250977204, 7249158572, + * 7265816895] The ceremony's write half. See the module header. + * + * @param request.actor recorded on every write (`null` for the upgrade command, which has no human actor). + */ +export async function applyStoredForms(host: StoredFormApplyHost, request: { actor: string | null }): Promise { + const census = await listStoredForms(host); + const nothing = { census, pairsEnsured: [], written: [], removed: [], rowsChanged: [] }; + // All or nothing: a row that holds the upgrade holds every write. + if (!census.precheck.canSwitch) return { applied: false, ...nothing }; + + const places = await storedFormPlaces(host); + const writes = new Map }>(); + /** The forms that go from each stored row, by the row's key. */ + const goes = new Map }>(); + const removed: StoredFormRemoved[] = []; + const take = (ref: StoredFormRowRef): void => { + const place = placeOf(places, ref); + const key = rowKeyOf(place.entry.type, place.entry.name, place.packageId); + const entry = goes.get(key) ?? { place, forms: new Set() }; + entry.forms.add(ref.form); + goes.set(key, entry); + }; + const write = (plan: StoredFormAddressPlan & { outcome: 'keep' | 'move' }, body: Record): void => { + const carried = plan.carries !== undefined ? switchedOff(body) : body; + const row = destinationRow(plan.destination, plan.form, carried); + const key = rowKeyOf(row.key.type, row.key.name, row.key.packageId); + if (writes.has(key)) { + // The planner holds a slot more than one plan claims; reaching here is a planner defect, never a guess. + throw new Error(`Two plans write the ${row.key.type} row '${row.key.name}' in '${row.key.packageId ?? 'the environment'}'; nothing was written.`); + } + writes.set(key, { + write: { + form: plan.form, row: row.key, destination: plan.destination, from: plan.served, + ...(plan.carries !== undefined ? { switchedOff: plan.carries.slug } : {}), + }, + packageId: row.packageId, + body: row.body, + }); + }; + + for (const plan of census.forms) { + if (plan.outcome === 'move') { + write(plan, formBodyOf(placeOf(places, plan.served), plan.form)); + take(plan.served); + for (const row of plan.behind) take(row); + } else if (plan.outcome === 'keep') { + // Already a stored `form` row at its destination: written again only to carry a withdrawal. + if (plan.carries !== undefined) { + const place = placeOf(places, plan.served); + const { _packageId: _pkg, ...stored } = place.entry.data as Record; + write(plan, stored); + } + for (const row of plan.behind) take(row); + } else if (plan.outcome === 'remove') { + const body = formBodyOf(placeOf(places, plan.served), plan.form); + removed.push({ + form: plan.form, row: plan.served, + ...(plan.object !== undefined ? { object: plan.object } : {}), + objectHasFieldGroups: plan.objectHasFieldGroups, body, + }); + take(plan.served); + for (const row of plan.behind) take(row); + } + // `left_in_place` writes nothing; `hold` cannot be here (`canSwitch`). + } + + // A row a plan writes to is never one another plan takes away. + for (const key of writes.keys()) { + if (goes.has(key)) throw new Error(`A plan writes the row another plan takes away (${key.split('\u0000').join(' ')}); nothing was written.`); + } + + // All or nothing needs a database that can roll back: on one that cannot, + // a run cut short after an old row went would leave a deployment that + // does not switch without it. Refused before anything is written. + const engine = host.engine as unknown as { transaction?: (fn: () => Promise) => Promise; getDefaultDriverName?: () => string | undefined }; + if ((writes.size > 0 || goes.size > 0) && !engineCanRollBack(engine)) { + const driver = engine.getDefaultDriverName?.(); + throw new Error( + `The stored-form upgrade refuses --apply here: the default driver${driver !== undefined ? ` '${driver}'` : ''} cannot roll back a transaction, and the upgrade moves stored forms all or nothing. Nothing was written. ` + + 'Run the upgrade against a database whose driver supports transactions, or stay on the current release; `os migrate stored-forms` still reports what the upgrade would move.', + ); + } + + // Step 1: the pairs, through the ensure door, before any row is written. + const registry = (host.engine as { registry?: { getPackage?: (id: string) => unknown } } | undefined)?.registry; + const pairsEnsured: string[] = []; + for (const { write: w } of writes.values()) { + const d = w.destination; + if (d.kind !== 'pair_override' && d.kind !== 'pair_form') continue; + if (pairsEnsured.includes(d.pair) || registry?.getPackage?.(d.pair)) continue; + await host.ensurePair(d.base); + pairsEnsured.push(d.pair); + } + + type Changed = Awaited>; + let changed: Changed = []; + const run = async (): Promise => { + // Steps 2 and 3: the destination rows, each read back; step 4: the old rows, once every copy reads back. + await writeStoredFormCopies(host, [...writes.values()], request.actor); + changed = await takeStoredFormRows(host, [...goes.values()], request.actor); + }; + // Without a rollback nothing is written or taken here (refused above). + if (engineCanRollBack(engine)) await retireOverlayCacheOnRollback(engine, () => engine.transaction!(run)); + else await run(); + const rowsChanged = changed; + + // The registry follows the store, after the commit. + await healStoredFormRows(host, [ + ...[...writes.values()].map(({ write: w, packageId, body }) => ({ type: 'form', name: w.row.name, packageId, item: body })), + ...rowsChanged.flatMap((row) => (row.change === 'resaved' ? [{ type: row.type, name: row.name, packageId: row.packageId ?? null, item: row.body! }] : [])), + ], rowsChanged.filter((row) => row.change === 'deleted').map((row) => ({ type: row.type, name: row.name, packageId: row.packageId ?? null }))); + + return { + applied: true, + census, + pairsEnsured, + written: [...writes.values()].map(({ write: w }) => w), + removed, + rowsChanged: rowsChanged.map(({ body: _body, ...row }) => row), + }; +} + +const WRITE_SOURCE = 'stored-forms --apply'; +const WRITE_MESSAGE = 'Stored old-shape form moved, folded or removed by the upgrade (ADR-0159 D7)'; + +/** The store's judgement of a write: an edit of a shipped item, or a runtime write. */ +function intentOf(host: StoredFormApplyHost, type: string, name: string): 'override-artifact' | 'runtime-only' { + return host.isArtifactBacked(type, name) ? 'override-artifact' : 'runtime-only'; +} + +/** + * Steps 2 and 3: write each destination `form` row, and read it back at its + * own address. Called INSIDE {@link applyStoredForms}'s transaction; the + * caller heals the registry after the commit ({@link healStoredFormRows}). + * Throws on a row that does not read back as written. + */ +async function writeStoredFormCopies( + host: StoredFormApplyHost, + writes: ReadonlyArray<{ write: StoredFormWritten; packageId: string | null; body: Record }>, + actor: string | null, +): Promise { + const repo = host.getOverlayRepo(); + for (const { write: w, packageId, body } of writes) { + const ref = { type: 'form', name: w.row.name, org: 'env' } as Parameters[0]; + const { head } = await repo.headAt(ref, { state: 'active', packageId }); + const put = await repo.put(ref, body, { + parentVersion: head?.hash ?? null, actor, source: WRITE_SOURCE, message: WRITE_MESSAGE, + // [ADR-0146 D2] A declared override writes the pair's own row and edits no + // managed item: the store judges it a runtime write, as the save door does. + intent: body.overrides !== undefined ? 'runtime-only' : intentOf(host, 'form', w.row.name), state: 'active', packageId, + } as Parameters[2]); + const back = await repo.headAt(ref, { state: 'active', packageId }); + if (back.head === null || back.head.hash !== put.version || (back.packageId ?? null) !== packageId) { + throw new Error(`The form row '${w.row.name}' written into '${packageId ?? 'the environment'}' does not read back as written; nothing was moved.`); + } + } +} + +/** + * Step 4: delete or re-save each old-shape row the plans take ({@link remaining}), + * locked against the checksum it is stored at. Called INSIDE + * {@link applyStoredForms}'s transaction, after every copy reads back; returns + * the rows it changed, which the caller heals after the commit + * ({@link healStoredFormRows}). + */ +async function takeStoredFormRows( + host: StoredFormApplyHost, + goes: ReadonlyArray<{ place: StoredFormPlace; forms: ReadonlySet }>, + actor: string | null, +): Promise }>> { + const repo = host.getOverlayRepo(); + const changed: Array }> = []; + const stored = await rawActiveRows(host); + for (const { place, forms } of goes) { + const raw = stored.get(rowKeyOf(place.entry.type, place.entry.name, place.packageId)); + const ref = { type: place.entry.type, name: place.entry.name, org: 'env' } as Parameters[0]; + const options = { + parentVersion: typeof raw?.checksum === 'string' ? raw.checksum : null, + actor, source: WRITE_SOURCE, message: WRITE_MESSAGE, + intent: intentOf(host, place.entry.type, place.entry.name), state: 'active' as const, + packageId: place.packageId ?? null, + }; + const key = { type: place.entry.type, name: place.entry.name, ...(place.packageId !== undefined ? { packageId: place.packageId } : {}) }; + const next = remaining(host, place, forms); + if (next === undefined) { + await repo.delete(ref, options as Parameters[1]); + changed.push({ ...key, change: 'deleted' }); + } else { + await repo.put(ref, next, options as Parameters[2]); + changed.push({ ...key, change: 'resaved', body: next }); + } + } + return changed; +} + +/** + * The registry follows the store, after {@link applyStoredForms} commits: each + * live row it wrote is written through (`type` is the literal `'form'` for a + * copy, and the stored row's own type for a re-saved container), and each row + * it deleted is healed from what the store then serves. + */ +async function healStoredFormRows( + host: StoredFormApplyHost, + live: ReadonlyArray<{ type: string; name: string; packageId: string | null; item: Record }>, + deleted: ReadonlyArray<{ type: string; name: string; packageId: string | null }>, +): Promise { + for (const row of live) { + await host.applyRegistryWriteThrough({ type: row.type, name: row.name, item: row.item, packageId: row.packageId, organizationId: null } as never); + } + for (const row of deleted) await host.restoreArtifactRegistryView(row.type, row.name, null, row.packageId); +} + +/** The active stored rows of both types, raw, by key: the checksum each write locks against. */ +async function rawActiveRows(host: StoredFormApplyHost): Promise>> { + const out = new Map>(); + for (const type of ['form', 'view']) { + for (const row of await host.readActiveOverlayRows({ type })) { + const entry = host.storedOverlayEntries({ type }, [row])[0]; + if (entry === undefined) continue; + out.set(rowKeyOf(entry.type, entry.name, entry.packageId), row as Record); + } + } + return out; +} + +/** + * The body a stored row keeps once `forms` go from it, or `undefined` when + * nothing of it stays (the row is deleted). A `form` row and an item-shaped + * `view` row hold one form: it goes, and the row with it. A container is + * re-saved without each member that goes, through the `form` write door's own + * removal ({@link oldShapeFormRowRemovals}): its lists, and any form the + * ceremony leaves as stored, byte-equal. + */ +function remaining(host: StoredFormApplyHost, place: StoredFormPlace, forms: ReadonlySet): Record | undefined { + if (place.type === 'form' || place.grain === 'item') return undefined; + let body = place.entry.data as Record; + const holdingsOf = (entry: { data: unknown; packageId: string | undefined }) => storedViewRowHoldings(host, entry); + for (const form of forms) { + const [removal] = oldShapeFormRowRemovals([{ name: place.entry.name, data: body, packageId: place.packageId }], form, place.packageId ?? null, holdingsOf); + if (removal === undefined) { + throw new Error(`The member of the stored view '${place.entry.name}' that carries '${form}' could not be named; nothing was written.`); + } + if (removal.kind === 'delete') return undefined; + body = removal.body; + } + // A container every member of which went is no container any more: the + // re-saved remnant (`{ name, object }`) would read as an unreadable row + // that holds the next run's switch. It goes, as a row that holds nothing. + if (!isAggregatedViewContainer(body)) return undefined; + return storedViewRowHoldings(host, { data: body, packageId: place.packageId }).size === 0 ? undefined : body; +} + +/** + * [ADR-0159 D7, card ⑤a] {@link applyStoredForms} over a live protocol + * instance. ⛔ Called by the major's upgrade command only: the standalone + * `os migrate stored-forms` is read-only. + */ +export function applyStoredFormsOf(protocol: ObjectStackProtocolImplementation, request: { actor: string | null }): Promise { + // The host's own members, read at call time, and the ensure door beside them. + const host = Object.create(protocolHost(protocol), { + ensurePair: { value: async (base: string) => { await protocol.ensureCustomizationPackage({ basePackageId: base }); } }, + }) as StoredFormApplyHost; + return applyStoredForms(host, request); +} diff --git a/packages/metadata-protocol/src/protocol-stored-form-migration.test.ts b/packages/metadata-protocol/src/protocol-stored-form-migration.test.ts index 5225067035e..ca55b0ed9b0 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-migration.test.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-migration.test.ts @@ -16,8 +16,10 @@ import { storedViewRowHoldings, type StoredFormPlace } from './protocol-form-rea import { INTERNAL_AHEAD_OF_LINKED_ROW, planStoredForms, + storedFormPairFix, type PairFixReading, type ShippedForm, + type StoredFormAddress, type StoredFormAddressPlan, type StoredFormCensus, type StoredFormPlanInput, @@ -99,6 +101,8 @@ function input(places: StoredFormPlace[], over: Partial & { isWritable: (pkg) => pkg === WORKSPACE || pkg === PAIR, actionTargets: new Set(), pairFix: () => PAIR_OK, + sealedFormShippers: () => [], + servedToday: () => true, objectHasFieldGroups: () => true, unreadable: [], ...over, @@ -296,6 +300,113 @@ describe('[ADR-0159 D7] planStoredForms — one outcome per form and address', ( expect(census.precheck.canSwitch).toBe(false); }); + it('a form no door serves today is left in place by the upgrade: a row bound to a read-only package that ships no form of the name, where the read serves no form of the name at that package, moves nothing and holds nothing (ablate: the census read of the form served today)', () => { + const census = planStoredForms(input([viewFormRow(OTHER, { enabled: true })], { + pairFix: (base) => ({ ok: true, pair: `${base}.custom`, basedOn: '2.0.0' }), + servedToday: (name, packageId) => !(name === NAME && packageId === OTHER), + })); + expect(census.forms.map((f) => [f.address, f.outcome, 'reason' in f ? f.reason : undefined])).toEqual([ + [{ kind: 'base', packageId: OTHER }, 'left_in_place', 'served_by_no_door'], + ]); + expect(census.precheck).toMatchObject({ canSwitch: true, holds: [] }); + }); + + for (const [hold, opts] of [ + ['the pair door refuses the pair (D7-c)', { pairFix: () => ({ ok: false, cause: 'administrator', refusal: 'refused' }) }], + ['the store seals the destination', { pairFix: (base: string) => ({ ok: true, pair: `${base}.custom`, basedOn: '2.0.0' }), sealedFormShippers: (name: string) => (name === NAME ? ['com.acme.shipper'] : []) }], + ] as const) { + it(`a form no door serves today is left in place before a hold its move would take: ${hold}, and nothing holds the upgrade (ablate: read the form served today before those holds)`, () => { + const census = planStoredForms(input([viewFormRow(OTHER, { enabled: true })], { + ...(opts as Partial), + servedToday: (name, packageId) => !(name === NAME && packageId === OTHER), + })); + expect(census.forms.map((f) => [f.address, f.outcome, 'reason' in f ? f.reason : undefined])).toEqual([ + [{ kind: 'base', packageId: OTHER }, 'left_in_place', 'served_by_no_door'], + ]); + expect(census.precheck).toMatchObject({ canSwitch: true, holds: [] }); + }); + } + + describe('a form no door serves today is left in place by the upgrade, whatever package its row is bound to (ablate: the census read of the form served today, at the address each plan is made at)', () => { + const unservedAt = (at: string | undefined) => (name: string, packageId: string | undefined) => !(name === NAME && packageId === at); + const shapes: readonly [string, StoredFormPlace, Parameters[1] & {}, StoredFormAddress][] = [ + ['a row bound to a writable package', viewFormRow(WORKSPACE, { enabled: true }), { ships: { [NAME]: [{ packageId: WORKSPACE, writable: true, form: undefined }] } }, { kind: 'package', packageId: WORKSPACE }], + ['the pair\'s own item', viewFormRow(PAIR, { enabled: true }), { ships: {} }, { kind: 'package', packageId: PAIR }], + ['the pair\'s declared override of a base that ships none', viewFormRow(PAIR, { enabled: true, overrides: BASE }), { ships: {} }, { kind: 'package', packageId: PAIR }], + ['a package-less row', viewFormRow(undefined, { enabled: true }), { ships: {} }, { kind: 'environment' }], + ]; + for (const [shape, row, opts, address] of shapes) { + const at = address.kind === 'environment' ? undefined : address.packageId; + it(`${shape}: no row moves, nothing holds`, () => { + const census = planStoredForms(input([row], { ...opts, servedToday: unservedAt(at) })); + expect(census.forms.map((f) => [f.address, f.outcome, 'reason' in f ? f.reason : undefined])).toEqual([[address, 'left_in_place', 'served_by_no_door']]); + expect(census.precheck).toMatchObject({ canSwitch: true, holds: [] }); + }); + it(`CONTROL: ${shape}, where the read serves it today, moves`, () => { + const census = planStoredForms(input([row], opts)); + expect(census.forms.map((f) => [f.address, f.outcome])).toEqual([[address, 'move']]); + }); + } + }); + + describe('the store\'s seal (ADR-0131 D6): the census reads a destination the way the run\'s write meets it', () => { + const SHIPPER = 'com.example.shipper'; + const sealedBy = (name: string): readonly string[] => (name === NAME ? [SHIPPER] : []); + + it('the pair\'s own item, where another package ships the name as a `form` item: the row holds the upgrade, naming that package, and nothing moves', () => { + const census = planStoredForms(input([viewFormRow(OTHER, { enabled: true })], { + pairFix: (base) => ({ ok: true, pair: `${base}.custom`, basedOn: '2.0.0' }), + sealedFormShippers: sealedBy, + })); + expect(census.forms.map((f) => [f.address, f.outcome])).toEqual([[{ kind: 'base', packageId: OTHER }, 'hold']]); + expect(census.forms[0]).toMatchObject({ cause: 'app_author' }); + expect(census.precheck).toMatchObject({ canSwitch: false, holds: [{ row: { packageId: OTHER, name: NAME }, cause: 'app_author' }] }); + expect(census.precheck.holds[0]!.refusal).toContain(`'${SHIPPER}'`); + expect(census.precheck.holds[0]!.refusal).toContain('sealed'); + expect(census.precheck.holds[0]!.action).toContain(`'${SHIPPER}'`); + }); + + it('a kept `form` row the run writes, because it carries a withdrawal folded into it, reads the seal too: it holds the upgrade, naming that package, and nothing is written', () => { + const ships = { [NAME]: [{ packageId: WORKSPACE, writable: true, form: undefined }] }; + const rows = [formRow(WORKSPACE, { enabled: true }), viewFormRow(undefined, { enabled: false })]; + const census = planStoredForms(input(rows, { ships, sealedFormShippers: sealedBy })); + expect(census.forms.map((f) => [f.address, f.outcome, 'cause' in f ? f.cause : undefined])).toEqual([[{ kind: 'package', packageId: WORKSPACE }, 'hold', 'app_author']]); + expect(census.precheck).toMatchObject({ canSwitch: false, holds: [{ row: { packageId: WORKSPACE, name: NAME }, cause: 'app_author' }] }); + expect(census.precheck.holds[0]!.refusal).toContain(`'${SHIPPER}'`); + expect(census.precheck.holds[0]!.refusal).toContain('carry a withdrawal'); + }); + + it('CONTROL: the same kept row where no package ships a `form` item of the name is kept and carries the withdrawal', () => { + const ships = { [NAME]: [{ packageId: WORKSPACE, writable: true, form: undefined }] }; + const rows = [formRow(WORKSPACE, { enabled: true }), viewFormRow(undefined, { enabled: false })]; + const census = planStoredForms(input(rows, { ships, sealedFormShippers: () => [] })); + expect(census.forms.map((f) => [f.address, f.outcome])).toEqual([[{ kind: 'package', packageId: WORKSPACE }, 'keep']]); + expect(census.forms[0]).toMatchObject({ carries: { slug: SLUG } }); + }); + + it('CONTROL: a kept row that carries nothing is not written, so the seal does not hold it', () => { + const ships = { [NAME]: [{ packageId: WORKSPACE, writable: true, form: undefined }] }; + const census = planStoredForms(input([formRow(WORKSPACE, { enabled: true })], { ships, sealedFormShippers: sealedBy })); + expect(census.forms.map((f) => [f.outcome, 'carries' in f ? f.carries : undefined])).toEqual([['keep', undefined]]); + }); + + it('CONTROL: the same row where no package ships a `form` item of the name moves into the pair', () => { + const census = planStoredForms(input([viewFormRow(OTHER, { enabled: true })], { + pairFix: (base) => ({ ok: true, pair: `${base}.custom`, basedOn: '2.0.0' }), + sealedFormShippers: () => [], + })); + expect(census.forms.map((f) => [f.outcome, destinationOf(f)])).toEqual([['move', { kind: 'pair_form', base: OTHER, pair: `${OTHER}.custom` }]]); + }); + + it('CONTROL: a declared override is written as the pair\'s own row and meets no seal, so the base shipping the name as a `form` item moves it', () => { + const census = planStoredForms(input([viewFormRow(PAIR, { enabled: false, overrides: BASE })], { + sealedFormShippers: (name) => (name === NAME ? [BASE] : []), + })); + expect(census.forms.map((f) => [f.outcome, (destinationOf(f) as { kind?: string } | undefined)?.kind])).toEqual([['move', 'pair_override']]); + expect(census.precheck.canSwitch).toBe(true); + }); + }); + it('move (ruling 7250977204): a pair\'s declared override of a base that ships no form of the name becomes the pair\'s own form — the door is not asked', () => { const census = planStoredForms(input([viewFormRow(PAIR, { enabled: true, overrides: BASE })], { ships: {}, @@ -618,6 +729,18 @@ describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another addr } }); + it('a hold stands where no door serves the row today: the pair\'s own item no door serves still claims the slot a row is planned into, and both hold the upgrade (ruling record 7265816895)', () => { + const census = planStoredForms(input([viewFormRow(SUITE_PAIR, { enabled: true }), viewFormRow(SUITE, { enabled: false })], { + ...over(), + servedToday: (name: string, packageId: string | undefined) => !(name === NAME && packageId === SUITE_PAIR), + })); + expect(census.forms.map((f) => [f.address, f.served.packageId, f.outcome]).sort()).toEqual([ + [{ kind: 'base', packageId: MODULE }, SUITE, 'hold'], + [{ kind: 'package', packageId: SUITE_PAIR }, SUITE_PAIR, 'hold'], + ].sort()); + expect(census.precheck.canSwitch).toBe(false); + }); + it('the pair\'s own row of the name, read at the pair\'s own address, claims the slot too: beside a row planned into that pair, both hold the upgrade (ruling record 7265816895)', () => { // The pair's own item, declaring no `overrides`: an old-shape `view` row, and a stored `form` row. for (const own of [viewFormRow(SUITE_PAIR, { enabled: true }), formRow(SUITE_PAIR, { enabled: true })]) { @@ -1060,3 +1183,79 @@ describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another addr expect(two.precheck.canSwitch).toBe(true); }); }); + +describe('[ADR-0159 D7-d] the fold\'s "closed today" reading, and the pair\'s own item with no `basedOn` (PR 2 of the card)', () => { + it('N4: a `view` row a `form` row outranks at its place is the row the `view` list serves: its withdrawal closes the form today, and the fold does not name it newly closed', () => { + const census = planStoredForms(input([formRow(undefined, { enabled: true }), viewFormRow(undefined, { enabled: false })])); + expect(census.forms).toEqual([expect.objectContaining({ + address: { kind: 'base', packageId: BASE }, + outcome: 'move', + served: expect.objectContaining({ type: 'form' }), + behind: [expect.objectContaining({ type: 'view', withdraws: SLUG })], + carries: expect.objectContaining({ slug: SLUG }), + newlyClosed: false, + })]); + }); + + it('N4 control: a second `view` row behind the first is read by no layer, and its withdrawal closes the form newly', () => { + const census = planStoredForms(input([formRow(undefined, { enabled: true }), viewFormRow(BASE, { enabled: true }), viewFormRow(undefined, { enabled: false })])); + expect(census.forms[0]).toMatchObject({ outcome: 'move', newlyClosed: true }); + }); + + describe('N16, at a base that ships the form', () => { + const SUITE = 'com.acme.suite'; + const SUITE_PAIR = 'com.acme.suite.custom'; + const manifests: Record }> = { + [SUITE]: { type: 'app' }, + [BASE]: { type: 'module', dependencies: { [SUITE]: '*' } }, + [PAIR]: {}, + }; + const over = { + installed: (id: string) => manifests[id], + isWritable: (pkg: string) => pkg === PAIR || pkg === SUITE_PAIR, + pairFix: (): PairFixReading => ({ ok: true, pair: SUITE_PAIR, basedOn: '1.0.0' }), + }; + + it('a second pair\'s override that withdraws the form is read today in that pair\'s own layer: carried, not newly closed', () => { + const census = planStoredForms(input([ + viewFormRow(SUITE_PAIR, { enabled: true, overrides: BASE }), + viewFormRow(PAIR, { enabled: false, overrides: BASE }), + ], over)); + expect(census.forms).toEqual([expect.objectContaining({ + address: { kind: 'base', packageId: BASE }, + served: expect.objectContaining({ packageId: SUITE_PAIR }), + behind: [expect.objectContaining({ packageId: PAIR, withdraws: SLUG })], + carries: expect.objectContaining({ slug: SLUG }), + newlyClosed: false, + })]); + }); + }); + + it('N14: 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 (no `basedOn` is declared); a declared override still holds there', () => { + const noVersion: PairFixReading = { ok: false, cause: 'app_author', refusal: 'no version', app: BASE, pairWithoutBasedOn: PAIR }; + const own = planStoredForms(input([viewFormRow(BASE, { enabled: true })], { ships: {}, pairFix: () => noVersion })); + expect(own.forms).toEqual([expect.objectContaining({ outcome: 'move', destination: { kind: 'pair_form', base: BASE, pair: PAIR } })]); + expect(own.precheck.canSwitch).toBe(true); + const declared = planStoredForms(input([viewFormRow(undefined, { enabled: true })], { pairFix: () => noVersion })); + expect(declared.forms).toEqual([expect.objectContaining({ outcome: 'hold', cause: 'app_author', refusal: 'no version' })]); + expect(declared.precheck.canSwitch).toBe(false); + }); +}); + +describe('[ADR-0159 D7-c] N5: where no pair id can be derived, the refusal is the planner\'s own sentence, with no raw reason code', () => { + const engineOf = (packages: Array<{ id: string; type?: string; dependencies?: Record }>) => ({ + registry: { getAllPackages: () => packages.map((m) => ({ manifest: { version: '1.0.0', ...m } })), getPackage: () => undefined }, + }); + for (const [base, words] of [ + ['com.example.forms.custom', 'is itself a paired customization package'], + ['Not A Package Id', 'is not a valid package id'], + ] as const) { + it(`base '${base}': the sentence names why, in words`, () => { + const fix = storedFormPairFix(engineOf([]) as never, base); + expect(fix.ok).toBe(false); + const refusal = (fix as Extract).refusal; + expect(refusal).toContain(words); + expect(refusal).not.toMatch(/base_[a-z_]+/); + }); + } +}); diff --git a/packages/metadata-protocol/src/protocol-stored-form-migration.ts b/packages/metadata-protocol/src/protocol-stored-form-migration.ts index b43f1e14adc..b3b36c0a543 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-migration.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-migration.ts @@ -80,7 +80,12 @@ * D7-e: a row that stands over a linked base is never listed for removal). * Not counted. * - `hold` — the move needs the base's pair and the pair cannot be ensured - * (D7-c). Counted: the upgrade does not switch. The hold names the cause, + * (D7-c). Counted: the upgrade does not switch. So does a move whose + * destination row the store seals (ADR-0131 D6): every destination but a + * declared override is written as an edit of the item a package ships at + * the name, and a managed package that ships the name as a `form` item + * seals it, so the census holds the row the run could not write + * ({@link sealedDestinationHold}). The hold names the cause, * repeats the ensure door's refusal, and gives the action for its cause. * A slot of a pair that more than one plan claims holds too, at every * claimant's address, the row named once ({@link holdContestedPairSlots}; @@ -96,7 +101,11 @@ * the served row carries no form at the name (a list, D7-d: every row of * the name at the address stays as stored; a list alone over a base that * ships the form is reported too), or the served row is internal and a row - * behind it declares a link ({@link INTERNAL_AHEAD_OF_LINKED_ROW}). + * behind it declares a link ({@link INTERNAL_AHEAD_OF_LINKED_ROW}), or the + * plan would move a form no door serves today (`served_by_no_door`: the + * effective `form` read lists no form of the name at the address; the + * plan is made first, so a hold it takes part in stands, and its move is + * then left in place, whatever package the row is bound to). * * A body the projection cannot read (D6 rule 7) holds the upgrade wherever it * stands (D7-c, `unreadable`), and an address whose served row is one waits @@ -117,7 +126,7 @@ * input): no write, no registry mutation. */ -import { pairOf, pairsOf, type InstalledManifestLookup } from '@objectstack/metadata-core'; +import { pairOf, pairsOf, type InstalledManifestLookup, type PairOfRefusal } from '@objectstack/metadata-core'; import { deriveViewContainerObject } from '@objectstack/spec'; import { customizationBasePackageId, @@ -135,6 +144,7 @@ import { installedManifestsOfEngine } from './installed-manifests.js'; import { customizationPairEnsureRefusal, kernelPackageScope, type PairRegistry } from './protocol-customization-package.js'; import { orderedFormRowsAt, + readEffectiveForms, storedFormPlaces, type FormReadHost, type OrderedFormRow, @@ -204,7 +214,14 @@ export type StoredFormLeftReason = /** {@link INTERNAL_AHEAD_OF_LINKED_ROW}. */ | 'internal_ahead_of_linked_row' /** The served row is a body the projection cannot read: the address waits on its hold. */ - | 'served_unreadable'; + | 'served_unreadable' + /** + * A form no door serves today is left in place by the upgrade: the + * effective `form` read lists no form of the name at the address the plan + * is made at ({@link StoredFormPlanInput.servedToday}). Not a withdrawn + * form, which the read lists switched off and D7 moves with its switch. + */ + | 'served_by_no_door'; /** A folded row's withdrawal the destination carries (D7-d). */ export interface StoredFormCarriedWithdrawal { @@ -355,6 +372,13 @@ export type PairFixReading = readonly app?: string; /** The per-package pair an earlier version created that holds the namespace (ADR-0146 D3, merge question 12). */ readonly earlierPair?: boolean; + /** + * The pair the door would ensure, where the only refusal is the base + * recording no version: a declared override has no `basedOn` to + * declare, while the pair's own `form` item declares none and moves + * (N14). + */ + readonly pairWithoutBasedOn?: string; }; /** The hold causes the pair door's refusal can carry. */ @@ -370,6 +394,19 @@ export interface StoredFormPlanInput { /** Every name a `type: 'form'` action opens, anywhere it is declared. */ readonly actionTargets: ReadonlySet; readonly pairFix: (base: string) => PairFixReading; + /** + * [ADR-0131 D6] The managed packages that ship `name` as a `form` item, + * where the store seals a `form` row of the name against a write as that + * item's edit; `[]` where it does not. Read as the run's write meets it + * ({@link storedFormSealedShippers}). + */ + readonly sealedFormShippers: (name: string) => readonly string[]; + /** + * Whether the effective `form` read the doors take their candidates from + * ({@link readEffectiveForms}) lists a form of `name` at `packageId` today + * (`undefined`: the environment's own address). + */ + readonly servedToday: (name: string, packageId: string | undefined) => boolean; readonly objectHasFieldGroups: (object: string) => boolean; /** The stored `view` bodies the projection cannot read. */ readonly unreadable: readonly { readonly type: string; readonly name: string; readonly packageId?: string; readonly reason: string; readonly links: readonly string[] }[]; @@ -1207,6 +1244,8 @@ export function planStoredForms(input: StoredFormPlanInput): StoredFormCensus { addresses.some((other) => other !== here && rowsAt.get(addressKey(other))?.[0]?.place === place); const plansOfName: { plan: StoredFormAddressPlan; rows: readonly OrderedFormRow[] }[] = []; + /** The addresses (by their rows) whose served row no door serves today. */ + const unservedAt = new Set(); for (const address of addresses) { const rows = rowsAt.get(addressKey(address))!; // An address where no row holds a form at the name has nothing to @@ -1254,6 +1293,16 @@ export function planStoredForms(input: StoredFormPlanInput): StoredFormCensus { ? first!.place.packageId === address.packageId : first!.place.packageId === undefined)); + // A form no door serves today is left in place by the upgrade + // (ADR-0159 D7, ruling record 7277149723): every plan that would + // move a row asks the effective `form` read whether it + // lists a form of the name at the address the plan is made at. The + // plan is still made, so a hold it takes part in stands; a move of + // it is left in place once every hold is read. + if (!atDestination && !input.servedToday(name, address.kind === 'environment' ? undefined : address.packageId)) { + unservedAt.add(rows); + } + if (!atDestination) { const internal = isInternal(first!, name, address, input, shipped); if (INTERNAL_AHEAD_OF_LINKED_ROW.applies(internal, behind)) { @@ -1283,6 +1332,19 @@ export function planStoredForms(input: StoredFormPlanInput): StoredFormCensus { }); continue; } + // A form no door serves today is left in place before the pair + // door's hold (D7-c) or the store's seal is read: neither is a + // hold the rule keeps standing for it (ADR-0159 D7). + if (unservedAt.has(rows) && (destination.kind === 'hold' || sealedDestinationHold(name, served, destination, input) !== undefined)) { + push({ ...base, outcome: 'left_in_place', reason: 'served_by_no_door' }); + continue; + } + const sealedBy = sealedDestinationHold(name, served, destination, input); + if (sealedBy !== undefined) { + push({ ...base, outcome: 'hold', cause: sealedBy.cause, refusal: sealedBy.refusal, action: sealedBy.action }); + holds.push(sealedBy); + continue; + } if (destination.kind === 'hold') { const action = storedFormHoldAction(destination.cause, { base: (address as { packageId: string }).packageId, @@ -1299,7 +1361,16 @@ export function planStoredForms(input: StoredFormPlanInput): StoredFormCensus { push({ ...base, outcome: 'keep', destination: keptDestination(address, first!), ...foldOf(first!, rest, served, behind, address, folded) }); continue; } - push({ ...base, outcome: atDestination ? 'keep' : 'move', destination, ...foldOf(first!, rest, served, behind, address, folded) }); + const fold = foldOf(first!, rest, served, behind, address, folded); + // A kept row the run writes (it carries a withdrawal) meets the + // store's seal the same way a moved row does (ADR-0131 D6). + const sealedKeep = atDestination && fold.carries !== undefined ? sealedDestinationHold(name, served, destination, input, 'kept') : undefined; + if (sealedKeep !== undefined) { + push({ ...base, outcome: 'hold', cause: sealedKeep.cause, refusal: sealedKeep.refusal, action: sealedKeep.action }); + holds.push(sealedKeep); + continue; + } + push({ ...base, outcome: atDestination ? 'keep' : 'move', destination, ...fold }); } const kept = keptRowsOf(plansOfName); @@ -1325,6 +1396,16 @@ export function planStoredForms(input: StoredFormPlanInput): StoredFormCensus { }; }); + // A form no door serves today is left in place by the upgrade: a move + // of it writes nothing (a hold it takes part in stands; the removal of + // an internal record form, which no public door serves by design, is + // ruling 3's and stays). + plansOfName.forEach(({ plan, rows }, index) => { + if (!unservedAt.has(rows) || plan.outcome !== 'move') return; + const { form, address, served, behind, untouched, alsoReadAt } = plan; + plansOfName[index] = { plan: { form, address, served, behind, untouched, alsoReadAt, outcome: 'left_in_place', reason: 'served_by_no_door' }, rows }; + }); + // Each plan names the rows another address reads too, and what it does. for (const { plan, rows } of plansOfName) { const elsewhere: StoredFormElsewhere[] = []; @@ -1411,10 +1492,44 @@ function pairFormDestination( if (ownPair !== undefined) return { kind: 'pair_form', base, pair: ownPair }; if (address.kind === 'package') return { kind: 'pair_form', base, pair: address.packageId }; const fix = input.pairFix(base); - if (!fix.ok) return holdOf(fix); + // [N14] The pair's own item declares no `basedOn`: a base that records no version holds no such move. + if (!fix.ok) return fix.pairWithoutBasedOn !== undefined ? { kind: 'pair_form', base, pair: fix.pairWithoutBasedOn } : holdOf(fix); return { kind: 'pair_form', base, pair: fix.pair }; } +/** + * [ADR-0131 D6] The hold of a plan that writes a destination row the store + * seals: a move, or a kept row that carries a withdrawal. The run writes every + * destination but a declared override (ADR-0146 D2, a runtime write) as an + * edit of the item a package ships at the name, and the store refuses that + * write on a `form` a managed package ships: the census reads the same seal, + * so the row holds here instead of failing the run. The cause is in the + * shipping package, its author's to remove. + */ +function sealedDestinationHold( + name: string, + served: StoredFormRowRef, + destination: DestinationReading, + input: Pick, + plan: 'moved' | 'kept' = 'moved', +): StoredFormHold | undefined { + if (destination.kind === 'hold' || destination.kind === 'pair_override') return undefined; + const shippers = input.sealedFormShippers(name); + if (shippers.length === 0) return undefined; + const quoted = shippers.map((id) => `'${id}'`).join(' and '); + const into = destination.kind === 'pair_form' ? `'${destination.pair}'` : destination.kind === 'package_form' ? `'${destination.packageId}'` : 'the environment'; + return { + row: served, + cause: 'app_author', + refusal: (plan === 'moved' + ? `The ${rowWords(served)} would move into ${into} as a \`form\` row '${name}'` + : `The ${rowWords(served)} is a \`form\` row '${name}' kept in ${into} that would be written to carry a withdrawal`) + + `, and ${quoted} ${shippers.length > 1 ? 'ship' : 'ships'}` + + ` a \`form\` item of that name: a managed package's item is sealed against every write onto it (ADR-0131 D6), so the row cannot be written there.`, + action: `The cause is in ${quoted}, its author's to remove. ${NO_MEASURED_EXIT}`, + }; +} + /** The destination of a stored `form` override kept where it stands, when the pair door refuses an ensure now. */ function keptDestination(address: StoredFormAddress, served: OrderedFormRow): StoredFormDestination { const overrides = isRecord(served.place.entry.data) ? served.place.entry.data.overrides : undefined; @@ -1480,8 +1595,18 @@ function foldOf( const forms = rest.filter((row) => row.holding.kind === 'form'); let layer: StoredFormPlace | undefined; if (address.kind === 'base' && first.overrideOf !== undefined) layer = rest.find((row) => row.overrideOf === undefined && !folded.has(row.place))?.place; + // [N4] Behind a served `form` row, the first `view` row is the row the + // effective `view` list serves here, the `form` row being no row of that + // type: its withdrawal closes the form today. + const firstOfItsType = (row: OrderedFormRow): boolean => + first.place.type === 'form' && row.place.type === 'view' && rest.find((r) => r.place.type === 'view') === row; + // [N16] A declared override in another pair of the base than the served + // one's is read today in that pair's own per-package layer. + const ownPairLayer = (row: OrderedFormRow): boolean => + first.overrideOf !== undefined && row.overrideOf !== undefined && row.place.packageId !== first.place.packageId; const closesToday = behind.some((row, i) => row.withdraws !== undefined - && (forms[i]?.place === layer || forms[i]?.moved !== undefined || folded.get(forms[i]!.place) === true)); + && (forms[i]?.place === layer || forms[i]?.moved !== undefined || folded.get(forms[i]!.place) === true + || firstOfItsType(forms[i]!) || ownPairLayer(forms[i]!))); // The address that closes is the kept body's: it keeps its own link and switches it off. return { carries: { slug: served.link, from }, newlyClosed: !closesToday }; } @@ -1505,7 +1630,33 @@ function sharedSlugsOf(places: readonly StoredFormPlace[]): StoredFormCensus['sh // ── The host reading ──────────────────────────────────────────────────────── /** The host members the census reads. */ -export type StoredFormCensusHost = FormReadHost & Pick; +export type StoredFormCensusHost = FormReadHost & Pick; + +/** + * [ADR-0131 D6] The managed packages that ship `name` as a `form` item, where + * the store seals a `form` row of the name: the predicate the protocol's doors + * ask ({@link ProtocolHost.isSealedManagedItem}), read for the census as the + * run's write meets it at the store. `[]` where nothing seals it. + */ +function storedFormSealedShippers(host: Pick, name: string): string[] { + if (!host.isSealedManagedItem('form', name)) return []; + const ids = host.shippedArtifactsOf('form', name) + .map((a) => (a as { _packageId?: unknown } | null)?._packageId) + .filter((id): id is string => typeof id === 'string' && id !== ''); + const sorted = [...new Set(ids)].sort(); + return sorted.length > 0 ? sorted : ['a managed package']; +} + +/** + * [N5] Why no pair id can be derived from a base, in the planner's own words: + * one clause per reason `pairOf` gives, never the raw reason code. + */ +const PAIR_ID_REFUSAL_WORDS: Readonly> = { + no_single_app: 'declares several Apps and its namespace picks none', + base_id_missing: 'has no package id', + base_is_customization_package: 'is itself a paired customization package, and a pair has no pair of its own', + base_id_invalid: 'is not a valid package id, and the pair\'s id is derived from it', +}; /** * [ADR-0159 D7-c] Whether `base`'s pair can be ensured for the move, read @@ -1520,9 +1671,7 @@ export function storedFormPairFix(engine: ProtocolHost['engine'], base: string): return { ok: false, cause: 'app_author', - refusal: pairId.reason === 'no_single_app' - ? `Package '${base}' declares several Apps and its namespace picks none, so it has no paired customization package (ADR-0146 D3).` - : `Package '${base}' has no paired customization package: ${pairId.reason} (ADR-0146 D3).`, + refusal: `Package '${base}' ${PAIR_ID_REFUSAL_WORDS[pairId.reason]}, so it has no paired customization package (ADR-0146 D3).`, }; } const pair = pairId.value; @@ -1558,7 +1707,10 @@ export function storedFormPairFix(engine: ProtocolHost['engine'], base: string): } const basedOn = registry.getPackage(base)?.manifest?.version; if (typeof basedOn !== 'string' || basedOn === '') { - return { ok: false, cause: 'app_author', refusal: `Package '${base}' records no version, so an override of it has no \`basedOn\` to declare (ADR-0146 D2).`, app: appId }; + return { + ok: false, cause: 'app_author', app: appId, pairWithoutBasedOn: pair, + refusal: `Package '${base}' records no version, so an override of it has no \`basedOn\` to declare (ADR-0146 D2).`, + }; } return { ok: true, pair, basedOn }; } @@ -1585,6 +1737,15 @@ function collectFormActionTargets(value: unknown, out: Set, depth = 0): export async function listStoredForms(host: StoredFormCensusHost): Promise { const places = await storedFormPlaces(host); const installed = installedManifestsOfEngine(host.engine); + // The forms the read serves today, by package and name: the list the doors read. + const servedNow = new Set(); + const servedNames = new Set(); + for (const item of await readEffectiveForms(host, { type: 'form' }, 'served')) { + const { name, _packageId: packageId } = (item ?? {}) as { name?: unknown; _packageId?: unknown }; + if (typeof name !== 'string') continue; + servedNames.add(name); + if (typeof packageId === 'string') servedNow.add(`${packageId}\u0000${name}`); + } const registry = (host.engine as unknown as { registry?: { listItems?: (type: string) => unknown[] } }).registry; const list = (type: string): unknown[] => { try { @@ -1661,6 +1822,9 @@ export async function listStoredForms(host: StoredFormCensusHost): Promise host.isWritablePackage(packageId), actionTargets, pairFix: (base) => storedFormPairFix(host.engine, base), + sealedFormShippers: (name) => storedFormSealedShippers(host, name), + // The environment's own address: a package-less row the read seats in a package's slot is served there (#21817). + servedToday: (name, packageId) => (packageId === undefined ? servedNames.has(name) : servedNow.has(`${packageId}\u0000${name}`)), objectHasFieldGroups: (object) => { const groups = (objects.get(object) as { fieldGroups?: unknown } | undefined)?.fieldGroups; return Array.isArray(groups) ? groups.length > 0 : isRecord(groups) && Object.keys(groups).length > 0; diff --git a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts index 09a34b5ed83..13f5483241b 100644 --- a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts +++ b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts @@ -420,9 +420,11 @@ describe('#17501 — /meta/types serves a real schema for `action`, and moves no // record and its master-detail lines are closed to change. // [#37792] `object` 54 → 55: `pinOverview`, the record page layout switch // (ADR-0085's Note of 2026-11-27). + // [#37802] `object` 55 → 56: `fieldTabs`, the record page's field tabs + // (the same Note). const CARD_PROPERTY_COUNTS: Record = { agent: 24, app: 24, dashboard: 21, dataset: 17, field: 89, flow: 24, - hook: 24, object: 55, page: 28, position: 14, report: 24, skill: 18, tool: 14, + hook: 24, object: 56, page: 28, position: 14, report: 24, skill: 18, tool: 14, }; it.each(Object.entries(CARD_PROPERTY_COUNTS))( diff --git a/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts b/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts index 82aa729b9d2..7eed9f46409 100644 --- a/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts +++ b/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts @@ -38,7 +38,7 @@ // The trace, measured on `origin/main` — all four routes fold at the producer // --------------------------------------------------------------------------- // `applyObjectRegistryMutation` has exactly ONE caller -// (`applyRegistryWriteThrough`), which has exactly NINE (the orphan +// (`applyRegistryWriteThrough`), which has exactly TEN (the orphan // adoption's, `reassignOrphanedMetadata`, retired with its door, #38150): // // 1. `saveMetaItem` passes `singularTypeForRepo`, and the method @@ -79,6 +79,11 @@ // 9. `undoLanded` (#38150) passes the same folded type: it writes back // through each loose row a refused move put // back with no transaction to cover it. +// 10. `healStoredFormRows` (ADR-0159 D7) passes the literal `'form'` for +// each copy the stored-form ceremony wrote, +// and for a container it re-saved the type of +// the stored row it read under the literal +// `'view'`, so no stored spelling reaches it. // // Both fold maps resolve the plural — `PLURAL_TO_SINGULAR.objects === 'object'` // and `canonicalMetaUrlType('objects') === 'object'` — so no route can deliver @@ -588,9 +593,9 @@ describe('[#8862] the `applyRegistryWriteThrough` caller set stays closed', () = const sources = [source, ...SPLIT_MODULES.map((file) => readFileSync(fileURLToPath(new URL(`./${file}`, import.meta.url)), 'utf8'))]; const sitesOf = (pattern: RegExp) => sources.flatMap((text) => text.match(pattern) ?? []); - it('has exactly nine call sites, all traced in this file’s header', () => { + it('has exactly ten call sites, all traced in this file’s header', () => { const callSites = sitesOf(/\b(?:this|host)\.applyRegistryWriteThrough\(/g); - expect(callSites).toHaveLength(9); + expect(callSites).toHaveLength(10); }); it('`applyObjectRegistryMutation` is reached only through the write-through', () => { diff --git a/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts b/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts index 4b9177762a5..536cca00b43 100644 --- a/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts +++ b/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts @@ -156,7 +156,7 @@ type Route = * transaction and hands the rows it wrote back: each caller calls `then` * after the commit, and `then` both writes through and heals. */ - | { readonly handedTo: 'module callers'; readonly then: 'healOldShapeFormRowRemovals' }; + | { readonly handedTo: 'module callers'; readonly then: 'healOldShapeFormRowRemovals' | 'healStoredFormRows' }; // [#28355] A door's write lives in its `…Unaudited` body; the public door of the same name // only wraps it with the refusal audit, so the member is the body's name. @@ -184,6 +184,11 @@ const WRITES: ReadonlyArray<{ readonly member: string; readonly verb: string; re { member: 'applyOldShapeFormRowRemovals', verb: 'repo.put(', route: { handedTo: 'module callers', then: 'healOldShapeFormRowRemovals' } }, // [ADR-0159 D5] …and the undo of that write on a runtime that cannot roll back puts each row back, healed. { member: 'restoreOldShapeFormRowRemovals', verb: 'repo.restoreVersion(', route: { sameMember: 'restoreArtifactRegistryView' } }, + // [ADR-0159 D7] The stored-form ceremony's write half: the copies and the old rows it takes, in one + // transaction; its caller heals the registry from the rows handed back, after the commit. + { member: 'writeStoredFormCopies', verb: 'repo.put(', route: { handedTo: 'module callers', then: 'healStoredFormRows' } }, + { member: 'takeStoredFormRows', verb: 'repo.delete(', route: { handedTo: 'module callers', then: 'healStoredFormRows' } }, + { member: 'takeStoredFormRows', verb: 'repo.put(', route: { handedTo: 'module callers', then: 'healStoredFormRows' } }, ]; /** The verb as `WRITES` spells it: no whitespace after its open paren, [#29985] the class as `this`. */ @@ -289,6 +294,9 @@ describe('[#29985] the census reads the modules the split moved bodies to', () = 'protocol-form-writes.ts: restoreOldShapeFormRowRemovals', 'protocol-package-move-in.ts: undoLanded', 'protocol-packageless-overlay-migration.ts: migratePackagelessOverlays', + 'protocol-stored-form-apply.ts: writeStoredFormCopies', + 'protocol-stored-form-apply.ts: takeStoredFormRows', + 'protocol-stored-form-apply.ts: takeStoredFormRows', ]); }); }); diff --git a/packages/objectql/src/protocol-stored-form-migration.test.ts b/packages/objectql/src/protocol-stored-form-migration.test.ts index d019a72bcc7..a19ea52383f 100644 --- a/packages/objectql/src/protocol-stored-form-migration.test.ts +++ b/packages/objectql/src/protocol-stored-form-migration.test.ts @@ -31,7 +31,7 @@ import './__fixtures__/lint-root-preload.testkit.js'; import { describe, expect, it } from 'vitest'; import type { ServiceObject } from '@objectstack/spec/data'; -import { ObjectStackProtocolImplementation, listStoredFormsOf } from '@objectstack/metadata-protocol'; +import { ObjectStackProtocolImplementation, applyStoredFormsOf, listStoredFormsOf } from '@objectstack/metadata-protocol'; import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObject } from '@objectstack/metadata-core'; import { ObjectQL } from './engine.js'; @@ -171,7 +171,7 @@ async function boot() { } as any); const protocol = new ObjectStackProtocolImplementation(engine, () => new Map()); const snapshot = () => JSON.stringify([...(stores.get('sys_metadata')?.values() ?? [])]); - return { engine, protocol, snapshot }; + return { engine, protocol, snapshot, stores }; } /** @@ -383,14 +383,16 @@ describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another addr newlyClosed: false, })]); }); - it('ruling record 7250977204 stands for every row its premise holds for: the read serves the row at the package it is bound to, and the census plans it there', async () => { + it('ruling record 7250977204 stands for every row its premise holds for: the read serves the row at the package it is bound to, and the census plans it there; the module ships the name as a `form` item, so the pair\'s own row is sealed (ADR-0131 D6) and the row holds there', async () => { const { engine, protocol } = await bootSuite({ moduleAs: 'form' }); await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(true)), label: 'Stored' }, SUITE); // The read today: the stored body under the App it is bound to, the module's own form at the module. expect((await servedForms(protocol)).sort()).toEqual([[SUITE, 'Stored'], [MODULE, 'Shipped form']]); - expect((await plansOf(protocol)).map((f) => [f.address.packageId, f.served.packageId, f.outcome, f.destination])).toEqual([ - [SUITE, SUITE, 'move', { kind: 'pair_form', base: SUITE, pair: SUITE_PAIR }], + const plans = await plansOf(protocol); + expect(plans.map((f) => [f.address.packageId, f.served.packageId, f.outcome, 'cause' in f ? f.cause : undefined])).toEqual([ + [SUITE, SUITE, 'hold', 'app_author'], ]); + expect((plans[0] as { refusal?: string }).refusal).toContain(`'${MODULE}'`); }); it('a stored `form` row the read serves at the package it is bound to is planned there', async () => { @@ -412,15 +414,16 @@ describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another addr ]); expect(result.precheck).toMatchObject({ canSwitch: false, holds: [{ row: { packageId: SUITE }, cause: 'app_author' }] }); }); - it('a member of a stored container is read at the package the container is bound to: the read serves the module\'s shipped form at the module, and the census plans the member at its own address', async () => { + it('a member of a stored container is read at the package the container is bound to: the read serves the module\'s shipped form at the module, and the census plans the member at its own address; a form no door serves today is left in place by the upgrade', async () => { const { engine, protocol } = await bootSuite({ appOwnsObject: true, moduleForm: {} }); await storeRow(engine, SUITE_OBJECT, { name: SUITE_OBJECT, object: SUITE_OBJECT, formViews: { contact: formBody(SUITE_OBJECT, { layout: 'horizontal' }) } }, SUITE); // The read today: one form of the name, the module's own, under the module. const served = ((await protocol.getMetaItems({ type: 'form' })) as any).items.filter((item: any) => item?.name === SUITE_NAME); expect(served.map((item: any) => [item._packageId, item.layout])).toEqual([[MODULE, undefined]]); expect((await plansOf(protocol)).map((f) => [f.address.packageId, f.served.packageId, f.served.grain, f.outcome, f.destination])).toEqual([ - [SUITE, SUITE, 'expansion', 'move', { kind: 'pair_form', base: SUITE, pair: SUITE_PAIR }], + [SUITE, SUITE, 'expansion', 'left_in_place', undefined], ]); + expect((await plansOf(protocol))[0]).toMatchObject({ reason: 'served_by_no_door' }); }); it('the pair\'s own row of the name, beside a row the census plans into that pair: today the module serves the bound row and the pair\'s own per-package layer reads its own row, and the census holds the upgrade at both (ruling record 7265816895)', async () => { @@ -577,3 +580,285 @@ describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another addr }); } }); + +/** + * [ADR-0159 D7; ruling records 7142585849 (items 2 and 3) and 7250977204] The + * ceremony's write half over the real protocol: `applyStoredFormsOf`, the + * `--apply` the major's upgrade command calls. The move, the fold, the + * removal, all or nothing with the switch, and a second run that moves + * nothing. + */ +describe('[ADR-0159 D7] applyStoredForms over the real protocol', () => { + const LIST_BODY = { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } }; + const stored = async (engine: ObjectQL, type: string, name: string): Promise> => + ((await engine.find('sys_metadata', { where: { type, name, state: 'active' } }, { context: { isSystem: true } })) as any[]) + .map((r) => ({ packageId: r.package_id ?? null, body: typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata })); + const formsAt = async (protocol: ObjectStackProtocolImplementation, name: string): Promise> => + ((await protocol.getMetaItems({ type: 'form' })) as any).items + .filter((item: any) => item?.name === name) + .map((item: any) => [item._packageId, item.sharing?.enabled]); + const apply = (protocol: ObjectStackProtocolImplementation): Promise => applyStoredFormsOf(protocol, { actor: null }); + + it('moves a package-less old-shape row over the base\'s linked form into the pair as its declared override, deletes the old row once the copy reads back, and a second run moves nothing', async () => { + const { engine, protocol, snapshot } = await boot(); + await storeRow(engine, NAME, viewItem(NAME, OBJECT, sharing(false))); + // The read today: the base's linked form, switched off by the stored row. + expect(await formsAt(protocol, NAME)).toEqual([[BASE, false]]); + const result = await apply(protocol); + expect(result).toMatchObject({ + applied: true, + pairsEnsured: [PAIR], + written: [{ form: NAME, row: { type: 'form', name: NAME, packageId: PAIR }, destination: { kind: 'pair_override', base: BASE, pair: PAIR, basedOn: '1.2.0' } }], + removed: [], + rowsChanged: [{ type: 'view', name: NAME, change: 'deleted' }], + }); + expect(await stored(engine, 'view', NAME)).toEqual([]); + const [moved] = await stored(engine, 'form', NAME); + expect(moved).toMatchObject({ packageId: PAIR, body: { name: NAME, overrides: { package: BASE, basedOn: '1.2.0' }, sharing: { publicLink: `/forms/${SLUG}`, enabled: false } } }); + // The address answers as before: the form, switched off. + expect(await formsAt(protocol, NAME)).toEqual([[BASE, false]]); + // Idempotent: the second run finds the row at its destination and writes nothing. + const after = snapshot(); + const again = await apply(protocol); + expect(again).toMatchObject({ applied: true, pairsEnsured: [], written: [], removed: [], rowsChanged: [] }); + expect(again.census.forms.filter((f: any) => f.form === NAME).map((f: any) => f.outcome)).toEqual(['keep']); + expect(snapshot()).toBe(after); + }); + + it('a container with lists and forms: the internal record form is removed, the public one moves, and the container is re-saved with its list byte-equal', async () => { + const { engine, protocol } = await boot(); + await storeRow(engine, OBJECT, { + name: OBJECT, object: OBJECT, list: LIST_BODY, + form: formBody(OBJECT, { label: 'Edited' }), formViews: { contact: formBody(OBJECT, sharing(false)) }, + }); + const result = await apply(protocol); + expect(result.applied).toBe(true); + expect(result.removed).toEqual([expect.objectContaining({ + form: `${OBJECT}.form`, object: OBJECT, objectHasFieldGroups: false, + body: expect.objectContaining({ label: 'Edited' }), + })]); + expect(result.written.map((w: any) => [w.form, w.row.packageId])).toEqual([[NAME, PAIR]]); + expect(result.rowsChanged).toEqual([{ type: 'view', name: OBJECT, change: 'resaved' }]); + const [container] = await stored(engine, 'view', OBJECT); + expect(container!.body).toEqual({ name: OBJECT, object: OBJECT, list: LIST_BODY }); + expect(JSON.stringify(container!.body.list)).toBe(JSON.stringify(LIST_BODY)); + expect((await apply(protocol))).toMatchObject({ written: [], removed: [], rowsChanged: [] }); + }); + + it('an item-shaped internal record form is deleted, its body in the report, and no history row is rewritten', async () => { + const { engine, protocol } = await boot(); + const name = `${OBJECT}.form`; + await storeRow(engine, name, { name, object: OBJECT, viewKind: 'form', isDefault: true, label: 'Internal', config: formBody(OBJECT, { label: 'Internal' }) }); + await engine.insert('sys_metadata_history', { + id: 'h_seed', type: 'view', name, organization_id: null, package_id: null, version: 1, + metadata: JSON.stringify({ name, label: 'Older' }), checksum: 'seed', operation_type: 'create', recorded_at: '2026-01-01T00:00:00.000Z', + }, { context: { isSystem: true } }).catch(() => undefined); + const historyBefore = JSON.stringify(((await engine.find('sys_metadata_history', {}, { context: { isSystem: true } })) as any[]).filter((r) => r.id === 'h_seed')); + const result = await apply(protocol); + expect(result.removed).toEqual([expect.objectContaining({ form: name, object: OBJECT, body: expect.objectContaining({ label: 'Internal' }) })]); + expect(result.rowsChanged).toEqual([{ type: 'view', name, change: 'deleted' }]); + expect(await stored(engine, 'view', name)).toEqual([]); + expect(await stored(engine, 'form', name)).toEqual([]); + expect(JSON.stringify(((await engine.find('sys_metadata_history', {}, { context: { isSystem: true } })) as any[]).filter((r) => r.id === 'h_seed'))).toBe(historyBefore); + }); + + it('all or nothing: beside a row that holds the upgrade, nothing is written and no pair is ensured; with the cause removed, every row moves (ablate: move what can be moved and report the rest)', async () => { + const { engine, protocol, snapshot } = await boot(); + await storeRow(engine, NAME, viewItem(NAME, OBJECT, sharing(false))); + const broken = `${OBJECT}.broken`; + await storeRow(engine, broken, { name: broken, viewKind: 'form', ...sharing(true) }); + const before = snapshot(); + const held = await apply(protocol); + expect(held).toMatchObject({ applied: false, pairsEnsured: [], written: [], removed: [], rowsChanged: [] }); + expect(held.census.precheck.canSwitch).toBe(false); + expect(held.census.precheck.holds).toEqual([expect.objectContaining({ cause: 'unreadable', row: expect.objectContaining({ name: broken }) })]); + expect(snapshot()).toBe(before); + expect((engine.registry as any).getPackage(PAIR)).toBeUndefined(); + expect(await formsAt(protocol, NAME)).toEqual([[BASE, false]]); + // The cause removed (the unreadable row gone), the run moves every row. + await protocol.deleteMetaItem({ type: 'view', name: broken } as any); + const moved = await apply(protocol); + expect(moved).toMatchObject({ applied: true, written: [{ form: NAME, row: { packageId: PAIR } }] }); + expect(await stored(engine, 'view', NAME)).toEqual([]); + expect(await formsAt(protocol, NAME)).toEqual([[BASE, false]]); + }); +}); + +/** + * [ADR-0159 D7; ruling records 7265816895 (step 5), 7249158572] A row the + * census holds: `--apply` writes nothing, every stored row byte-equal, and + * every address of the name serves what it served before the refused run. + * Each shape is a held-row shape the census pins above name; the last two are + * the engine half of the planner's pins of a row kept as stored behind an + * internal form (S14), and the third-address shape. + */ +describe('[ADR-0159 D7] a held row: applyStoredForms writes nothing at any address', () => { + /** Every effective `form` item of `name`: the package it is served under, and its body. */ + const servedAt = async (protocol: ObjectStackProtocolImplementation, name: string): Promise => + JSON.stringify(((await protocol.getMetaItems({ type: 'form' })) as any).items + .filter((item: any) => item?.name === name) + .map((item: any) => [item._packageId, item]) + .sort((a: any, b: any) => String(a[0]).localeCompare(String(b[0])))); + const declaring = (base: string) => ({ overrides: { package: base, basedOn: '3.0.0' } }); + /** Run `--apply` over a held store: refused, nothing written, both the store and every address as before. */ + const refusedRun = async (protocol: ObjectStackProtocolImplementation, snapshot: () => string, name: string, holdsAt: number) => { + const before = snapshot(); + const served = await servedAt(protocol, name); + const plans = (await census(protocol)).forms.filter((f: any) => f.form === name); + expect(plans.filter((f: any) => f.outcome === 'hold')).toHaveLength(holdsAt); + const result = await applyStoredFormsOf(protocol, { actor: null }); + expect(result).toMatchObject({ applied: false, written: [], removed: [], rowsChanged: [], pairsEnsured: [] }); + expect(result.census.precheck.canSwitch).toBe(false); + expect(snapshot()).toBe(before); + expect(await servedAt(protocol, name)).toBe(served); + return plans; + }; + + it('served at two modules (ruling record 7265816895, step 5)', async () => { + const { engine, protocol, snapshot } = await bootSuite({ second: true }); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT), label: 'No link' }, SUITE); + await refusedRun(protocol, snapshot, SUITE_NAME, 2); + }); + + it('served at its own package and at the module (ruling record 7265816895, step 5)', async () => { + const { engine, protocol, snapshot } = await bootSuite({ appShipsForm: true }); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT), label: 'No link' }, SUITE); + await refusedRun(protocol, snapshot, SUITE_NAME, 2); + }); + + for (const type of ['view', 'form'] as const) { + it(`a pair slot two plans claim, the pair's own ${type} row beside a row planned into it (ruling record 7265816895, every contested slot)`, async () => { + const { engine, protocol, snapshot } = await bootSuite(); + const own = type === 'view' + ? { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(true)), label: 'Pair own' } + : { name: SUITE_NAME, object: SUITE_OBJECT, label: 'Pair own', type: 'simple', sections: [{ fields: ['name'] }], ...sharing(true) }; + await storeRow(engine, SUITE_NAME, own, SUITE_PAIR, type); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(false)), label: 'Switched off' }, SUITE); + await refusedRun(protocol, snapshot, SUITE_NAME, 2); + }); + } + + it('served at two modules, left in place at one and moved at the other', async () => { + const { engine, protocol, snapshot } = await bootSuite({ second: true, moduleForm: {} }); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT), label: 'Internal override', isDefault: true, ...declaring(SUITE) }, SUITE_PAIR); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(true)), label: 'Linked' }, SUITE); + await refusedRun(protocol, snapshot, SUITE_NAME, 2); + }); + + it('S14 over the real read: a package-less internal row ahead of a package-less container whose member is linked, kept as stored at one App\'s address, behind the row bound to another App that would move: that move holds, the kept rows listed apart (ruling record 7249158572)', async () => { + const { engine, protocol, snapshot } = await boot(); + registerOther(engine, 'com.example.other', formBody(OBJECT)); + await storeRow(engine, NAME, { ...viewItem(NAME, OBJECT), label: 'Internal', isDefault: true }); + await storeRow(engine, OBJECT, { name: OBJECT, object: OBJECT, formViews: { contact: formBody(OBJECT, sharing(true)) } }); + await storeRow(engine, NAME, { ...viewItem(NAME, OBJECT, sharing(true)), label: 'Linked' }, BASE); + const plans = await refusedRun(protocol, snapshot, NAME, 1); + const held = plans.find((f: any) => f.outcome === 'hold'); + expect(held).toMatchObject({ address: { kind: 'base', packageId: BASE }, cause: 'app_author', behind: [] }); + expect(held.heldApart.map((r: any) => [r.packageId, r.grain])).toEqual([[undefined, 'item'], [undefined, 'expansion']]); + expect(held.refusal).toContain('7249158572'); + }); + + it('the third-address shape: a row kept behind an internal form left in place at one address, served and moved at another, the internal row served apart at a third: every plan of the name holds and nothing is written', async () => { + const { engine, protocol, snapshot } = await bootSuite({ appShipsForm: true, appOwnsObject: true, moduleForm: {} }); + // A further App that ships the form linked: the package-less internal row is read there too, apart. + engine.registerApp({ + id: 'com.example.other', name: 'other', version: '2.0.0', type: 'app', namespace: 'other', + forms: [{ name: SUITE_NAME, object: SUITE_OBJECT, label: 'Other', type: 'simple', sections: [{ fields: ['name'] }], ...sharing(true) }], + } as any); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT), label: 'Internal', isDefault: true }); + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(true)), label: 'Linked' }, SUITE); + const plans = await refusedRun(protocol, snapshot, SUITE_NAME, 3); + expect(plans.map((f: any) => [f.address.packageId, f.outcome, f.served?.packageId]).sort()).toEqual([ + ['com.example.other', 'hold', undefined], + [MODULE, 'hold', undefined], + [SUITE, 'hold', SUITE], + ].sort()); + }); +}); + +describe('[ADR-0159 D7, ruling record 7249158572] N33: a container member kept as stored beside a sibling member that moves', () => { + it('the kept member reads back byte-equal after --apply, the moved sibling is gone from the container, and the container keeps nothing else', async () => { + const { engine, protocol } = await bootSuite({ moduleForm: {} }); + const INTAKE = `${SUITE_OBJECT}.intake`; + // At the module: a package-less internal form ahead of the container's linked member, both left in place. + await storeRow(engine, SUITE_NAME, { ...viewItem(SUITE_NAME, SUITE_OBJECT), label: 'Internal', isDefault: true }); + const contact = formBody(SUITE_OBJECT, { label: 'Kept member', ...sharing(true) }); + const intake = formBody(SUITE_OBJECT, { label: 'Moved member', sharing: { publicLink: '/forms/intake-37111', enabled: true, allowAnonymous: true } }); + await storeRow(engine, SUITE_OBJECT, { name: SUITE_OBJECT, object: SUITE_OBJECT, formViews: { contact, intake } }); + const before = (await census(protocol)).forms; + expect(before.filter((f: any) => f.form === SUITE_NAME).map((f: any) => f.outcome)).toEqual(['left_in_place']); + expect(before.filter((f: any) => f.form === INTAKE).map((f: any) => [f.outcome, f.destination])).toEqual([['move', { kind: 'environment_form' }]]); + const result = await applyStoredFormsOf(protocol, { actor: null }); + expect(result.applied).toBe(true); + expect(result.written.map((w: any) => w.form)).toEqual([INTAKE]); + const rows = ((await engine.find('sys_metadata', { where: { type: 'view', name: SUITE_OBJECT, state: 'active' } }, { context: { isSystem: true } })) as any[]); + expect(rows).toHaveLength(1); + const kept = JSON.parse(rows[0].metadata); + expect(JSON.stringify(kept.formViews.contact)).toBe(JSON.stringify(contact)); + expect(kept.formViews).not.toHaveProperty('intake'); + // The internal row ahead of it is left in place as well. + expect(((await engine.find('sys_metadata', { where: { type: 'view', name: SUITE_NAME, state: 'active' } }, { context: { isSystem: true } })) as any[])).toHaveLength(1); + }); +}); + +describe('[ADR-0159 D7-c, ADR-0146 D3] N13: the pair door\'s refusals and the draft read, through the real protocol', () => { + const switchedOff = { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(false)), label: 'Switched off' }; + const planOf = async (protocol: ObjectStackProtocolImplementation) => (await census(protocol)).forms.filter((f: any) => f.form === SUITE_NAME); + + it('control: with the pair\'s namespace free, the row bound to the App moves into the pair', async () => { + const { engine, protocol } = await bootSuite(); + await storeRow(engine, SUITE_NAME, switchedOff, SUITE); + expect((await planOf(protocol)).map((f: any) => [f.outcome, f.destination?.kind])).toEqual([['move', 'pair_override']]); + }); + + it('the per-package pair an earlier version created for a member of the App holds the namespace: the door\'s 409, read as that pair (administrator, no command on this release), and --apply writes nothing', async () => { + const { engine, protocol, snapshot } = await bootSuite(); + engine.registerApp({ + id: `${MODULE}.custom`, name: 'suite-service-custom', version: '0.1.0', type: 'app', namespace: 'suite_custom', + dependencies: { [MODULE]: '^3.1.0' }, + } as any); + await storeRow(engine, SUITE_NAME, switchedOff, SUITE); + const [plan] = await planOf(protocol); + expect(plan).toMatchObject({ outcome: 'hold', cause: 'administrator' }); + expect(plan.refusal).toContain('re-identified as the App\'s pair'); + // Read as the earlier pair: the action names no command that clears it. + expect(plan.action).toContain('no command on this release does that'); + const before = snapshot(); + expect(await applyStoredFormsOf(protocol, { actor: null })).toMatchObject({ applied: false, written: [], pairsEnsured: [] }); + expect(snapshot()).toBe(before); + }); + + it('a package outside the App holds the namespace: the door\'s 422, read as the administrator\'s, not as an earlier pair', async () => { + const { engine, protocol } = await bootSuite(); + engine.registerApp({ id: 'com.example.squatter', name: 'squatter', version: '1.0.0', type: 'app', namespace: 'suite_custom' } as any); + await storeRow(engine, SUITE_NAME, switchedOff, SUITE); + const [plan] = await planOf(protocol); + expect(plan).toMatchObject({ outcome: 'hold', cause: 'administrator' }); + expect(plan.refusal).toContain('already owned by package \'com.example.squatter\''); + expect(plan.action).not.toContain('no command on this release does that'); + expect(plan.action).toContain('Remove the cause the refusal names'); + }); + + it('an old-shape draft is listed, and --apply leaves it as stored (ruling record 7250982640)', async () => { + const { engine, protocol } = await bootSuite(); + await engine.insert('sys_metadata', { + type: 'view', name: SUITE_NAME, organization_id: null, package_id: SUITE, + metadata: JSON.stringify(switchedOff), state: 'draft', version: 1, + }, { context: { isSystem: true } }); + expect((await census(protocol)).drafts).toEqual([{ type: 'view', name: SUITE_NAME, packageId: SUITE }]); + const drafts = async () => ((await engine.find('sys_metadata', { where: { type: 'view', name: SUITE_NAME, state: 'draft' } }, { context: { isSystem: true } })) as any[]).map((r) => r.metadata); + const before = await drafts(); + expect((await applyStoredFormsOf(protocol, { actor: null })).applied).toBe(true); + expect(await drafts()).toEqual(before); + }); +}); + +/** A second App and its module, which ships `formViews.contact` on {@link OBJECT} with `contact` as given. */ +function registerOther(engine: ObjectQL, id: string, contact: Record) { + engine.registerApp({ id, name: id.split('.').pop(), version: '2.0.0', type: 'app', namespace: id.split('.').pop() } as any); + engine.registerApp({ + id: `${id}.desk`, name: `${id.split('.').pop()}-desk`, version: '2.1.0', type: 'module', namespace: id.split('.').pop(), + dependencies: { [id]: '^2.0.0' }, + views: [{ object: OBJECT, formViews: { contact } }], + } as any); +} diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 22c39ef9702..4a7ef4bc8f2 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const arMetadataForms: NonNullable = { label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "المفتاح", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "المجموعات", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "الحقول القابلة للبحث", helpText: "أسماء الحقول التي يطابقها استعلام $search ‏(ADR-0061): القيمة الافتراضية لمنتقي السجلات والبحث السريع في القوائم والبحث العام؛ ويمكن لطريقة العرض تضييقها. عند عدم تعيينها، يستخدم البحث حقل الاسم/العنوان إضافة إلى الحقول النصية القصيرة. يجب أن يسمّي كل إدخال حقلًا مخزَّنًا من هذا الكائن — ويُرفض عند النشر الاسم المجهول أو حقل الصيغة الافتراضي." diff --git a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts index 589663e6467..bb02c8c8d54 100644 --- a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts @@ -96,6 +96,10 @@ export const arGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.sections.refresh.label": "1b63ae2e002930a6", "metadataForms.object.fields.actionLayout.selection.helpText": "3647854e40367b07", "metadataForms.object.fields.actionLayout.selection.label": "68d28c84b59e72b3", + "metadataForms.object.fields.fieldTabs.groups.helpText": "0c98d15573eccade", + "metadataForms.object.fields.fieldTabs.helpText": "81a1a0076b489db7", + "metadataForms.object.fields.fieldTabs.key.helpText": "21ab5c572c405819", + "metadataForms.object.fields.fieldTabs.label": "5493ff02a20f00bd", "metadataForms.object.fields.pinOverview.helpText": "768f0157c04d4ee2", "metadataForms.object.fields.pinOverview.label": "901b14e51cd49243", "metadataForms.permission.fields.fields.helpText": "887a0bae04a950e2", diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 40fc193b477..c393a0301dc 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const deMetadataForms: NonNullable = { label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "Schlüssel", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "Gruppen", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "Durchsuchbare Felder", helpText: "Feldnamen, auf die die Abfrage $search passt (ADR-0061): der Standard für die Datensatzauswahl, die Schnellsuche der Liste und die globale Suche; eine Ansicht kann ihn einschränken. Nicht gesetzt, sucht die Suche im Namens-/Titelfeld und in kurzen Textfeldern. Jeder Eintrag muss ein gespeichertes Feld dieses Objekts benennen – ein unbekannter Name oder ein virtuelles Formelfeld wird bei der Veröffentlichung abgelehnt." diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts index 0b99263831e..3e76081d8de 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts @@ -133,6 +133,10 @@ export const deGeneratedSourceHashes: Readonly> = { "metadataForms.object.fields.actionLayout.selection.helpText": "3647854e40367b07", "metadataForms.object.fields.actionLayout.selection.label": "68d28c84b59e72b3", "metadataForms.object.fields.enable.feeds.label": "669c64671f632139", + "metadataForms.object.fields.fieldTabs.groups.helpText": "0c98d15573eccade", + "metadataForms.object.fields.fieldTabs.helpText": "81a1a0076b489db7", + "metadataForms.object.fields.fieldTabs.key.helpText": "21ab5c572c405819", + "metadataForms.object.fields.fieldTabs.label": "5493ff02a20f00bd", "metadataForms.object.fields.lifecycle.storage.shards.label": "739988affb36b2e0", "metadataForms.object.fields.name.label": "5274417ff1ccaf01", "metadataForms.object.fields.pinOverview.helpText": "768f0157c04d4ee2", diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 8203b00a766..e6ccad13467 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const enMetadataForms: NonNullable = { label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "Key", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "Groups", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "Searchable Fields", helpText: "Field names the $search query matches (ADR-0061): the default for the record picker, list quick-search and global search; a view may narrow it. Unset, search uses the name/title field plus short-text fields. Each entry must name a stored field of this object — an unknown name or a virtual formula field is refused at publish." diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index 6506a7dac2a..9927aad6541 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const esESMetadataForms: NonNullable = label: "Fijar resumen", helpText: "Si la página de registro de escritorio ancha fija el resumen (los campos propios del registro) en una columna izquierda junto a las demás pestañas. Sin definir: se fija como antes siempre que la página sea lo bastante ancha y tenga otras pestañas; un interruptor sin tocar no escribe nada, por lo que aparece desactivado mientras la página sigue fijada. Desactivado una vez definido: la página completa de escritorio nunca se fija, en ningún ancho, y el resumen es su primera pestaña, abierta por defecto, con los campos dispuestos según el ancho en hasta tres columnas, también cuando el resumen contiene una tabla relacionada. La vista previa lateral y un teléfono se ven igual en ambos casos." }, + fieldTabs: { + label: "Pestañas de campos", + helpText: "Grupos de campos que la página de registro estándar muestra como pestañas, justo después del resumen, en este orden, antes de las listas relacionadas. Cada pestaña nombra los grupos que muestra, en orden; el resumen conserva los grupos que ninguna pestaña nombra y los campos sin grupo. La pestaña toma su título e icono de su primer grupo. El formulario de entrada, las páginas de impresión y las páginas propias no cambian. Se rechazan un grupo nombrado dos veces, un grupo que Grupos de campos no declara y un grupo de lista relacionada." + }, + "fieldTabs.key": { + label: "Clave", + helpText: "Clave técnica en snake_case, única entre las pestañas de campos de este objeto; es la dirección de la pestaña en la página de registro (fields:clave)." + }, + "fieldTabs.groups": { + label: "Grupos", + helpText: "Las claves de los grupos de campos que muestra esta pestaña, en orden (al menos una). Un grupo que llena una lista relacionada se queda en el resumen y aquí se rechaza." + }, searchableFields: { label: "Campos buscables", helpText: "Nombres de campo con los que coincide la consulta $search (ADR-0061): el valor predeterminado del selector de registros, la búsqueda rápida de listas y la búsqueda global; una vista puede acotarlo. Sin definir, la búsqueda usa el campo de nombre/título más los campos de texto corto. Cada entrada debe nombrar un campo almacenado de este objeto: un nombre desconocido o un campo formula virtual se rechaza al publicar." diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index a96ecb208e4..86284881ec3 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const frMetadataForms: NonNullable = { label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "Clé", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "Groupes", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "Champs de recherche", helpText: "Noms des champs auxquels correspond la requête $search (ADR-0061) : la valeur par défaut pour le sélecteur d’enregistrements, la recherche rapide dans les listes et la recherche globale ; une vue peut la restreindre. Si elle n’est pas définie, la recherche utilise le champ de nom/titre ainsi que les champs de texte court. Chaque entrée doit désigner un champ stocké de cet objet — un nom inconnu ou un champ de formule virtuel est refusé à la publication." diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index 9e979940dd3..3f73a5b853d 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -154,6 +154,10 @@ export const frGeneratedSourceHashes: Readonly> = { "metadataForms.object.fields.actionLayout.selection.helpText": "3647854e40367b07", "metadataForms.object.fields.actionLayout.selection.label": "68d28c84b59e72b3", "metadataForms.object.fields.description.label": "779a4342c8eb6707", + "metadataForms.object.fields.fieldTabs.groups.helpText": "0c98d15573eccade", + "metadataForms.object.fields.fieldTabs.helpText": "81a1a0076b489db7", + "metadataForms.object.fields.fieldTabs.key.helpText": "21ab5c572c405819", + "metadataForms.object.fields.fieldTabs.label": "5493ff02a20f00bd", "metadataForms.object.fields.fields.description.label": "779a4342c8eb6707", "metadataForms.object.fields.fields.expression.label": "cd1b52ad1588075e", "metadataForms.object.fields.fields.max.label": "8081d808ef64ff91", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 22e1b607fe1..32c221bb231 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const jaJPMetadataForms: NonNullable = label: "概要を固定", helpText: "デスクトップの広いレコードページで、概要(レコード自身の項目)を左の列に固定し、他のタブをその横に並べるかどうか。未設定:ページが十分に広く他のタブがあれば、これまでどおり固定されます。触れていないスイッチは何も書き込まないため、オフと表示されていてもページは固定されたままです。一度オフに設定すると:デスクトップの全画面ページはどの幅でも固定されず、概要が最初のタブとして既定で開き、項目は幅に合わせて最大 3 列で並びます。概要に関連テーブルがある場合も同じです。サイドプレビューとスマートフォンはどちらでも同じ表示です。" }, + fieldTabs: { + label: "フィールドタブ", + helpText: "標準レコードページで、概要のすぐ後に、この順序で関連リストより前にタブとして表示するフィールドグループ。各タブは表示するグループを順番に指定します。概要には、どのタブにも指定されていないグループと、どのグループにも属さないフィールドが残ります。タブのタイトルとアイコンは最初のグループのものを使います。入力フォーム、印刷ページ、独自に作成したページは変わりません。2 回指定されたグループ、フィールドグループで宣言されていないグループ、関連リストのグループは拒否されます。" + }, + "fieldTabs.key": { + label: "キー", + helpText: "snake_case の機械キー。このオブジェクトのフィールドタブ内で一意で、レコードページ上のタブのアドレス(fields:キー)になります。" + }, + "fieldTabs.groups": { + label: "グループ", + helpText: "このタブが表示するフィールドグループのキーを順番に指定します(1 つ以上)。関連リストで埋まるグループは概要に残り、ここでは拒否されます。" + }, searchableFields: { label: "検索対象項目", helpText: "$search クエリが照合する項目名(ADR-0061)。レコードピッカー、一覧のクイック検索、グローバル検索の既定値で、ビューで絞り込めます。未設定の場合は名前/タイトル項目と短いテキスト項目で検索します。各項目はこのオブジェクトの保存済みの項目を指す必要があり、不明な名前や仮想の formula 項目は公開時に拒否されます。" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index ac02f952593..4f00e2598e6 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const koMetadataForms: NonNullable = { label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "키", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "그룹", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "검색 가능 필드", helpText: "$search 쿼리가 일치시키는 필드 이름입니다(ADR-0061). 레코드 선택기, 목록 빠른 검색, 전역 검색의 기본값이며 뷰에서 좁힐 수 있습니다. 설정하지 않으면 이름/제목 필드와 짧은 텍스트 필드로 검색합니다. 각 항목은 이 객체의 저장된 필드를 지정해야 하며, 알 수 없는 이름이나 가상 수식 필드는 게시할 때 거부됩니다." diff --git a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts index 3c060cfb5a3..1fc0cb999be 100644 --- a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts @@ -96,6 +96,10 @@ export const koGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.sections.refresh.label": "1b63ae2e002930a6", "metadataForms.object.fields.actionLayout.selection.helpText": "3647854e40367b07", "metadataForms.object.fields.actionLayout.selection.label": "68d28c84b59e72b3", + "metadataForms.object.fields.fieldTabs.groups.helpText": "0c98d15573eccade", + "metadataForms.object.fields.fieldTabs.helpText": "81a1a0076b489db7", + "metadataForms.object.fields.fieldTabs.key.helpText": "21ab5c572c405819", + "metadataForms.object.fields.fieldTabs.label": "5493ff02a20f00bd", "metadataForms.object.fields.pinOverview.helpText": "768f0157c04d4ee2", "metadataForms.object.fields.pinOverview.label": "901b14e51cd49243", "metadataForms.permission.fields.fields.helpText": "887a0bae04a950e2", diff --git a/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts index 0fa2c4c8a9a..91316f25fe9 100644 --- a/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts @@ -1025,7 +1025,11 @@ describe('#19403 round 8 — the population, DERIVED from the form and a shape', // 134 since #37792 gave `basics` the `pinOverview` row (the record page // layout switch) — label and help text, authored in every translated // locale, so `openEchoes` stays at zero. - expect(OPEN_LEAVES.length).toBe(134); + // 140 since #37802 gave `basics` the `fieldTabs` repeater (the record + // page's field tabs) — the row and its `key` and `groups` sub-rows, six + // leaves (three labels, three help texts), authored in every translated + // locale, so `openEchoes` stays at zero. + expect(OPEN_LEAVES.length).toBe(140); expect(PANEL_LEAVES.some((l) => l.path === 'fields.placeholder')).toBe(false); expect(OPEN_LEAVES.some((l) => l.path === 'fields.placeholder')).toBe(true); for (const path of ['name', 'label', 'fields', 'fields.valueDomain', 'fields.deleteBehavior', 'fields.expression']) { diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index 49194ba2957..b7d17ace88e 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1366,9 +1366,12 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // 872 since #38692: the `knowledge_source` form's `source.retrieval` // group and its `mode` row (the retrieval mode) — two row labels, // authored in every locale. - // 873 since ADR-0162 D1: the object form's `closedStates` row (the + // 875 since #37802: the object form's `fieldTabs` repeater (the record + // page's field tabs) — the row and its `key` and `groups` sub-rows, + // three labels, authored in all three locales. + // 876 since ADR-0162 D1: the object form's `closedStates` row (the // states that close a record), authored in every locale. - expect(translated.length, `${locale} positive control`).toBe(873); + expect(translated.length, `${locale} positive control`).toBe(876); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index 5799f66badb..800dbcd16fe 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const ptBRMetadataForms: NonNullable = label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "Chave", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "Grupos", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "Campos pesquisáveis", helpText: "Nomes de campos que a consulta $search compara (ADR-0061): o padrão para o seletor de registros, a busca rápida da lista e a busca global; uma visualização pode restringi-lo. Quando não definido, a busca usa o campo de nome/título mais os campos de texto curto. Cada entrada deve nomear um campo armazenado deste objeto — um nome desconhecido ou um campo de fórmula virtual é recusado na publicação." diff --git a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts index f8e7135ce8c..51b6c9b7c94 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts @@ -109,6 +109,10 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "metadataForms.object.fields.actionLayout.selection.helpText": "3647854e40367b07", "metadataForms.object.fields.actionLayout.selection.label": "68d28c84b59e72b3", "metadataForms.object.fields.enable.feeds.label": "669c64671f632139", + "metadataForms.object.fields.fieldTabs.groups.helpText": "0c98d15573eccade", + "metadataForms.object.fields.fieldTabs.helpText": "81a1a0076b489db7", + "metadataForms.object.fields.fieldTabs.key.helpText": "21ab5c572c405819", + "metadataForms.object.fields.fieldTabs.label": "5493ff02a20f00bd", "metadataForms.object.fields.lifecycle.storage.shards.label": "739988affb36b2e0", "metadataForms.object.fields.pinOverview.helpText": "768f0157c04d4ee2", "metadataForms.object.fields.pinOverview.label": "901b14e51cd49243", diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index a0f886fa8dc..a100b0a30d4 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const ruMetadataForms: NonNullable = { label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "Ключ", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "Группы", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "Поля поиска", helpText: "Имена полей, по которым ищет запрос $search (ADR-0061): значение по умолчанию для выбора записей, быстрого поиска в списке и глобального поиска; представление может его сузить. Если не задано, поиск использует поле названия/заголовка и короткие текстовые поля. Каждая запись должна указывать хранимое поле этого объекта — неизвестное имя или виртуальное поле формулы отклоняется при публикации." diff --git a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts index f270a7b9ac9..94dc7169b72 100644 --- a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts @@ -96,6 +96,10 @@ export const ruGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.sections.refresh.label": "1b63ae2e002930a6", "metadataForms.object.fields.actionLayout.selection.helpText": "3647854e40367b07", "metadataForms.object.fields.actionLayout.selection.label": "68d28c84b59e72b3", + "metadataForms.object.fields.fieldTabs.groups.helpText": "0c98d15573eccade", + "metadataForms.object.fields.fieldTabs.helpText": "81a1a0076b489db7", + "metadataForms.object.fields.fieldTabs.key.helpText": "21ab5c572c405819", + "metadataForms.object.fields.fieldTabs.label": "5493ff02a20f00bd", "metadataForms.object.fields.pinOverview.helpText": "768f0157c04d4ee2", "metadataForms.object.fields.pinOverview.label": "901b14e51cd49243", "metadataForms.permission.fields.fields.helpText": "887a0bae04a950e2", diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index a1780f6e490..9697e502a00 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const zhCNMetadataForms: NonNullable = label: "固定概览", helpText: "桌面宽屏记录页是否把概览(记录自己的字段)固定在左栏、其他页签排在旁边。未设置:只要页面够宽且有其他页签,就照旧固定;没动过的开关不写任何值,所以它显示为关闭,页面却仍然固定。设置为关闭后:桌面整页在任何宽度下都不再固定,概览是第一个页签并默认打开,字段按页面宽度最多排三列,概览里有子表时也一样。侧边预览和手机无论设不设都一样。" }, + fieldTabs: { + label: "字段页签", + helpText: "在标准记录页上作为页签绘制的字段分组,紧跟在概览之后,按此顺序排在相关列表之前。每个页签列出它绘制的分组及顺序;概览保留没有页签认领的分组和不属于任何分组的字段。页签的标题和图标取自它的第一个分组。录入表单、打印页和自定义页面不受影响。同一分组被命名两次、字段分组里没有声明的分组,以及相关列表分组,都会被拒绝。" + }, + "fieldTabs.key": { + label: "键", + helpText: "snake_case 格式的机器键,在本对象的字段页签中唯一;也是该页签在记录页上的地址(fields:键)。" + }, + "fieldTabs.groups": { + label: "分组", + helpText: "此页签绘制的字段分组键,按顺序排列(至少一个)。由相关列表填充的分组留在概览中,在这里会被拒绝。" + }, searchableFields: { label: "可搜索字段", helpText: "$search 查询匹配的字段名(ADR-0061):记录选择器、列表快速搜索和全局搜索的默认范围,视图可以再收窄。未设置时,搜索使用名称/标题字段加上短文本字段。每一项都必须是本对象已存储的字段——未知的名称或虚拟的 formula 字段会在发布时被拒绝。" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index aebeef34c5f..734f298cdc0 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const zhHantMetadataForms: NonNullable label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "鍵", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "分組", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "可搜尋欄位", helpText: "$search 查詢比對的欄位名(ADR-0061):記錄選擇器、清單快速搜尋和全域搜尋的預設範圍,檢視可以再收窄。未設定時,搜尋使用名稱/標題欄位加上短文字欄位。每一項都必須是本物件已儲存的欄位——未知的名稱或虛擬的 formula 欄位會在發布時被拒絕。" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts index 356460549be..55d55f4e207 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts @@ -94,6 +94,10 @@ export const zhHantGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.sections.refresh.label": "1b63ae2e002930a6", "metadataForms.object.fields.actionLayout.selection.helpText": "3647854e40367b07", "metadataForms.object.fields.actionLayout.selection.label": "68d28c84b59e72b3", + "metadataForms.object.fields.fieldTabs.groups.helpText": "0c98d15573eccade", + "metadataForms.object.fields.fieldTabs.helpText": "81a1a0076b489db7", + "metadataForms.object.fields.fieldTabs.key.helpText": "21ab5c572c405819", + "metadataForms.object.fields.fieldTabs.label": "5493ff02a20f00bd", "metadataForms.object.fields.pinOverview.helpText": "768f0157c04d4ee2", "metadataForms.object.fields.pinOverview.label": "901b14e51cd49243", "metadataForms.report.fields.dateRange.allowCustomRange.helpText": "eb95a6b1536e22fd", diff --git a/packages/plugins/knowledge-pgvector/README.md b/packages/plugins/knowledge-pgvector/README.md index f84798730c2..d7fb0af98d1 100644 --- a/packages/plugins/knowledge-pgvector/README.md +++ b/packages/plugins/knowledge-pgvector/README.md @@ -59,8 +59,10 @@ The next call retries; no restart is needed. A database the plugin cannot reach Two legs in one statement (one snapshot), merged by reciprocal rank fusion (RRF, `k` = 60) before the knowledge service re-checks each hit as the caller. Each leg ranks at most `topK` passages; a hit's `score` is the sum of `1 / (60 + rank)` over the legs that rank it, divided by that of a passage first in both, so it lies in `(0, 1]`: 1 for first in both legs, 0.5 for first in one alone. The organization filter, the record scope and the metadata `filter` are one `WHERE`, run in both legs before either ranks. +**Retrieval modes.** The store reports all three modes (`capabilities.retrieval`: `vector`, `keyword`, `hybrid`), `hybrid` by default, and a source chooses with `source.retrieval.mode`. `hybrid` runs both legs as above. `vector` runs the vector leg alone and `keyword` the keyword leg alone: the other leg is not written into the statement, and a hit's `score` is `61 / (60 + rank)`, 1 for the first. `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. The keyword index is kept whatever the mode, so changing the mode rebuilds nothing. + - **Keyword leg.** The query is split into terms at white space and punctuation; a hyphen, dot, slash, underscore, `#`, `@` or `+` inside a term keeps it whole, so `X-200` is one term (at most 16 terms). A run of Han, kana or Hangul inside a term is cut into overlapping pieces of three characters and of two (a run of two is one piece, a run of one is dropped), so a question written without spaces is still matched word by word; a figure or a code next to a run (`2000`, `X-200`) stays one term. Under the cap the figures, codes and words come first, then the pieces of three characters, then those of two. A word of three characters or more is matched as a phrase (`phraseto_tsquery('simple', …)`) on the passage's `to_tsvector('simple', content)`, which a GIN expression index (`knowledge_vec_d_content_tsv`) serves. The `simple` configuration lower-cases and neither stems nor drops stop words, so a code or a name matches as written. A shorter term (「出差」), and a term holding a Han, kana or Hangul character — which the parser never splits, so a `tsvector` holds a whole run of them as one word — is matched as a substring over the rows in scope: by `content LIKE '%…%'` when the term holds no cased letter (a piece of Han, kana or Hangul, a figure), where case folding could find nothing more, and by `content ILIKE '%…%'` otherwise. A passage's keyword score sums, over the terms it holds, the term's BM25 inverse document frequency among the rows in scope, so a word most passages hold weighs little. -- **Keyword index.** An expression index: no column is added and no row rewritten, and PostgreSQL keeps it in step with every write. It is made with the passage table; a table made by a release without one gets it from the first write or search of that width (`CREATE INDEX IF NOT EXISTS`, which blocks writes to the table while it builds). +- **Keyword index.** An expression index: no column is added and no row rewritten, and PostgreSQL keeps it in step with every write. It is made with the passage table; a table made by a release without one gets it from the first write of that width, or the first search of that width with keyword terms (never under `vector`) (`CREATE INDEX IF NOT EXISTS`, which blocks writes to the table while it builds). - **Vector leg.** An exact cosine scan; a passage whose cosine similarity is not positive is not ranked by it. ## Pool size and time limit diff --git a/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs b/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs index eb5d5fa7386..80abe4b8f85 100644 --- a/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs +++ b/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs @@ -203,14 +203,19 @@ describe('bench instrument — segment seams over the real adapter and service', expect(extractRankingWhere('WITH cand AS (SELECT chunk_id, 0 AS distance FROM t WHERE x)', ['a', 1, 5])).toBeUndefined(); }); - it('a failed embed is counted, and the search answers no hit with the service\'s "search failed" line', async () => { + it('a failed embed is counted, and the search is refused SERVICE_UNAVAILABLE naming the source, with the service\'s "search failed" line', async () => { const { search, errors } = setup({ failEmbed: true }); const outcome = await search({ query: 'leave policy', topK: TOP_K }, CALLER); const s = summarizeRecord(outcome); expect(s.embedFailures).toBe(1); expect(s.calls.ranking).toBe(0); - expect(s.ok).toBe(true); - expect(s.hits).toBe(0); + expect(s.ok).toBe(false); + expect(s.errorCode).toBe('SERVICE_UNAVAILABLE'); + expect(outcome.error).toMatchObject({ + code: 'SERVICE_UNAVAILABLE', + status: 503, + refused: [expect.objectContaining({ sourceId: 'clauses', code: 'SERVICE_UNAVAILABLE', status: 503 })], + }); expect(errors.filter((m) => /search failed/.test(m))).toHaveLength(1); }); }); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts index 4a8be8ed477..c48d725e9cf 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts @@ -30,6 +30,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => { scope: true, dropSource: true, keywordLeg: true, + retrieval: true, }, }); }); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts new file mode 100644 index 00000000000..e93c41181b2 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts @@ -0,0 +1,145 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The retrieval modes (ADR-0161, the dated note of 2026-11-30 under K8), without + * a database: the capability report, the legs each mode writes into the + * ranking statement, that `keyword` never calls the embedder, and the + * fusion's scores — `hybrid` bit-identical to the fusion before modes + * existed, one leg `61 / (60 + rank)`. The behaviour against a real + * PostgreSQL is the contract suite's (`contract.live-postgres.test.ts`). + */ + +import { describe, expect, it } from 'vitest'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import { PgvectorKnowledgeAdapter, type PgClientLike, type PgPoolLike } from '../index.js'; +import { RETRIEVAL, RRF_K, fuse } from '../pgvector-adapter.js'; +import { FakeEmbedder } from './live-pg.testkit.js'; + +const source = { name: 'modes', label: 'modes', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['b'] } } as KnowledgeSource; + +/** A store with one active generation whose ranking statement is recorded and answers nothing. */ +function recordingPool(): { pool: PgPoolLike; rankings: string[]; statements: string[] } { + const rankings: string[] = []; + const statements: string[] = []; + const answer = async (text: string): Promise<{ rows: R[] }> => { + statements.push(text); + if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.0' }] as R[] }; + if (text.includes('to_regclass')) return { rows: [{ present: 'x' }] as R[] }; + if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) { + return { rows: [{ generation: 1, fingerprint: 'fp', recipe_hash: 'rh', dim: 384, state: 'active' }] as R[] }; + } + if (text.includes('GROUP BY chunk_id')) rankings.push(text); + return { rows: [] as R[] }; + }; + const client = (): PgClientLike => ({ query: answer, release: () => undefined }); + return { pool: { query: answer, connect: async () => client() }, rankings, statements }; +} + +async function searched(mode: 'vector' | 'keyword' | 'hybrid' | undefined, query = 'granite quarry') { + return searchedRaw(mode, query); +} + +async function searchedRaw(mode: string | undefined, query = 'granite quarry') { + const store = recordingPool(); + const embedder = new FakeEmbedder(); + const adapter = new PgvectorKnowledgeAdapter({ pool: store.pool, embedder }); + const hits = await adapter.search(query, { + source, + topK: 5, + index: { fingerprint: 'fp' }, + ...(mode === undefined ? {} : { retrieval: { mode: mode as 'hybrid' } }), + }); + return { hits, embedder, rankings: store.rankings, statements: store.statements }; +} + +describe('knowledge-pgvector retrieval modes', () => { + it('reports all three modes, hybrid by default', () => { + const adapter = new PgvectorKnowledgeAdapter({ pool: recordingPool().pool, embedder: new FakeEmbedder() }); + expect(adapter.capabilities.retrieval).toBe(RETRIEVAL); + expect(RETRIEVAL).toEqual({ modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' }); + }); + + it('hybrid, and no mode, write both legs into the statement', async () => { + for (const mode of ['hybrid', undefined] as const) { + const { rankings, embedder } = await searched(mode); + expect(rankings).toHaveLength(1); + expect(rankings[0]).toContain('vec AS ('); + expect(rankings[0]).toContain('kw AS ('); + expect(embedder.calls).toBe(1); + } + }); + + it('vector writes the vector leg alone', async () => { + const { rankings, embedder } = await searched('vector'); + expect(rankings).toHaveLength(1); + expect(rankings[0]).toContain('vec AS ('); + expect(rankings[0]).not.toContain('kw AS ('); + expect(embedder.calls).toBe(1); + }); + + it('vector writes no keyword condition into any statement, not just none into the fusion', async () => { + // Measured on PG17 + pgvector 0.8.7 over 59,949 clauses: the keyword terms (sixteen + // LIKEs over every row in scope) were most of a hybrid statement's cost. + const hybrid = await searched('hybrid', 'granite quarry w3x 出差'); + expect(hybrid.rankings[0]).toMatch(/\bI?LIKE\b/); + const { statements } = await searched('vector', 'granite quarry w3x 出差'); + expect(statements.length).toBeGreaterThan(0); + for (const text of statements) { + expect(text).not.toMatch(/\bI?LIKE\b/); + expect(text).not.toMatch(/tsquery|@@/); + } + }); + + it('keyword writes the keyword leg alone and never calls the embedder', async () => { + const { rankings, embedder } = await searched('keyword'); + expect(rankings).toHaveLength(1); + expect(rankings[0]).not.toContain('vec AS ('); + expect(rankings[0]).toContain('kw AS ('); + // Equal keyword scores fall to the chunk id: the candidates carry no distance. + expect(rankings[0]).toContain('0 AS distance'); + expect(embedder.calls).toBe(0); + }); + + it('a mode it does not list is refused before anything is embedded or ranked', async () => { + const refused = await searchedRaw('rerank').catch((e: unknown) => e); + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(String((refused as Error).message)).toContain("does not run the retrieval mode 'rerank'"); + }); + + it('keyword with no term to match answers nothing and reads no passage', async () => { + const { hits, rankings, embedder } = await searched('keyword', ' '); + expect(hits).toEqual([]); + expect(rankings).toHaveLength(0); + expect(embedder.calls).toBe(0); + }); +}); + +describe('knowledge-pgvector fusion under the retrieval modes', () => { + type Row = { chunk_id: string; vpos: number | null; kpos: number | null }; + + /** The fusion's score as it stood before retrieval modes existed: the hybrid pin's reference. */ + const before = (row: Row): number => { + const best = 2 / (RRF_K + 1); + const leg = (pos: number | null) => (pos === null ? 0 : 1 / (RRF_K + Number(pos))); + return (leg(row.vpos) + leg(row.kpos)) / best; + }; + + it('hybrid is bit-identical to the fusion before modes, for every pair of ranks up to 200', () => { + const ranks: Array = [null, ...Array.from({ length: 200 }, (_, i) => i + 1)]; + const rows: Row[] = []; + for (const vpos of ranks) for (const kpos of ranks) if (vpos !== null || kpos !== null) rows.push({ chunk_id: `${vpos}:${kpos}`, vpos, kpos }); + const fused = fuse(rows, rows.length, 2); + expect(fused).toHaveLength(rows.length); + let differing = 0; + for (const { row, score } of fused) if (!Object.is(score, before(row))) differing += 1; + expect(differing).toBe(0); + }); + + it('one leg scores 61 / (60 + rank): the first is 1, and scores fall with rank', () => { + const rows: Row[] = Array.from({ length: 50 }, (_, i) => ({ chunk_id: `c${String(i + 1).padStart(3, '0')}`, vpos: i + 1, kpos: null })); + const fused = fuse(rows, 50, 1); + expect(fused[0]?.score).toBe(1); + for (const { row, score } of fused) expect(score).toBeCloseTo(61 / (60 + Number(row.vpos)), 12); + for (let i = 1; i < fused.length; i++) expect(fused[i - 1]!.score).toBeGreaterThan(fused[i]!.score); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index 6fe750f9cf7..ef41a406c9d 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -136,6 +136,17 @@ const CONCURRENT_MODIFICATION = 'CONCURRENT_MODIFICATION'; /** The `k` of reciprocal rank fusion: a passage at rank `r` of a leg adds `1 / (k + r)` to its score. */ export const RRF_K = 60; +/** + * The retrieval modes this adapter runs, and its default (ADR-0161, the dated + * note of 2026-11-30 under K8): all three, `hybrid` when a source declares none. + * A report, not configuration; the default does not move with what the + * database offers. + */ +export const RETRIEVAL = Object.freeze({ + modes: Object.freeze(['vector', 'keyword', 'hybrid'] as const), + default: 'hybrid' as const, +}); + /** The default of {@link PgvectorKnowledgeAdapterOptions.statementTimeoutMs}, in milliseconds. */ export const DEFAULT_STATEMENT_TIMEOUT_MS = 10_000; @@ -192,8 +203,17 @@ interface Readiness { * Two legs, merged by reciprocal rank fusion (`k` = {@link RRF_K}) before the * knowledge service re-checks each hit as the caller. Each leg ranks at most * `topK` passages; a passage's score is the sum of `1 / (k + rank)` over the - * legs that rank it, divided by the score of a passage first in both, so it - * lies in `(0, 1]`. Both legs run in one statement, so in one snapshot. + * legs that rank it, divided by the score of a passage first in every leg + * that runs, so it lies in `(0, 1]`. Both legs run in one statement, so in one + * snapshot. + * + * The search's retrieval mode (`AdapterSearchOptions.retrieval`, {@link + * RETRIEVAL}) names the legs that run: `hybrid` (the default) both, `vector` + * the vector leg alone, `keyword` the keyword leg alone — the leg left out is + * not written into the statement. Under one leg a passage's score is + * `61 / (60 + rank)`, so the first is 1. `keyword` does not embed the query: + * the keyword leg's passages of equal score are ranked by chunk id, and a + * query with no terms answers nothing. * * - The vector leg: an exact scan by cosine distance — no approximate index, * so a 3072-wide model works (pgvector's HNSW index stops at 2000 @@ -292,7 +312,7 @@ interface Readiness { */ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { readonly id: string; - readonly capabilities = { chunks: true } as const; + readonly capabilities = { chunks: true, retrieval: RETRIEVAL } as const; private readonly pool?: PgPoolLike; private readonly unavailable?: string; private readonly resolveEmbedder: () => IEmbedder | undefined; @@ -617,16 +637,34 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { const topK = Math.max(0, Math.floor(opts.topK)); if (topK === 0) return []; - // The query is embedded before a connection is taken. - const [vector] = await embedder.embed([`${this.queryPrefix}${query}`]); - if (!Array.isArray(vector) || vector.length !== generation.dim) { - throw new Error( - `knowledge-pgvector: the embedder answered a ${Array.isArray(vector) ? vector.length : 'missing'}-wide query ` + - `vector, and this source's index holds ${generation.dim}-wide vectors.`, + // The legs the search's mode runs (ADR-0161, the dated note of 2026-11-30 + // under K8); the service hands only a mode this adapter lists, and any + // other is refused, never run on a scale it was not built for. + const mode = opts.retrieval?.mode ?? RETRIEVAL.default; + if (!(RETRIEVAL.modes as readonly string[]).includes(mode)) { + throw Object.assign( + new Error( + `knowledge-pgvector does not run the retrieval mode '${String(mode)}': it runs ` + + `${RETRIEVAL.modes.map((m) => `'${m}'`).join(', ')}.`, + ), + { code: 'VALIDATION_ERROR', status: 400 }, ); } - const vectorLeg = !vector.every((x) => x === 0); - const terms = keywordTerms(query); + // The query is embedded before a connection is taken — never under + // `keyword`, which makes no query vector. + let vector: number[] = []; + if (mode !== 'keyword') { + const [embedded] = await embedder.embed([`${this.queryPrefix}${query}`]); + if (!Array.isArray(embedded) || embedded.length !== generation.dim) { + throw new Error( + `knowledge-pgvector: the embedder answered a ${Array.isArray(embedded) ? embedded.length : 'missing'}-wide query ` + + `vector, and this source's index holds ${generation.dim}-wide vectors.`, + ); + } + vector = embedded; + } + const vectorLeg = mode !== 'keyword' && !vector.every((x) => x === 0); + const terms = mode === 'vector' ? [] : keywordTerms(query); if (!vectorLeg && terms.length === 0) return []; if (terms.length > 0) await this.ensureKeywordIndex(generation.dim); @@ -768,7 +806,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { const now = await this.generations(opts.source.name); if (now.active?.generation !== generation.generation) return undefined; } - return fuse(result.rows, topK).map(({ row: r, score }) => ({ + return fuse(result.rows, topK, mode === 'hybrid' ? 2 : 1).map(({ row: r, score }) => ({ chunkId: r.chunk_id, documentId: r.document_id, sourceId: opts.source.name, @@ -1474,16 +1512,19 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { } /** - * Reciprocal rank fusion of the two legs' rows (`vpos`, `kpos`: a row's rank - * in each leg, or null): best first, at most `topK`; a tie goes to the better + * Reciprocal rank fusion of the legs' rows (`vpos`, `kpos`: a row's rank in + * each leg, or null): best first, at most `topK`; a tie goes to the better * vector rank, then to the chunk id. The score is the fused sum divided by - * that of a row first in both legs. + * that of a row first in each of the `legs` the search's mode runs: under + * `hybrid` (two) exactly as before modes existed, under one leg + * `61 / (60 + rank)`. Exported for its pin test, not from the package entry. */ -function fuse( +export function fuse( rows: readonly R[], topK: number, + legs: 1 | 2, ): Array<{ row: R; score: number }> { - const best = 2 / (RRF_K + 1); + const best = legs / (RRF_K + 1); const leg = (pos: string | number | null) => (pos === null ? 0 : 1 / (RRF_K + Number(pos))); const vectorRank = (row: R) => (row.vpos === null ? Infinity : Number(row.vpos)); return rows diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index 0bf9eb8ed3d..b4ad4260c1b 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -51,8 +51,10 @@ On a file the store sets WAL and a busy timeout: without them a second process w Two legs, merged by reciprocal rank fusion (RRF, `k` = 60) before the knowledge service re-checks each hit as the caller. Each leg ranks at most `topK` passages; a hit's `score` is the sum of `1 / (60 + rank)` over the legs that rank it, divided by that of a passage first in both, so it lies in `(0, 1]`: 1 for first in both legs, 0.5 for first in one alone. +**Retrieval modes.** The store reports all three modes (`capabilities.retrieval`: `vector`, `keyword`, `hybrid`), `hybrid` by default, and a source chooses with `source.retrieval.mode`. `hybrid` runs both legs as above. `vector` runs the vector leg alone and `keyword` the keyword leg alone: the other leg is not written into any statement, and a hit's `score` is `61 / (60 + rank)`, 1 for the first. `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. The keyword index is kept whatever the mode, so changing the mode rebuilds nothing. + - **Keyword leg.** The query is split into terms at white space and punctuation; a hyphen, dot, slash, underscore, `#`, `@` or `+` inside a term keeps it whole, so `X-200` and `v1.2` are one term each (at most 16 terms). A run of Han, kana or Hangul inside a term is cut into overlapping pieces of three characters and of two (a run of two is one piece, a run of one is dropped), so a question written without spaces is still matched word by word; a figure or a code next to a run (`2000`, `X-200`) stays one term. Under the cap the figures, codes and words come first, then the pieces of three characters, then those of two. A term of three characters or more is matched as one quoted FTS5 phrase in the passage table's trigram index — so `X-200` is text, never FTS5 syntax, and 「住宿标准」 matches inside 「员工出差住宿标准」. A shorter term, which a trigram index cannot match (「出差」), is matched by `content LIKE '%…%'` over the rows in scope. A passage's keyword score sums, over the terms it holds, the term's BM25 inverse document frequency among the rows in scope, so a word most passages hold weighs little. There is no dictionary segmentation: the pieces find a code, a name or a phrase as written, and the vector leg answers the question's meaning. -- **Keyword index.** Each passage table `knowledge__g` has one beside it: a map table `…-kw`, a contentless FTS5 table `…-fts` (`tokenize='trigram'`) and three triggers that keep both in step with every insert, rewrite and removal of a passage, inside the statement that writes it. It is made with the table and dropped with it. A table made by a release without one gets it at its first search, built from the rows it holds in one transaction; until then nothing else changes. Its names hold a hyphen, which no source, generation or object name can, and an object under one of them that the store did not make is never dropped or used: the generation is refused `SERVICE_UNAVAILABLE`, naming it. +- **Keyword index.** Each passage table `knowledge__g` has one beside it: a map table `…-kw`, a contentless FTS5 table `…-fts` (`tokenize='trigram'`) and three triggers that keep both in step with every insert, rewrite and removal of a passage, inside the statement that writes it. It is made with the table and dropped with it. A table made by a release without one gets it at its first search that has keyword terms (never under `vector`), built from the rows it holds in one transaction; until then nothing else changes. Its names hold a hyphen, which no source, generation or object name can, and an object under one of them that the store did not make is never dropped or used: the generation is refused `SERVICE_UNAVAILABLE`, naming it. - **Vector leg.** Passages ranked by the cosine distance of their stored vector (`vector_distance_cos`); a passage whose cosine similarity is not positive is not ranked by it. Its ranks 1…`topK` feed the fusion, whichever of the two ways below found the passages. The organization filter, the record scope (a passage's record, or a metadata value equal to an id as text, a list matching by any element) and the metadata `filter` (JSON equality per key) are one `WHERE`, run in both legs. A search with a record scope or a metadata `filter` reads that `WHERE` once per statement, into a set of the passages in scope, and both legs and the keyword leg's counts read the passages in scope from that set by their key: a metadata term reads each passage's JSON, a pass over the table, which would otherwise be paid once by each leg and once more by the keyword counts. Measured on 59,621 one-passage records of 1,024 dimensions (one organization, `topK` 40, a Chinese question of 16 terms): a search scoped to 3 policies' clauses (90 passages) took about 1.0 s a statement before and 80 ms after, one scoped to a unit holding 10% of them 1.0 to 1.4 s before and 250 to 450 ms after. The keyword leg's candidates are read once a statement, not once for its counts and once for its ranks. And the keyword leg is computed once a search: when the approximate pass falls short and a wider pass or the exact scan follows, that statement binds the keyword ranks the first one answered. diff --git a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts index 903aba6ac35..0862fcbce35 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts @@ -28,6 +28,7 @@ for (const kind of ['memory', 'file'] as const) { scope: true, dropSource: true, keywordLeg: true, + retrieval: true, }, }); }); diff --git a/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts b/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts new file mode 100644 index 00000000000..ceddeea0b42 --- /dev/null +++ b/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts @@ -0,0 +1,180 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The retrieval modes (ADR-0161, the dated note of 2026-11-30 under K8) on + * libSQL: the capability report, the legs each mode writes into the ranking + * statement, that `keyword` never calls the embedder nor reads the + * approximate index, and the fusion's scores — `hybrid` bit-identical to the + * fusion before modes existed, one leg `61 / (60 + rank)`. What each mode + * answers is also the contract suite's (`contract.test.ts`). + */ + +import { afterAll, describe, expect, it } from 'vitest'; +import type { Client } from '@libsql/client'; +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; +import type { AdapterContext } from '@objectstack/spec/contracts'; +import { TursoKnowledgeAdapter } from '../index.js'; +import { RETRIEVAL, RRF_K, fuse } from '../turso-adapter.js'; +import { FakeEmbedder, storeOf } from './turso.testkit.js'; + +const source = (id: string): KnowledgeSource => + ({ name: id, label: id, adapter: 'under_test', source: { kind: 'object', object: 'article', content: ['body'] } }) as KnowledgeSource; +const FP = { fingerprint: 'fp-test:modes', recipeHash: 'rh-test:1' }; +const ctx = (s: KnowledgeSource): AdapterContext => ({ source: s, reason: 'manual', index: FP }); +const doc = (s: KnowledgeSource, n: string, content: string): KnowledgeDocument => { + const id = `${s.name}:${n}`; + return { id, sourceId: s.name, sourceRecordId: n, content, metadata: {}, chunks: [{ id: `${id}#0`, documentId: id, index: 0, content }] }; +}; + +/** A client whose every executed statement's SQL is recorded. */ +function recording(client: Client): { client: Client; sql: string[] } { + const sql: string[] = []; + const watched = new Proxy(client, { + get(t, key) { + const value = Reflect.get(t, key, t) as unknown; + if (typeof value !== 'function') return value; + const fn = (value as (...a: unknown[]) => unknown).bind(t); + if (key === 'execute') { + return (statement: unknown, ...rest: unknown[]) => { + sql.push(typeof statement === 'string' ? statement : String((statement as { sql: unknown }).sql)); + return fn(statement, ...rest); + }; + } + return fn; + }, + }); + return { client: watched, sql }; +} + +/** The ranking statements recorded since `from`: those that merge the legs. */ +const rankings = (sql: string[], from: number) => sql.slice(from).filter((s) => s.includes('GROUP BY chunk_id')); + +describe('knowledge-turso retrieval modes', () => { + const store = storeOf('memory'); + afterAll(() => store.closeAll()); + + async function seeded(opts: { vectorIndexThreshold?: number } = {}) { + const s = source(`modes_${Math.random().toString(36).slice(2, 8)}`); + const watched = recording(store.client()); + const embedder = new FakeEmbedder(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: watched.client, embedder, ...opts }); + const docs = Array.from({ length: 50 }, (_, i) => doc(s, String(i).padStart(3, '0'), `granite quarry stone ${i} w${i % 7}x`)); + await adapter.beginBuild(ctx(s)); + await adapter.upsert(docs, ctx(s)); + await adapter.completeBuild(ctx(s)); + return { s, adapter, embedder, sql: watched.sql }; + } + + it('reports all three modes, hybrid by default', () => { + const adapter = store.adapter(); + expect(adapter.capabilities.retrieval).toBe(RETRIEVAL); + expect(RETRIEVAL).toEqual({ modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' }); + }); + + it('hybrid writes both legs, and answers exactly what no mode answers', async () => { + const { s, adapter, embedder, sql } = await seeded(); + const from = sql.length; + const calls = embedder.calls; + const hybrid = await adapter.search('granite w3x', { source: s, topK: 5, retrieval: { mode: 'hybrid' }, index: FP }); + const ranked = rankings(sql, from); + expect(ranked).toHaveLength(1); + expect(ranked[0]).toContain('vec AS ('); + expect(ranked[0]).toContain('kw AS'); + // The control for the vector case below: hybrid does write the keyword terms. + expect(ranked[0]).toMatch(/\bMATCH\b/); + expect(embedder.calls).toBe(calls + 1); + expect(hybrid).toEqual(await adapter.search('granite w3x', { source: s, topK: 5, index: FP })); + }); + + it('vector writes the vector leg alone; the first hit scores 1', async () => { + const { s, adapter, sql } = await seeded(); + const from = sql.length; + const hits = await adapter.search('granite w3x', { source: s, topK: 5, retrieval: { mode: 'vector' }, index: FP }); + const ranked = rankings(sql, from); + expect(ranked).toHaveLength(1); + expect(ranked[0]).toContain('vec AS ('); + expect(ranked[0]).not.toContain('kw AS'); + // No keyword condition is written at all, not just left out of the fusion: on a + // large table the keyword terms (LIKE, or the FTS5 match) are most of a search's cost. + const written = sql.slice(from); + expect(written.length).toBeGreaterThan(0); + for (const q of written) { + expect(q).not.toMatch(/\bLIKE\b/i); + expect(q).not.toMatch(/\bMATCH\b/); + expect(q).not.toContain('-fts'); + } + expect(hits[0]?.score).toBe(1); + }); + + it('keyword writes the keyword leg alone, never calls the embedder, and ranks equal scores by chunk id', async () => { + const { s, adapter, embedder, sql } = await seeded(); + const from = sql.length; + const calls = embedder.calls; + const hits = await adapter.search('granite', { source: s, topK: 5, retrieval: { mode: 'keyword' }, index: FP }); + const ranked = rankings(sql, from); + expect(ranked).toHaveLength(1); + expect(ranked[0]).not.toContain('vec AS ('); + expect(ranked[0]).toContain('kw AS'); + expect(embedder.calls).toBe(calls); + // Every passage holds the one term equally: chunk id order, first scoring 1. + expect(hits.map((h) => h.chunkId)).toEqual([...hits.map((h) => h.chunkId)].sort()); + expect(hits[0]?.score).toBe(1); + // No term to match: nothing, and no passage read. + const at = sql.length; + expect(await adapter.search(' ', { source: s, topK: 5, retrieval: { mode: 'keyword' }, index: FP })).toEqual([]); + expect(rankings(sql, at)).toHaveLength(0); + }); + + it('a mode it does not list is refused before anything is read or embedded', async () => { + const { s, adapter, embedder, sql } = await seeded(); + const from = sql.length; + const calls = embedder.calls; + const refused = await adapter + .search('granite w3x', { source: s, topK: 5, retrieval: { mode: 'rerank' as never }, index: FP }) + .catch((e: unknown) => e); + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(String((refused as Error).message)).toContain("does not run the retrieval mode 'rerank'"); + expect(embedder.calls).toBe(calls); + expect(rankings(sql, from)).toEqual([]); + }); + + it('keyword never reads the approximate index of a generation that has one', async () => { + const { s, adapter, sql } = await seeded({ vectorIndexThreshold: 40 }); + const from = sql.length; + await adapter.search('granite', { source: s, topK: 5, retrieval: { mode: 'keyword' }, index: FP }); + expect(sql.slice(from).some((q) => q.includes('vector1bit('))).toBe(false); + const at = sql.length; + await adapter.search('granite', { source: s, topK: 5, retrieval: { mode: 'vector' }, index: FP }); + expect(sql.slice(at).some((q) => q.includes('vector1bit('))).toBe(true); + }); +}); + +describe('knowledge-turso fusion under the retrieval modes', () => { + type Row = { chunk_id: string; vpos: number | null; kpos: number | null }; + + /** The fusion's score as it stood before retrieval modes existed: the hybrid pin's reference. */ + const before = (row: Row): number => { + const best = 2 / (RRF_K + 1); + const leg = (pos: unknown) => (pos === null || pos === undefined ? 0 : 1 / (RRF_K + Number(pos))); + return (leg(row.vpos) + leg(row.kpos)) / best; + }; + + it('hybrid is bit-identical to the fusion before modes, for every pair of ranks up to 200', () => { + const ranks: Array = [null, ...Array.from({ length: 200 }, (_, i) => i + 1)]; + const rows: Row[] = []; + for (const vpos of ranks) for (const kpos of ranks) if (vpos !== null || kpos !== null) rows.push({ chunk_id: `${vpos}:${kpos}`, vpos, kpos }); + const fused = fuse(rows, rows.length, 2); + expect(fused).toHaveLength(rows.length); + let differing = 0; + for (const { row, score } of fused) if (!Object.is(score, before(row))) differing += 1; + expect(differing).toBe(0); + }); + + it('one leg scores 61 / (60 + rank): the first is 1, and scores fall with rank', () => { + const rows: Row[] = Array.from({ length: 50 }, (_, i) => ({ chunk_id: `c${String(i + 1).padStart(3, '0')}`, vpos: null, kpos: i + 1 })); + const fused = fuse(rows, 50, 1); + expect(fused[0]?.score).toBe(1); + for (const { row, score } of fused) expect(score).toBeCloseTo(61 / (60 + Number(row.kpos)), 12); + for (let i = 1; i < fused.length; i++) expect(fused[i - 1]!.score).toBeGreaterThan(fused[i]!.score); + }); +}); diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 93aa4111847..248f40bf932 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -197,6 +197,17 @@ const LOCK_CONFLICT = 'LOCK_CONFLICT'; /** The `k` of reciprocal rank fusion: a passage at rank `r` of a leg adds `1 / (k + r)` to its score. */ export const RRF_K = 60; +/** + * The retrieval modes this adapter runs, and its default (ADR-0161, the dated + * note of 2026-11-30 under K8): all three, `hybrid` when a source declares none. + * A report, not configuration; the default does not move with whether a + * generation has an approximate index. + */ +export const RETRIEVAL = Object.freeze({ + modes: Object.freeze(['vector', 'keyword', 'hybrid'] as const), + default: 'hybrid' as const, +}); + /** A generation row: one index of one source under one fingerprint. */ interface GenerationRow { generation: number; @@ -310,8 +321,16 @@ function withTimeout(work: Promise, ms: number, commit = false): Promise(work: Promise, ms: number, commit = false): Promise `'${m}'`).join(', ')}.`, + ), + { code: 'VALIDATION_ERROR', status: 400 }, ); } - const vectorLeg = !vector.every((x) => x === 0); - const terms = keywordTerms(query); + // The query is embedded before the database is read — never under + // `keyword`, which makes no query vector. + let vector: number[] = []; + if (mode !== 'keyword') { + const [embedded] = await embedder.embed([`${this.queryPrefix}${query}`]); + if (!Array.isArray(embedded) || embedded.length !== active.dim) { + throw new Error( + `knowledge-turso: the embedder answered a ${Array.isArray(embedded) ? embedded.length : 'missing'}-wide query ` + + `vector, and this source's index holds ${active.dim}-wide vectors.`, + ); + } + vector = embedded; + } + const vectorLeg = mode !== 'keyword' && !vector.every((x) => x === 0); + const terms = mode === 'vector' ? [] : keywordTerms(query); if (!vectorLeg && terms.length === 0) return []; // One WHERE for both legs: the organization filter, the record scope and // the metadata filter, each bound as values. ?1 is the query vector. - const args: unknown[] = [vectorLiteral(vector)]; + // Under `keyword` there is no query vector and no statement reads ?1; it is bound as NULL. + const args: unknown[] = [mode === 'keyword' ? null : vectorLiteral(vector)]; const where: string[] = []; // Whether the record index can serve the exact scan: a scope of record terms alone. let recordScope = false; @@ -925,7 +963,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { } return this.searchAttempt(query, opts, attempt + 1); } - return fuse(result.rows, topK).map(({ row: r, score }) => { + return fuse(result.rows, topK, mode === 'hybrid' ? 2 : 1).map(({ row: r, score }) => { const headingPath = parseJson(r.heading_path); return { chunkId: String(r.chunk_id), @@ -1684,16 +1722,19 @@ async function oneBitVectorsWork(db: Pick): Promise } /** - * Reciprocal rank fusion of the two legs' rows (`vpos`, `kpos`: a row's rank - * in each leg, or null): best first, at most `topK`; a tie goes to the better + * Reciprocal rank fusion of the legs' rows (`vpos`, `kpos`: a row's rank in + * each leg, or null): best first, at most `topK`; a tie goes to the better * vector rank, then to the chunk id. The score is the fused sum divided by - * that of a row first in both legs. + * that of a row first in each of the `legs` the search's mode runs: under + * `hybrid` (two) exactly as before modes existed, under one leg + * `61 / (60 + rank)`. Exported for its pin test, not from the package entry. */ -function fuse>( +export function fuse>( rows: readonly R[], topK: number, + legs: 1 | 2, ): Array<{ row: R; score: number }> { - const best = 2 / (RRF_K + 1); + const best = legs / (RRF_K + 1); const leg = (pos: unknown) => (pos === null || pos === undefined ? 0 : 1 / (RRF_K + Number(pos))); const vectorRank = (row: R) => (row.vpos === null || row.vpos === undefined ? Infinity : Number(row.vpos)); return rows diff --git a/packages/rest/src/public-form-two-type-withdrawal.test.ts b/packages/rest/src/public-form-two-type-withdrawal.test.ts index 3b6652469e8..7ca5961761f 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -22,7 +22,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; -import { ObjectStackProtocolImplementation, resetEnvWritableMetadataTypes } from '@objectstack/metadata-protocol'; +import { ObjectStackProtocolImplementation, applyStoredFormsOf, listStoredFormsOf, resetEnvWritableMetadataTypes } from '@objectstack/metadata-protocol'; import { SysMetadataAuditObject, SysMetadataCommitObject, @@ -928,6 +928,17 @@ describe('[ADR-0159 card ② item 2, D5, ADR-0029 D9.2a] the `/meta/form` read: const CAP = 'ftt.legal_desk'; const holder = { systemPermissions: [CAP] }; const stranger = { systemPermissions: [] as string[] }; + // The first served `view` read in a worker loads `@objectstack/lint` cold + // (metadata-diagnostics.ts attaches its lint warnings lazily, the cause + // meta-qualified-item-route.test.ts records): ~1s of this file's first such + // read on an idle box, past 5s on a loaded CI runner. It is a one-off load of + // the worker, not part of the read a test below asserts on, so the load is + // taken here, once, and each test's budget is for its own reads. + beforeAll(async () => { + const b = await booted({}); + await b.seedRow('view', NAME, null, viewItem(true)); + expect((await b.meta('view', NAME, holder)).status).toBe(200); + }); it('a caller refused a form\'s document at `/api/v1/meta/view/NAME` is refused it at `/api/v1/meta/form/NAME`; its holder is served both', async () => { // A view item's own audience gate travels with the form it projects. On @@ -1333,3 +1344,453 @@ describe('[#38626] `409 FORM_ADDRESS_TAKEN` carries the holding form as data on expect(answer.details?.holder).toEqual({ name: NAME, packageId: BASE }); }); }); + +/** + * [ADR-0159 D7, card ⑤a "Done when"; ruling records 7142585849, 7250977204, + * 7249158572 and 7265816895] The stored-form ceremony's write half + * (`applyStoredFormsOf`, the `--apply` the major's upgrade command calls), + * through BOTH doors before and after the run: the move, the fold and the + * removal change what no door answers, except a form the report names newly + * closed. Each pin asserts status, `code` and that no record was written + * (`closedOnBothDoors`). The ablation each pin names was run by hand and is + * recorded on the PR. + */ +describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', () => { + const engines: ObjectQL[] = []; + const savedWritable = process.env.OS_METADATA_WRITABLE; + beforeAll(() => { delete process.env.OS_METADATA_WRITABLE; }); + beforeEach(() => { + ObjectStackProtocolImplementation.resetEnvWritableCache(); + resetEnvWritableMetadataTypes(); + }); + afterAll(async () => { + if (savedWritable === undefined) delete process.env.OS_METADATA_WRITABLE; + else process.env.OS_METADATA_WRITABLE = savedWritable; + ObjectStackProtocolImplementation.resetEnvWritableCache(); + resetEnvWritableMetadataTypes(); + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const booted = async (ships: { forms?: unknown[]; views?: unknown[] }): Promise => { + const b = await boot(ships); + engines.push(b.engine); + return b; + }; + const apply = (b: Booted): Promise => applyStoredFormsOf(b.protocol, { actor: null }); + /** Every stored row, as the store holds it: the bytes a refused run must leave. */ + const allRows = async (b: Booted) => JSON.stringify(((await b.engine.find('sys_metadata', {}, { context: { isSystem: true } })) as any[]) + .map((r) => [r.type, r.name, r.package_id ?? null, r.state, typeof r.metadata === 'string' ? r.metadata : JSON.stringify(r.metadata), r.checksum]) + .sort((a, c) => JSON.stringify(a).localeCompare(JSON.stringify(c)))); + const activeBodies = async (b: Booted, type: string, name: string, packageId: string | null) => + (await rawRows(b, type, name, packageId)).map((r) => JSON.parse(r.metadata)); + + /** The record-form slot: a container's default `form`, served as `OBJECT.form`. */ + const DFORM = `${OBJECT}.form`; + const fields = { type: 'simple', sections: [{ fields: ['name', 'email'] }] }; + const switchedOff = { enabled: false, allowAnonymous: true, publicLink: `/forms/${SLUG}` }; + const baseDefaultForm = (sharingBlock: Record | null) => ({ object: OBJECT, form: { ...fields, ...(sharingBlock ? { sharing: sharingBlock } : {}) } }); + const slotItem = (sharingBlock: Record | null, extra: Record = {}) => ({ + name: DFORM, object: OBJECT, viewKind: 'form', isDefault: true, label: 'In the slot', + config: { ...fields, data: { provider: 'object', object: OBJECT }, ...(sharingBlock ? { sharing: sharingBlock } : {}) }, + ...extra, + }); + + for (const listers of [0, 1, 2] as const) { + it(`a package-less form at the environment's own address is served today where the read seats it: with ${listers} package(s) shipping a list of the name, both doors serve it before --apply, it moves into the environment, and both doors serve it after (ablate: read the environment's own address only at the environment)`, async () => { + const b = await booted({}); + for (let i = 0; i < listers; i++) { + b.engine.registerApp({ + id: `com.example.lister37111n${i}`, name: `lister37111n${i}`, version: '1.0.0', namespace: `lsn${i}`, + views: [{ object: OBJECT, listViews: { contact: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } } }], + } as any); + } + await b.engine.syncSchemas(); + await b.seedRow('view', NAME, null, viewItem(true)); + const doors = async () => [answered(await b.get()), answered(await b.post())]; + const answers = await doors(); + expect(answers[0]![0]).toBe(200); + expect(answers[1]![0]).not.toBe(404); + const result = await apply(b); + expect(result.census.forms.filter((f: any) => f.form === NAME).map((f: any) => [f.address, f.outcome, f.destination?.kind])).toEqual([ + [{ kind: 'environment' }, 'move', 'environment_form'], + ]); + expect(result).toMatchObject({ applied: true }); + expect(result.written.map((w: any) => [w.form, w.row.type, w.row.packageId ?? null])).toEqual([[NAME, 'form', null]]); + expect(await doors()).toEqual(answers); + }); + } + + describe('on a database that cannot roll back a transaction, --apply is refused before anything is written', () => { + const bootedNoRollBack = async (ships: { forms?: unknown[]; views?: unknown[] }): Promise => { + const b = await boot(ships, { canRollBack: false }); + engines.push(b.engine); + expect((b.protocol as any).engine.getDriverByName((b.protocol as any).engine.getDefaultDriverName())?.supports?.transactionsUnsupported).toBe(true); + return b; + }; + + it('a row the census moves: the refusal names the driver and what to do, no pair is ensured, every stored row byte-equal, and both doors answer the same before and after (ablate: the refusal of --apply on an engine that cannot roll back)', async () => { + const b = await bootedNoRollBack({}); + await b.seedRow('view', NAME, BASE, viewItem(true)); + const census = await listStoredFormsOf(b.protocol); + expect(census.forms.filter((f: any) => f.form === NAME).map((f: any) => f.outcome)).toEqual(['move']); + expect(census.precheck.canSwitch).toBe(true); + const doors = async () => [answered(await b.get()), answered(await b.post())]; + const before = await allRows(b); + const answers = await doors(); + const driver = (b.protocol as any).engine.getDefaultDriverName(); + const refused = await apply(b).then(() => undefined, (error: unknown) => error as Error); + expect(refused).toBeInstanceOf(Error); + expect(refused!.message).toContain(`'${driver}' cannot roll back`); + expect(refused!.message).toContain('Nothing was written'); + expect(refused!.message).toContain('supports transactions'); + expect(refused!.message).toContain('os migrate stored-forms'); + expect((b.engine as any).registry?.getPackage?.(PAIR)).toBeFalsy(); + expect(await allRows(b)).toBe(before); + expect(await doors()).toEqual(answers); + }); + + it('CONTROL: a run with nothing to write or take is not refused there', async () => { + const b = await bootedNoRollBack({ forms: [formItem(true)] }); + const result = await apply(b); + expect(result).toMatchObject({ applied: true, written: [], removed: [], rowsChanged: [], pairsEnsured: [] }); + }); + }); + + it('the switched-off form in a record-form slot, the stored twin: moved with its switch, not listed for removal, closed before and after (ablate: judge "public" by `sharing.enabled === true`)', async () => { + const b = await booted({ views: [baseDefaultForm(sharing(true))] }); + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, slotItem(switchedOff, overrides), DFORM); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result.applied).toBe(true); + expect(result.removed).toEqual([]); + expect(result.written.map((w: any) => [w.form, w.row.type, w.row.packageId])).toEqual([[DFORM, 'form', PAIR]]); + expect(await activeBodies(b, 'form', DFORM, PAIR)).toEqual([expect.objectContaining({ sharing: switchedOff, overrides: overrides.overrides })]); + await closedOnBothDoors(b); + }); + + for (const shape of ['a `.custom` override', 'a package-less row'] as const) { + it(`its twin, the link-less row over an open base, as ${shape}: a \`form\` row with no link, never listed for removal, closed before and after (ablate: class the row by its own body alone)`, async () => { + const b = await booted({ views: [baseDefaultForm(sharing(true))] }); + if (shape === 'a `.custom` override') { + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, slotItem(null, overrides), DFORM); + } else { + await b.seedRow('view', DFORM, null, slotItem(null)); + } + await closedOnBothDoors(b); + const census = (await apply(b)).census; + expect(census.forms.filter((f: any) => f.form === DFORM).map((f: any) => f.outcome)).toEqual(['move']); + const [moved] = await activeBodies(b, 'form', DFORM, PAIR); + expect(moved).toBeDefined(); + expect(moved.sharing).toBeUndefined(); + await closedOnBothDoors(b); + }); + } + + for (const shape of ['a `.custom` switch-only override', 'a member of a stored container'] as const) { + it(`the ceremony keeps a withdrawal closed: withdrawn by ${shape}, the form answers 404 after it, the moved row carries the stored body without the read's provenance, and a second run finds nothing (ablate: the provenance strip; the emptied container's deletion)`, async () => { + const b = await booted({ views: [container(true)] }); + if (shape === 'a `.custom` switch-only override') { + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, viewItem(false, overrides)); + } else { + await b.seedRow('view', OBJECT, null, { name: OBJECT, ...container(false) }); + } + await closedOnBothDoors(b); + expect((await apply(b)).applied).toBe(true); + expect(await rawRows(b, 'view', shape === 'a member of a stored container' ? OBJECT : NAME, shape === 'a member of a stored container' ? null : PAIR)).toEqual([]); + // The moved row carries the withdrawal as stored, and none of the provenance the read's expansion wears from the base. + const [moved] = await activeBodies(b, 'form', NAME, PAIR); + expect(moved).toMatchObject({ sharing: sharing(false), overrides: overrides.overrides }); + for (const key of ['_packageId', '_packageVersion', '_provenance']) expect(moved).not.toHaveProperty(key); + await closedOnBothDoors(b); + // Idempotent: nothing of the emptied container is left to hold the next run. + expect(await apply(b)).toMatchObject({ applied: true, written: [], removed: [], rowsChanged: [] }); + await closedOnBothDoors(b); + }); + } + + it('a `.custom` view override that withdraws a form the base ships as a `form` item: moved into the pair as that form\'s declared override, written as the pair\'s own row and not as an edit of the shipped item, closed before and after (ablate: judge the declared override\'s write as an override of the shipped item)', async () => { + const b = await booted({ forms: [formItem(true)] }); + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, viewItem(false, overrides)); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result.written.map((w: any) => [w.form, w.row.type, w.row.packageId, w.destination.kind])).toEqual([[NAME, 'form', PAIR, 'pair_override']]); + expect(await activeBodies(b, 'form', NAME, PAIR)).toEqual([expect.objectContaining({ sharing: sharing(false), overrides: overrides.overrides })]); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual([]); + await closedOnBothDoors(b); + }); + + it('the fold keeps the served body and only narrows: an open override in the pair beside a package-less row that withdraws the form is closed before and after, and the destination keeps its link with the switch off (ablate: the carry of the folded row\'s switch)', async () => { + const b = await booted({ views: [container(true)] }); + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, viewItem(true, overrides)); + await b.seedRow('view', NAME, null, viewItem(false)); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result.written).toEqual([expect.objectContaining({ form: NAME, switchedOff: SLUG })]); + expect(await activeBodies(b, 'form', NAME, PAIR)).toEqual([expect.objectContaining({ sharing: expect.objectContaining({ publicLink: `/forms/${SLUG}`, enabled: false }) })]); + expect(await rawRows(b, 'view', NAME, null)).toEqual([]); + await closedOnBothDoors(b); + }); + + it('the fold: a link-less row bound to the read-only base, over its open form, beside an open package-less row, is closed before and after, and the pair\'s override has no link (ablate: take the package-less row first)', async () => { + const b = await booted({ views: [container(true)] }); + await b.seedRow('view', NAME, BASE, viewItem(null)); + await b.seedRow('view', NAME, null, viewItem(true)); + await closedOnBothDoors(b); + expect((await apply(b)).applied).toBe(true); + const [moved] = await activeBodies(b, 'form', NAME, PAIR); + expect(moved).toMatchObject({ overrides: overrides.overrides }); + expect(moved.sharing).toBeUndefined(); + await closedOnBothDoors(b); + }); + + it('the fold, the writable-base twin: a writable package\'s own open row beside a package-less row that withdraws the form is open before and closed after, and the report names it newly closed (ablate: the report\'s line for a newly closed form)', async () => { + const b = await booted({}); + await b.install(DEPENDENT); + await b.saveInto('view', DEPENDENT, viewItem(true)); + await b.seedRow('view', NAME, null, viewItem(false)); + await openOnBothDoors(b); + const result = await apply(b); + expect(result.census.forms.filter((f: any) => f.form === NAME)).toEqual([expect.objectContaining({ + address: { kind: 'package', packageId: DEPENDENT }, outcome: 'move', newlyClosed: true, + })]); + await closedOnBothDoors(b); + }); + + it('the fold, a writable package\'s list ahead of a package-less form row: closed before and after, no `form` row of the name, the list byte-equal, the row left in place and not holding (ablate: fold the package-less row into the package\'s own `form` row)', async () => { + const b = await booted({}); + await b.install(DEPENDENT); + await b.saveInto('view', DEPENDENT, LIST); + await b.seedRow('view', NAME, null, viewItem(true)); + const list = await rawRows(b, 'view', NAME, DEPENDENT); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result.census.precheck.canSwitch).toBe(true); + expect(result.census.forms.filter((f: any) => f.form === NAME).map((f: any) => [f.outcome, f.reason])).toEqual([['left_in_place', 'served_no_form']]); + expect(await rawRows(b, 'form', NAME, DEPENDENT)).toEqual([]); + expect(await rawRows(b, 'view', NAME, DEPENDENT)).toEqual(list); + expect(await rawRows(b, 'view', NAME, null)).toHaveLength(1); + await closedOnBothDoors(b); + }); + + it('the fold, a no-form row ahead of a form row: a list bound to the base, over its open form, beside an open package-less form row, is closed before and after, the pair holds no row of the name (ablate: find the served row among form rows only)', async () => { + const b = await booted({ views: [container(true)] }); + await b.seedRow('view', NAME, BASE, LIST); + await b.seedRow('view', NAME, null, viewItem(true)); + const before = await allRows(b); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result.census.precheck.canSwitch).toBe(true); + expect(result.census.forms.filter((f: any) => f.form === NAME).map((f: any) => f.outcome)).toEqual(['left_in_place']); + expect(await rawRows(b, 'form', NAME, PAIR)).toEqual([]); + expect(await allRows(b)).toBe(before); + await closedOnBothDoors(b); + }); + + it('the retired form and its successor on one address: both rows are moved as written, not through the `form` save door, the successor answers before and after, and the report names the pair (ablate: move the rows through the `form` save door)', async () => { + const b = await booted({}); + const RETIRED = `${OBJECT}.retired`; + await b.seedRow('view', RETIRED, null, { ...viewItem(false), name: RETIRED, label: 'Retired' }); + await b.seedRow('view', NAME, null, viewItem(true)); + await openOnBothDoors(b); + const result = await apply(b); + expect(result.census.sharedSlugs).toEqual([{ slug: SLUG, forms: [RETIRED, NAME].sort() }]); + expect(result.written.map((w: any) => [w.form, w.row.type, w.row.packageId ?? null]).sort()).toEqual([[NAME, 'form', null], [RETIRED, 'form', null]].sort()); + expect(await rawRows(b, 'view', NAME, null)).toEqual([]); + expect(await rawRows(b, 'view', RETIRED, null)).toEqual([]); + await openOnBothDoors(b); + expect((await b.get()).body).toMatchObject({ slug: SLUG, label: 'Contact us' }); + }); + + it('all or nothing: with a row that holds the upgrade stored beside movable rows, --apply writes nothing, every stored row byte-equal, and both doors answer the same before and after (ablate: move what can be moved and report the rest)', async () => { + const b = await booted({ views: [container(true)] }); + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, viewItem(false, overrides)); + const BROKEN = `${OBJECT}.broken`; + await b.seedRow('view', BROKEN, null, { name: BROKEN, viewKind: 'form', sharing: sharing(true) }); + const before = await allRows(b); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result).toMatchObject({ applied: false, written: [], removed: [], rowsChanged: [], pairsEnsured: [] }); + expect(result.census.precheck.holds).toEqual([expect.objectContaining({ cause: 'unreadable' })]); + expect(await allRows(b)).toBe(before); + await closedOnBothDoors(b); + }); + + it('internal record forms are removed, and only those: an unlinked default form in a stored container with a list goes, the container is re-saved with its list byte-equal, the report carries its body (ablate: the base half of the internal test)', async () => { + const b = await booted({ views: [{ object: OBJECT, form: fields, formViews: { contact: { ...body(true), data: { provider: 'object', object: OBJECT } } } }] }); + const LIST_BODY = { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } }; + await b.seedRow('view', OBJECT, null, { name: OBJECT, object: OBJECT, list: LIST_BODY, form: { ...fields, label: 'Edited' } }); + await openOnBothDoors(b); + const result = await apply(b); + expect(result.removed).toEqual([expect.objectContaining({ form: DFORM, object: OBJECT, body: expect.objectContaining({ label: 'Edited' }) })]); + const [kept] = await activeBodies(b, 'view', OBJECT, null); + expect(kept).toEqual({ name: OBJECT, object: OBJECT, list: LIST_BODY }); + await openOnBothDoors(b); + }); + + it('the pair\'s own item (ruling 7250977204): a row bound to a read-only package that ships no form of the name moves into the pair declaring no `overrides`, and the public address answers byte-equal before and after', async () => { + const b = await booted({}); + await b.seedRow('view', NAME, BASE, viewItem(true)); + const before = await b.get(); + expect(before.status).toBe(200); + const result = await apply(b); + expect(result.written).toEqual([expect.objectContaining({ destination: { kind: 'pair_form', base: BASE, pair: PAIR } })]); + const [moved] = await activeBodies(b, 'form', NAME, PAIR); + expect(moved).toBeDefined(); + expect(moved).not.toHaveProperty('overrides'); + expect(JSON.stringify(await b.get())).toBe(JSON.stringify(before)); + }); + + it('the census and the run agree where the store seals the destination: the pair\'s own item for a row bound to a read-only package that ships no form of the name, where another package ships the name as a `form` item, holds the upgrade in the census, and --apply writes nothing (ablate: the census read of the store\'s seal)', async () => { + const b = await booted({}); + const SHIPPER = 'com.example.shipper37111'; + b.engine.registerApp({ + id: SHIPPER, name: 'shipper37111', version: '1.0.0', type: 'app', namespace: 'fts', + dependencies: { [BASE]: '^1.0.0' }, + forms: [formItem(true, {}, OTHER_SLUG)], + } as any); + await b.engine.syncSchemas(); + await b.seedRow('view', NAME, BASE, viewItem(true)); + const doors = async () => [answered(await b.get()), answered(await b.post()), answered(await b.get(OTHER_SLUG))]; + const before = await allRows(b); + const answers = await doors(); + const census = await listStoredFormsOf(b.protocol); + const plans = census.forms.filter((f: any) => f.form === NAME).map((f: any) => [f.address, f.outcome, (f as any).cause ?? null]); + expect(plans).toEqual([[{ kind: 'base', packageId: BASE }, 'hold', 'app_author']]); + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.holds).toEqual([expect.objectContaining({ row: expect.objectContaining({ name: NAME, packageId: BASE }), cause: 'app_author' })]); + expect(census.precheck.holds[0]!.refusal).toContain(`'${SHIPPER}'`); + const result = await apply(b); + expect(result).toMatchObject({ applied: false, written: [], removed: [], rowsChanged: [], pairsEnsured: [] }); + expect(await allRows(b)).toBe(before); + expect(await doors()).toEqual(answers); + }); + + it('the census and the run agree where the store seals a kept row the run writes: a `form` row kept in a package the environment writes, carrying the withdrawal of an old-shape row folded into it, where another package ships the name as a `form` item, holds the upgrade in the census, and --apply writes nothing (ablate: the census read of the store\'s seal for a kept row)', async () => { + const b = await booted({}); + await b.install(DEPENDENT); + const SHIPPER = 'com.example.shipper37111'; + b.engine.registerApp({ + id: SHIPPER, name: 'shipper37111', version: '1.0.0', type: 'app', namespace: 'fts', + dependencies: { [BASE]: '^1.0.0' }, + forms: [formItem(true, {}, OTHER_SLUG)], + } as any); + await b.engine.syncSchemas(); + await b.seedRow('form', NAME, DEPENDENT, formItem(true)); + await b.seedRow('view', NAME, DEPENDENT, viewItem(false)); + const before = await allRows(b); + const census = await listStoredFormsOf(b.protocol); + const plans = census.forms.filter((f: any) => f.form === NAME && f.address.packageId === DEPENDENT).map((f: any) => [f.outcome, (f as any).cause ?? null]); + expect(plans).toEqual([['hold', 'app_author']]); + expect(census.precheck.canSwitch).toBe(false); + expect(census.precheck.holds.map((h: any) => h.refusal).join('\n')).toContain(`'${SHIPPER}'`); + const result = await apply(b); + expect(result).toMatchObject({ applied: false, written: [], removed: [], rowsChanged: [], pairsEnsured: [] }); + expect(await allRows(b)).toBe(before); + }); + + it('a form no door serves today is left in place by the upgrade: the row stays as stored, nothing is written, and both doors answer 404 before --apply and after it (ablate: the census read of the form served today)', async () => { + const b = await booted({}); + b.engine.registerApp({ + id: 'com.example.lister37111', name: 'lister37111', version: '1.0.0', namespace: 'lst', + views: [{ object: OBJECT, listViews: { contact: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } } }], + } as any); + await b.engine.syncSchemas(); + await b.seedRow('view', NAME, BASE, viewItem(true)); + const before = await allRows(b); + const doors = async () => [answered(await b.get()), answered(await b.post())]; + expect(await doors()).toEqual([[404, 'FORM_NOT_FOUND'], [404, 'FORM_NOT_FOUND']]); + const result = await apply(b); + expect(result.census.forms.filter((f: any) => f.form === NAME).map((f: any) => [f.address, f.outcome, f.reason])).toEqual([ + [{ kind: 'base', packageId: BASE }, 'left_in_place', 'served_by_no_door'], + ]); + expect(result).toMatchObject({ applied: true, written: [], removed: [], rowsChanged: [] }); + expect(await allRows(b)).toBe(before); + expect(await doors()).toEqual([[404, 'FORM_NOT_FOUND'], [404, 'FORM_NOT_FOUND']]); + }); + + for (const [shape, pkg, extra] of [ + ['bound to a package the environment writes', DEPENDENT, {}], + ['the pair\'s own row', PAIR, {}], + ['the pair\'s declared override of a base that ships no form of the name', PAIR, overrides], + ] as const) { + it(`a form no door serves today is left in place by the upgrade, whatever package its row is bound to: ${shape} (ablate: the census read of the form served today, at the address each plan is made at)`, async () => { + const b = await booted({}); + await b.install(pkg); + b.engine.registerApp({ + id: 'com.example.lister37111', name: 'lister37111', version: '1.0.0', namespace: 'lst', + views: [{ object: OBJECT, listViews: { contact: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } } }], + } as any); + await b.engine.syncSchemas(); + await b.seedRow('view', NAME, pkg, viewItem(true, extra)); + const before = await allRows(b); + const doors = async () => [answered(await b.get()), answered(await b.post())]; + expect(await doors()).toEqual([[404, 'FORM_NOT_FOUND'], [404, 'FORM_NOT_FOUND']]); + const result = await apply(b); + const plans = result.census.forms.filter((f: any) => f.form === NAME); + expect(plans.length).toBeGreaterThan(0); + expect(plans.map((f: any) => [f.outcome, f.reason])).toEqual(plans.map(() => ['left_in_place', 'served_by_no_door'])); + expect(result.written.filter((w: any) => w.form === NAME)).toEqual([]); + expect(await allRows(b)).toBe(before); + expect(await doors()).toEqual([[404, 'FORM_NOT_FOUND'], [404, 'FORM_NOT_FOUND']]); + }); + } + + for (const [shape, overrideOpen, boundOpen] of [ + ['the pair\'s override withdraws the form, the bound row is open', false, true], + ['the pair\'s override is open, the bound row withdraws the form (read today: closed, the withdrawal carried)', true, false], + ] as const) { + it(`M3 through both doors: no package ships the name, a row bound to the read-only base beside the pair's declared override of it; ${shape}: one \`form\` row in the pair, the override's body kept, and both doors answer as before (ablate: plan the pair's override at the pair's own address)`, async () => { + const b = await booted({}); + await b.install(PAIR); + await b.saveBeforeTheGate('view', PAIR, viewItem(overrideOpen, overrides)); + await b.seedRow('view', NAME, BASE, viewItem(boundOpen)); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result.applied).toBe(true); + expect(result.written.map((w: any) => [w.form, w.row.type, w.row.packageId])).toEqual([[NAME, 'form', PAIR]]); + const [kept] = await activeBodies(b, 'form', NAME, PAIR); + // The override's body is the one kept; a withdrawal the bound row carried narrows it to switched off. + expect(kept.sharing).toEqual(overrideOpen ? { ...sharing(true), enabled: false } : sharing(false)); + expect(await rawRows(b, 'view', NAME, BASE)).toEqual([]); + expect(await rawRows(b, 'view', NAME, PAIR)).toEqual([]); + await closedOnBothDoors(b); + }); + } + + for (const open of [false, true]) { + it(`a row the read serves at another address than the package it is bound to (ruling record 7254350842): a module ships the form on its own object, the row bound to its App is ${open ? 'open' : 'switched off'}; it moves into the pair as the module's declared override, and both doors answer as before (ablate: plan the row at the package it is bound to)`, async () => { + const b = await booted({}); + const MODULE = `${BASE}.desk`; + const TICKET = 'ftt_ticket'; + const TICKET_FORM = `${TICKET}.contact`; + const TICKET_SLUG = 'ticket-37111'; + const data = { provider: 'object', object: TICKET }; + // The base as an App, as an installed App's manifest states it: its module's App. + b.engine.registerApp({ id: BASE, name: 'forms37086', version: '1.0.0', type: 'app', namespace: 'ftt', objects: [INQUIRY] } as any); + b.engine.registerApp({ + id: MODULE, name: 'forms37086-desk', version: '1.1.0', type: 'module', namespace: 'ftt', + dependencies: { [BASE]: '^1.0.0' }, + objects: [{ ...INQUIRY, name: TICKET, label: 'Ticket' }], + views: [{ object: TICKET, formViews: { contact: { ...body(true, TICKET_SLUG), data } } }], + } as any); + await b.engine.syncSchemas(); + await b.seedRow('view', TICKET_FORM, BASE, { name: TICKET_FORM, object: TICKET, viewKind: 'form', label: 'Stored', config: { ...body(open, TICKET_SLUG), data } }); + const doors = async () => [answered(await b.get(TICKET_SLUG)), (await b.get(TICKET_SLUG)).body?.label ?? null]; + const before = await doors(); + expect(before).toEqual(open ? [[200, undefined], 'Stored'] : [[404, 'FORM_NOT_FOUND'], null]); + const result = await apply(b); + expect(result.census.forms.filter((f: any) => f.form === TICKET_FORM).map((f: any) => [f.address.packageId, f.outcome, f.destination?.kind])).toEqual([[MODULE, 'move', 'pair_override']]); + const [moved] = await activeBodies(b, 'form', TICKET_FORM, PAIR); + expect(moved).toMatchObject({ overrides: { package: MODULE } }); + expect(await rawRows(b, 'view', TICKET_FORM, BASE)).toEqual([]); + expect(await doors()).toEqual(before); + if (open) expect(answered(await b.post(TICKET_SLUG))).not.toEqual([404, 'FORM_NOT_FOUND']); + else expect(answered(await b.post(TICKET_SLUG))).toEqual([404, 'FORM_NOT_FOUND']); + }); + } +}); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts index 4179f73877d..7eb1a35142a 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -1533,14 +1533,19 @@ describe('KnowledgeService — search refills after the permission filter', () = expect(asked()).toEqual([['s1', 15], ['s2', 15], ['s1', 60]]); }); - it('a refill the adapter fails keeps the source\'s round-one survivors', async () => { + it('a refill the adapter fails without a code refuses the source, as a coded refusal of the refill does', async () => { const { svc, adapter } = setup({ s1: rankedHits('s1', 100) }, ['rec_2']); const first = adapter.searchSpy.getMockImplementation()!; adapter.searchSpy.mockImplementationOnce(first).mockImplementationOnce(async () => { throw new Error('store unavailable'); }); - const out = await svc.search('q', { topK: 5, executionContext: MEMBER }); - expect(out.map((h) => h.sourceRecordId)).toEqual(['rec_2']); + // The only source refused the refill: its round-one survivors are dropped + // and the search is refused whole, never answered with a partial read. + await expect(svc.search('q', { topK: 5, executionContext: MEMBER })).rejects.toMatchObject({ + code: 'SERVICE_UNAVAILABLE', + status: 503, + refused: [expect.objectContaining({ sourceId: 's1', code: 'SERVICE_UNAVAILABLE', status: 503 })], + }); expect(adapter.searchSpy).toHaveBeenCalledTimes(2); }); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts index 1a391754a48..4499ab1c945 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts @@ -616,11 +616,16 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb const named = /No embedder is configured[\s\S]*ai\.embedder_provider[\s\S]*restart/; await expect(indexOne(knowledge, 'hello')).rejects.toThrow(named); - // The adapter's search answers the error; the service's search reports it - // per source and answers no hits. + // The adapter's search answers the error; the service's search refuses + // the source (never no hits), and the only source refused refuses the + // whole search. The embedder's own text stays on the operator's line. await expect(knowledge.getAdapter('vec').search('hello', { source: knowledge.getSource('docs')!, topK: 5 })) .rejects.toThrow(named); - await expect(knowledge.search('hello', { sourceIds: ['docs'], executionContext: SYSTEM })).resolves.toEqual([]); + await expect(knowledge.search('hello', { sourceIds: ['docs'], executionContext: SYSTEM })).rejects.toMatchObject({ + code: 'SERVICE_UNAVAILABLE', + status: 503, + refused: [expect.objectContaining({ sourceId: 'docs', code: 'SERVICE_UNAVAILABLE', status: 503 })], + }); expect(lines.some((l) => l.level === 'error' && named.test(l.line))).toBe(true); // A vector column cannot be sized from it either. expect(() => embedder.dimensions).toThrow(named); @@ -740,7 +745,12 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb (err: unknown) => err as Error, ); expect(failure.message).not.toContain(API_KEY); - await rejected.knowledge.search('hello', { sourceIds: ['docs'], executionContext: SYSTEM }); + const searched = await rejected.knowledge.search('hello', { sourceIds: ['docs'], executionContext: SYSTEM }).then( + () => { throw new Error('expected a refusal'); }, + (err: unknown) => err as Error & { code?: string; status?: number }, + ); + expect(searched).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(searched.message).not.toContain(API_KEY); expect(requests.length).toBeGreaterThan(0); expect(rejected.lines.filter((l) => l.line.includes(API_KEY))).toEqual([]); }); @@ -1061,7 +1071,11 @@ describe('[ADR-0161 K8, note on item 12] a runtime-composed knowledge service is expect(heldLines()).toEqual([]); expect(knowledge.knowledgeTools().definitions.map((d) => d.name)).toEqual(['search_knowledge']); expect(lines.some((l) => l.level === 'info' && l.line.includes('no embedder is configured ('))).toBe(true); - await expect(knowledge.search('granite', { sourceIds: ['docs'], executionContext: SYSTEM })).resolves.toEqual([]); + await expect(knowledge.search('granite', { sourceIds: ['docs'], executionContext: SYSTEM })).rejects.toMatchObject({ + code: 'SERVICE_UNAVAILABLE', + status: 503, + refused: [expect.objectContaining({ sourceId: 'docs', code: 'SERVICE_UNAVAILABLE', status: 503 })], + }); expect(calls).toContain('search'); }); }); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts index b027f228861..c0dd5d9bec6 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts @@ -258,11 +258,14 @@ describe('search_knowledge — a refused source (ADR-0161 K7, rule 5)', () => { }); }); - it('control: a failure without a code is logged and skipped as before, and carries no refused list', async () => { + it('a failure without a code refuses its source as SERVICE_UNAVAILABLE, its own text withheld — never no hits', async () => { const answer = await createKnowledgeTools(twoSources(['policy_clauses'], () => new Error('socket hang up'))) .searchKnowledge({ query: 'q' }, caller); expect(answer.hits.map((h) => h.sourceId)).toEqual(['faq']); - expect(answer).not.toHaveProperty('refused'); + expect(answer.refused).toEqual([ + { sourceId: 'policy_clauses', code: 'SERVICE_UNAVAILABLE', message: expect.stringContaining("source 'policy_clauses'") }, + ]); + expect(answer.refused?.[0].message).not.toContain('socket hang up'); }); it('an answer with nothing refused carries no refused list', async () => { diff --git a/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts b/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts new file mode 100644 index 00000000000..9d7d3ec7058 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts @@ -0,0 +1,377 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38692 phase 1a] A source's retrieval mode (`source.retrieval.mode`) as the + * knowledge service reads it: the effective mode (the declaration, else the + * adapter's default), handed to the adapter on every search and logged at + * `debug`, never answered to the caller; and the four refusal points of a + * declared mode the adapter does not run (save, registration, the boot's + * reading, every search). Such a source is still indexed. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { LiteKernel } from '@objectstack/core'; +import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { + KnowledgeHit, + KnowledgeRetrievalMode, + KnowledgeSource, + ObjectKnowledgeSource, +} from '@objectstack/spec/ai'; +import { KnowledgeService } from '../knowledge-service.js'; +import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js'; +import { KnowledgeSourceLoader } from '../knowledge-source-loader.js'; +import { knowledgeIndexStatusActionHandler } from '../knowledge-build-actions.js'; +import { + RETRIEVAL_UNSUPPORTED_CODE, + readRetrieval, + resolveRetrievalMode, + retrievalRefusalText, +} from '../knowledge-retrieval-mode.js'; + +const SYSTEM = { isSystem: true, positions: [], permissions: [] } as never; +const ALL_MODES: KnowledgeRetrievalMode[] = ['vector', 'keyword', 'hybrid']; + +function adapterOf( + id: string, + retrieval?: { modes: KnowledgeRetrievalMode[]; default: KnowledgeRetrievalMode }, +): IKnowledgeAdapter & { searchSpy: ReturnType; upsertSpy: ReturnType } { + const searchSpy = vi.fn(async (_q: string, opts: { source: KnowledgeSource }): Promise => [ + { chunkId: `${opts.source.name}#c1`, documentId: `${opts.source.name}:d1`, sourceId: opts.source.name, snippet: 'x', score: 1 }, + ]); + const upsertSpy = vi.fn(async () => undefined); + return { + id, + upsert: upsertSpy, + delete: vi.fn(async () => undefined), + search: searchSpy, + ...(retrieval === undefined ? {} : { capabilities: { retrieval } }), + searchSpy, + upsertSpy, + } as never; +} + +function source(name: string, adapter: string, mode?: KnowledgeRetrievalMode | 'empty'): KnowledgeSource { + return { + name, + label: name, + adapter, + source: { + kind: 'object', + object: 'task', + content: ['title', 'notes'], + ...(mode === undefined ? {} : { retrieval: mode === 'empty' ? {} : { mode } }), + } as ObjectKnowledgeSource, + }; +} + +function logged() { + const lines: Array<[string, string]> = []; + return { + lines, + logger: { + debug: (m: string) => lines.push(['debug', m]), + info: (m: string) => lines.push(['info', m]), + warn: (m: string) => lines.push(['warn', m]), + error: (m: string) => lines.push(['error', m]), + }, + }; +} + +describe('resolveRetrievalMode — the effective mode and where it came from', () => { + const hybridStore = adapterOf('turso', { modes: ALL_MODES, default: 'hybrid' }); + const vectorOnly = adapterOf('vec', { modes: ['vector'], default: 'vector' }); + const silent = adapterOf('memory'); + + it('the declaration wins; none declared (or `retrieval: {}`) takes the adapter default', () => { + for (const mode of ALL_MODES) { + expect(resolveRetrievalMode(source('s', 'turso', mode), hybridStore)).toEqual({ refused: false, mode, from: 'source' }); + } + expect(resolveRetrievalMode(source('s', 'turso'), hybridStore)).toEqual({ refused: false, mode: 'hybrid', from: 'adapter' }); + expect(resolveRetrievalMode(source('s', 'turso', 'empty'), hybridStore)).toEqual({ refused: false, mode: 'hybrid', from: 'adapter' }); + }); + + it('a mode the adapter does not list is refused, never run another way', () => { + expect(resolveRetrievalMode(source('s', 'vec', 'keyword'), vectorOnly)).toEqual({ + refused: true, + declared: 'keyword', + modes: ['vector'], + }); + }); + + it('an adapter that reports no modes is never told one: none declared searches as before, a declared one is refused', () => { + expect(resolveRetrievalMode(source('s', 'memory'), silent)).toEqual({ refused: false }); + expect(resolveRetrievalMode(source('s', 'memory', 'vector'), silent)).toEqual({ refused: true, declared: 'vector' }); + }); + + it('the refusal text names the declared mode, the modes the store runs and the remedies', () => { + expect(retrievalRefusalText('vec', 'keyword', vectorOnly)).toBe( + "its `retrieval.mode` is 'keyword', and the store 'vec' runs 'vector' (default 'vector'); a source is never " + + "searched in a mode other than the one it declares. Write one of 'vector' as `retrieval.mode`, or remove it " + + "for the store's default, or bind the source to a store that runs 'keyword'.", + ); + expect(retrievalRefusalText('memory', 'vector', silent)).toContain( + "the store 'memory' reports no retrieval modes, so a source on it may only leave `retrieval.mode` out", + ); + }); + + it('the operator reading carries the declaration, the effective mode, its origin and the store modes', () => { + expect(readRetrieval(source('s', 'turso'), hybridStore)).toEqual({ + mode: 'hybrid', + from: 'adapter', + modes: ALL_MODES, + default: 'hybrid', + }); + expect(readRetrieval(source('s', 'vec', 'keyword'), vectorOnly)).toEqual({ + declared: 'keyword', + refused: true, + modes: ['vector'], + default: 'vector', + }); + expect(readRetrieval(source('s', 'memory'), silent)).toEqual({}); + }); +}); + +describe('the search hands the adapter its effective mode', () => { + it('declared, defaulted, and nothing at all for an adapter that reports no modes', async () => { + const { lines, logger } = logged(); + const svc = new KnowledgeService({ logger }); + const turso = adapterOf('turso', { modes: ALL_MODES, default: 'hybrid' }); + const memory = adapterOf('memory'); + svc.registerAdapter('turso', turso); + svc.registerAdapter('memory', memory); + svc.registerSource(source('kw', 'turso', 'keyword')); + svc.registerSource(source('dflt', 'turso')); + svc.registerSource(source('plain', 'memory')); + + const report = await svc.searchWithRefusals('q', { executionContext: SYSTEM }); + expect(report.refused).toEqual([]); + const modeOf = (name: string) => + turso.searchSpy.mock.calls.find(([, o]) => (o as { source: KnowledgeSource }).source.name === name)?.[1]?.retrieval; + expect(modeOf('kw')).toEqual({ mode: 'keyword' }); + expect(modeOf('dflt')).toEqual({ mode: 'hybrid' }); + expect(memory.searchSpy).toHaveBeenCalledOnce(); + expect('retrieval' in (memory.searchSpy.mock.calls[0]![1] as object)).toBe(false); + + // The mode and its origin are the operator's, at debug; the caller's answer carries neither. + const debug = lines.filter(([level]) => level === 'debug').map(([, m]) => m); + expect(debug).toContain("[knowledge] source 'kw' searched in 'keyword' mode (declared by the source)."); + expect(debug).toContain("[knowledge] source 'dflt' searched in 'hybrid' mode (the default of adapter 'turso')."); + expect(JSON.stringify(report)).not.toMatch(/keyword|hybrid|retrieval/); + }); +}); + +describe('a declared mode the adapter does not run — the four refusal points', () => { + function bootLike() { + const { lines, logger } = logged(); + const svc = new KnowledgeService({ logger }); + const vec = adapterOf('vec', { modes: ['vector'], default: 'vector' }); + const memory = adapterOf('memory'); + return { svc, vec, memory, lines }; + } + + it('1 · the save is refused 400 VALIDATION_ERROR, listing the modes the store runs', async () => { + const svc = new KnowledgeService({ dataEngine: {} as IDataEngine }); + svc.registerAdapter('vec', adapterOf('vec', { modes: ['vector'], default: 'vector' })); + svc.registerAdapter('memory', adapterOf('memory')); + const ctx = { userId: 'u1', positions: [], permissions: [] } as never; + const onVec = await svc.admitAuthoredSource(source('s1', 'vec', 'keyword'), ctx); + expect(onVec).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400 }); + expect((onVec as { message: string }).message).toContain("the store 'vec' runs 'vector' (default 'vector')"); + const onMemory = await svc.admitAuthoredSource(source('s2', 'memory', 'hybrid'), ctx); + expect(onMemory).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400 }); + expect((onMemory as { message: string }).message).toContain("the store 'memory' reports no retrieval modes"); + // A mode the store runs passes this point (the save goes on to its next check). + const ok = await svc.admitAuthoredSource(source('s3', 'vec', 'vector'), ctx); + expect((ok as { message?: string }).message ?? '').not.toContain('retrieval.mode'); + }); + + it('2 · registration in code refuses it only when its adapter already resolves; the loader takes it', () => { + const { svc, vec } = bootLike(); + svc.registerAdapter('vec', vec); + let refused: unknown; + try { + svc.registerSource(source('s1', 'vec', 'keyword')); + } catch (err) { + refused = err; + } + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(String((refused as Error).message)).toContain("registerSource refused source 's1': its `retrieval.mode` is 'keyword'"); + expect(svc.getSource('s1')).toBeUndefined(); + // A published item meets no save and is not refused by the loader: 3 and 4 hold it. + svc.registerMetadataSource(source('s2', 'vec', 'hybrid')); + expect(svc.getSource('s2')).toBeDefined(); + // A store not registered yet is no verdict: the source is taken. + svc.registerSource(source('s3', 'pgvector', 'keyword')); + expect(svc.getSource('s3')).toBeDefined(); + }); + + it('3 · the boot reading names it once at error; 4 · every search lists it in `refused`, never runs it at the default', async () => { + const { svc, vec, lines } = bootLike(); + svc.registerSource(source('bad', 'vec', 'keyword')); + svc.registerSource(source('good', 'vec')); + svc.registerAdapter('vec', vec); + + expect(svc.reportUnsupportedRetrieval()).toEqual(['bad']); + const errors = lines.filter(([level]) => level === 'error').map(([, m]) => m); + expect(errors).toHaveLength(1); + expect(errors[0]).toContain("[knowledge] source 'bad' is not searched: its `retrieval.mode` is 'keyword'"); + expect(errors[0]).toContain(`answers ${RETRIEVAL_UNSUPPORTED_CODE}`); + + const both = await svc.searchWithRefusals('q', { executionContext: SYSTEM }); + expect(both.hits.map((h) => h.sourceId)).toEqual(['good']); + expect(both.refused).toEqual([ + expect.objectContaining({ sourceId: 'bad', code: RETRIEVAL_UNSUPPORTED_CODE, status: 503 }), + ]); + expect(both.refused[0]!.message).toContain("Knowledge source 'bad' is not searched: its `retrieval.mode` is 'keyword'"); + // Never searched another way. + expect(vec.searchSpy.mock.calls.map(([, o]) => (o as { source: KnowledgeSource }).source.name)).toEqual(['good']); + + const alone = await svc.search('q', { sourceIds: ['bad'], executionContext: SYSTEM }).catch((e: unknown) => e); + expect(alone).toMatchObject({ code: RETRIEVAL_UNSUPPORTED_CODE, status: 503 }); + }); + + it('a mode declared on an adapter that reports none is refused at every search the same way', async () => { + const { svc, memory } = bootLike(); + svc.registerSource(source('s1', 'memory', 'vector')); + svc.registerAdapter('memory', memory); + expect(svc.reportUnsupportedRetrieval()).toEqual(['s1']); + const alone = await svc.search('q', { sourceIds: ['s1'], executionContext: SYSTEM }).catch((e: unknown) => e); + expect(alone).toMatchObject({ code: RETRIEVAL_UNSUPPORTED_CODE, status: 503 }); + expect(memory.searchSpy).not.toHaveBeenCalled(); + }); + + it('such a source is still indexed: the mode is read by search alone', async () => { + const find = vi.fn(async (_o: string, query: { where?: unknown }) => + query.where === undefined ? [{ id: 'r1', title: 'T1', notes: 'N1' }] : [], + ); + const svc = new KnowledgeService({ dataEngine: { find } as unknown as IDataEngine }); + const vec = adapterOf('vec', { modes: ['vector'], default: 'vector' }); + svc.registerSource(source('bad', 'vec', 'keyword')); + svc.registerAdapter('vec', vec); + const res = await svc.reindexSource('bad'); + expect(res.ok).toBe(true); + expect(res.indexed).toBe(1); + expect(vec.upsertSpy).toHaveBeenCalledOnce(); + }); + + it('a published item (the loader, its store already started) is registered and indexed, named at error, refused on every search', async () => { + const { lines, logger } = logged(); + const find = vi.fn(async (_o: string, query: { where?: unknown }) => + query.where === undefined ? [{ id: 'r1', title: 'T1', notes: 'N1' }] : [], + ); + const svc = new KnowledgeService({ logger, dataEngine: { find } as unknown as IDataEngine }); + const vec = adapterOf('vec', { modes: ['vector'], default: 'vector' }); + // The loader runs at kernel:ready and on metadata:reloaded, after every store's start(). + svc.registerAdapter('vec', vec); + const loader = new KnowledgeSourceLoader({ + service: svc, + logger, + readItems: async () => [source('pkg_bad', 'vec', 'keyword'), source('pkg_good', 'vec')], + namespaceOf: () => undefined, + buildOnReload: false, + }); + const pass = await loader.reconcile('boot'); + expect(pass.added.sort()).toEqual(['pkg_bad', 'pkg_good']); + expect(svc.getSource('pkg_bad')).toBeDefined(); + expect(lines.filter(([level, m]) => level === 'warn' && m.includes('pkg_bad'))).toEqual([]); + + // Still indexes: the mode is read by search alone. + expect(await svc.reindexSource('pkg_bad')).toMatchObject({ ok: true, indexed: 1 }); + expect(vec.upsertSpy).toHaveBeenCalledOnce(); + + // 3 · the boot reading names it at error. + expect(svc.reportUnsupportedRetrieval()).toEqual(['pkg_bad']); + const errors = lines.filter(([level]) => level === 'error').map(([, m]) => m); + expect(errors).toHaveLength(1); + expect(errors[0]).toContain("[knowledge] source 'pkg_bad' is not searched: its `retrieval.mode` is 'keyword'"); + + // 4 · every search lists it in `refused` and never runs it. + const both = await svc.searchWithRefusals('q', { executionContext: SYSTEM }); + expect(both.hits.map((h) => h.sourceId)).toEqual(['pkg_good']); + expect(both.refused).toEqual([ + expect.objectContaining({ sourceId: 'pkg_bad', code: RETRIEVAL_UNSUPPORTED_CODE, status: 503 }), + ]); + expect(vec.searchSpy.mock.calls.map(([, o]) => (o as { source: KnowledgeSource }).source.name)).toEqual(['pkg_good']); + }); + + it('a source on a store not mounted is named by the unmounted reading, not this one', () => { + const { svc } = bootLike(); + svc.registerSource(source('s1', 'pgvector', 'keyword')); + expect(svc.reportUnsupportedRetrieval()).toEqual([]); + expect(svc.describeRetrieval(svc.getSource('s1')!)).toBeUndefined(); + }); + + it('the plugin takes the reading at kernel:bootstrapped, beside the unmounted-adapter reading', async () => { + const reading = vi.spyOn(KnowledgeService.prototype, 'reportUnsupportedRetrieval'); + try { + const kernel = new LiteKernel({ logger: { level: 'silent' } } as never); + kernel.use( + new KnowledgeServicePlugin({ + sources: [source('bad', 'vec', 'keyword'), source('good', 'vec')], + enableEventSync: false, + buildAtBoot: false, + }), + ); + kernel.use({ + name: 'test.late-store', + init: async () => undefined, + start: async (ctx) => { + ctx.getService('knowledge').registerAdapter('vec', adapterOf('vec', { modes: ['vector'], default: 'vector' })); + }, + }); + await kernel.bootstrap(); + expect(reading).toHaveBeenCalledTimes(1); + expect(reading.mock.results[0]?.value).toEqual(['bad']); + await kernel.shutdown(); + } finally { + reading.mockRestore(); + } + }); +}); + +describe('index_status carries each source\'s retrieval and each store\'s modes', () => { + it('the effective mode and its origin, the refusal, and "reports none" as an absent member', async () => { + const svc = new KnowledgeService(); + svc.registerSource(source('dflt', 'turso')); + svc.registerSource(source('bad', 'vec', 'keyword')); + svc.registerSource(source('plain', 'memory')); + svc.registerAdapter('turso', adapterOf('turso', { modes: ALL_MODES, default: 'hybrid' })); + svc.registerAdapter('vec', adapterOf('vec', { modes: ['vector'], default: 'vector' })); + svc.registerAdapter('memory', adapterOf('memory')); + const answer = await knowledgeIndexStatusActionHandler(svc)({ + namespace: 'knowledge', + actionId: 'index_status', + values: {}, + payload: {}, + ctx: {}, + } as never); + const details = (answer as { + details: { sources: Array<{ id: string; retrieval?: unknown }>; adapters: unknown; defaultAdapter?: string }; + }).details; + // Three stores and none marked the deployment's: a source naming none binds to none. + expect(details.defaultAdapter).toBeUndefined(); + const byId = Object.fromEntries(details.sources.map((s) => [s.id, s.retrieval])); + expect(byId.dflt).toEqual({ mode: 'hybrid', from: 'adapter', modes: ALL_MODES, default: 'hybrid' }); + expect(byId.bad).toEqual({ declared: 'keyword', refused: true, modes: ['vector'], default: 'vector' }); + expect(byId.plain).toEqual({}); + expect(details.adapters).toEqual([ + { id: 'turso', retrieval: { modes: ALL_MODES, default: 'hybrid' } }, + { id: 'vec', retrieval: { modes: ['vector'], default: 'vector' } }, + { id: 'memory' }, + ]); + }); + + it('names the store a source that names none binds to: the deployment\'s, else the only one', async () => { + const marked = new KnowledgeService({ deploymentAdapter: 'turso' }); + marked.registerAdapter('memory', adapterOf('memory')); + marked.registerAdapter('turso', adapterOf('turso', { modes: ALL_MODES, default: 'hybrid' })); + const only = new KnowledgeService(); + only.registerAdapter('memory', adapterOf('memory')); + const ask = { namespace: 'knowledge', actionId: 'index_status', values: {}, payload: {}, ctx: {} } as never; + const read = async (svc: KnowledgeService) => + ((await knowledgeIndexStatusActionHandler(svc)(ask)) as { details: { defaultAdapter?: string } }).details.defaultAdapter; + expect(await read(marked)).toBe('turso'); + expect(await read(only)).toBe('memory'); + }); +}); diff --git a/packages/services/service-knowledge/src/__tests__/search-uncoded-throw-38728.test.ts b/packages/services/service-knowledge/src/__tests__/search-uncoded-throw-38728.test.ts new file mode 100644 index 00000000000..fd766f2f8fd --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/search-uncoded-throw-38728.test.ts @@ -0,0 +1,145 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +// An adapter whose `search` throws without both an ADR-0112 `code` and `status` (an embedder that +// cannot be reached, a timeout outside the store) is refused for that source, +// never answered as zero hits: the caller reads a `refused` entry naming the +// source, coded SERVICE_UNAVAILABLE (503), under a platform sentence; the +// thrown message reaches the operator's `error` line only. + +import { describe, it, expect, vi } from 'vitest'; +import { KnowledgeService, SEARCH_FIRST_ROUND_FACTOR } from '../knowledge-service.js'; +import type { IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; + +const SYSTEM = { positions: [], permissions: [], isSystem: true }; +const INTERNAL = 'embedder down at http://10.0.0.7:11434 (key sk-secret)'; + +function source(name: string, adapter: string): KnowledgeSource { + return { + name, + label: name, + adapter, + source: { kind: 'object', object: 'task', content: ['title'], metadataFields: ['status'] } as ObjectKnowledgeSource, + }; +} + +function hit(sourceId: string, record: string, n = 0, score = 0.9): KnowledgeHit { + return { chunkId: `${sourceId}:${record}#${n}`, documentId: `${sourceId}:${record}`, sourceId, sourceRecordId: record, score, snippet: 'ok' }; +} + +function adapter(id: string, search: IKnowledgeAdapter['search']): IKnowledgeAdapter { + return { id, upsert: vi.fn(async () => undefined), delete: vi.fn(async () => undefined), search: vi.fn(search) }; +} + +function setup(adapters: IKnowledgeAdapter[]) { + const logger = { debug: vi.fn(), warn: vi.fn(), error: vi.fn() }; + const svc = new KnowledgeService({ logger: logger as never }); + for (const a of adapters) { + svc.registerAdapter(a.id, a); + svc.registerSource(source(a.id, a.id)); + } + return { svc, logger }; +} + +describe('knowledge search: an adapter throw without a code is refused for its source, never zero hits', () => { + it('a plain Error from search: one refused entry naming the source, SERVICE_UNAVAILABLE / 503; other sources still served', async () => { + const { svc, logger } = setup([ + adapter('failing', async () => { throw new Error(INTERNAL); }), + adapter('answering', async () => [hit('answering', 'r1')]), + ]); + const report = await svc.searchWithRefusals('q', { executionContext: SYSTEM }); + expect(report.hits.map((h) => h.documentId)).toEqual(['answering:r1']); + expect(report.refused).toHaveLength(1); + expect(report.refused[0]).toMatchObject({ sourceId: 'failing', code: 'SERVICE_UNAVAILABLE', status: 503 }); + // The caller's sentence names the source; the thrown text stays with the operator. + expect(report.refused[0].message).toContain("source 'failing'"); + expect(report.refused[0].message).not.toContain('10.0.0.7'); + expect(report.refused[0].message).not.toContain('sk-secret'); + expect(logger.error.mock.calls.some(([line]) => String(line).includes(INTERNAL))).toBe(true); + }); + + it('the only source throws uncoded: the search is refused whole, SERVICE_UNAVAILABLE / 503, not answered empty', async () => { + const { svc } = setup([adapter('failing', async () => { throw new Error(INTERNAL); })]); + const thrown = await svc.searchWithRefusals('q', { executionContext: SYSTEM }).then( + () => undefined, + (e: unknown) => e as { code?: string; status?: number; message: string; refused?: Array<{ sourceId: string; code: string }> }, + ); + expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(thrown?.refused).toEqual([expect.objectContaining({ sourceId: 'failing', code: 'SERVICE_UNAVAILABLE', status: 503 })]); + expect(thrown?.message).not.toContain('sk-secret'); + }); + + it('every searched source throws uncoded (an embedder outage): refused whole, 503, refused naming each', async () => { + const { svc } = setup([ + adapter('first', async () => { throw new Error(INTERNAL); }), + adapter('second', async () => { throw new Error(INTERNAL); }), + ]); + const thrown = await svc.searchWithRefusals('q', { executionContext: SYSTEM }).then( + () => undefined, + (e: unknown) => e as { code?: string; status?: number; message: string; refused?: Array<{ sourceId: string; code: string }> }, + ); + expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(thrown?.refused?.map((r) => [r.sourceId, r.code])).toEqual([ + ['first', 'SERVICE_UNAVAILABLE'], + ['second', 'SERVICE_UNAVAILABLE'], + ]); + expect(thrown?.message).not.toContain('sk-secret'); + }); + + it('an uncoded throw beside a coded refusal, none answering: refused names both, top-level code is the first in source order', async () => { + const { svc } = setup([ + adapter('failing', async () => { throw new Error(INTERNAL); }), + adapter('refusing', async () => { + throw Object.assign(new Error("Knowledge source 'refusing' needs a rebuild."), { code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 }); + }), + ]); + const thrown = await svc.searchWithRefusals('q', { executionContext: SYSTEM }).then( + () => undefined, + (e: unknown) => e as { code?: string; status?: number; message: string; refused?: Array<{ sourceId: string; code: string; status: number }> }, + ); + expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(thrown?.refused?.map((r) => [r.sourceId, r.code, r.status])).toEqual([ + ['failing', 'SERVICE_UNAVAILABLE', 503], + ['refusing', 'KNOWLEDGE_REBUILD_REQUIRED', 409], + ]); + }); + + it('a coded refusal is unchanged: its own code, status and message', async () => { + const { svc } = setup([ + adapter('refusing', async () => { + throw Object.assign(new Error("Knowledge source 'refusing' needs a rebuild."), { code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 }); + }), + adapter('answering', async () => [hit('answering', 'r1')]), + ]); + const report = await svc.searchWithRefusals('q', { executionContext: SYSTEM }); + expect(report.hits.map((h) => h.documentId)).toEqual(['answering:r1']); + expect(report.refused).toEqual([ + { sourceId: 'refusing', code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409, message: "Knowledge source 'refusing' needs a rebuild." }, + ]); + }); + + it('a source that matches nothing answers no hits and no refusal', async () => { + const { svc, logger } = setup([adapter('empty', async () => [])]); + const report = await svc.searchWithRefusals('q', { executionContext: SYSTEM }); + expect(report).toEqual({ hits: [], refused: [] }); + expect(logger.error).not.toHaveBeenCalled(); + }); + + it('a source that answers the first round and throws uncoded on the refill: refused once, its first-round hits dropped', async () => { + const topK = 5; + let calls = 0; + const { svc } = setup([ + // Round one fills its ask with passages of one record, so the record-level search refills it. + adapter('flaky', async () => { + calls += 1; + if (calls > 1) throw new Error(INTERNAL); + return Array.from({ length: topK * SEARCH_FIRST_ROUND_FACTOR }, (_, n) => hit('flaky', 'r0', n, 1 - n / 1000)); + }), + adapter('answering', async () => [hit('answering', 'r9', 0, 0.5)]), + ]); + const report = await svc.searchWithRefusals('q', { granularity: 'record', topK, executionContext: SYSTEM }); + expect(calls).toBe(2); + expect(report.hits.map((h) => h.sourceId)).toEqual(['answering']); + expect(report.refused).toEqual([expect.objectContaining({ sourceId: 'flaky', code: 'SERVICE_UNAVAILABLE', status: 503 })]); + }); +}); diff --git a/packages/services/service-knowledge/src/index.ts b/packages/services/service-knowledge/src/index.ts index 7b6e8f6ac82..0b68acfa628 100644 --- a/packages/services/service-knowledge/src/index.ts +++ b/packages/services/service-knowledge/src/index.ts @@ -64,10 +64,12 @@ export { knowledgeRebuildActionHandler, } from './knowledge-build-actions.js'; export type { + KnowledgeIndexStatusAdapter, KnowledgeIndexStatusBuild, KnowledgeIndexStatusEntry, KnowledgeIndexStatusQueue, } from './knowledge-build-actions.js'; +export type { KnowledgeRetrievalReading, RetrievalModeOrigin } from './knowledge-retrieval-mode.js'; export { KNOWLEDGE_SYNC_STATE_OBJECT, ObjectStoreKnowledgeSyncState } from './knowledge-sync-state.js'; export type { KnowledgeStoredBuild, diff --git a/packages/services/service-knowledge/src/knowledge-build-actions.ts b/packages/services/service-knowledge/src/knowledge-build-actions.ts index a8540c0f8bb..accd5719635 100644 --- a/packages/services/service-knowledge/src/knowledge-build-actions.ts +++ b/packages/services/service-knowledge/src/knowledge-build-actions.ts @@ -21,7 +21,10 @@ * build, with its counts while it runs and once it ended, and its record * syncs that failed and are not yet repaired. Beside the sources, the * record-sync messages waiting on the queue (`pendingRecordSyncs`, every - * source's together). + * source's together). [#38692 phase 1a] Each source's retrieval reading + * (`retrieval`: its effective mode and where it came from, the modes its + * store runs, a refusal), each mounted store's modes (`adapters`) and the + * store a source that names none binds to (`defaultAdapter`). * * Both run through the settings action door (`POST /api/settings/knowledge/ACTION`), * which gates an HTTP caller on the namespace's write permission, @@ -47,6 +50,8 @@ import type { import type { KnowledgeService, KnowledgeSourceDescription } from './knowledge-service.js'; import type { KnowledgeStoredBuild, KnowledgeSyncFailures } from './knowledge-sync-state.js'; import { KNOWLEDGE_RECORD_SYNC_QUEUE } from './knowledge-record-sync-queue.js'; +import type { KnowledgeRetrievalReading } from './knowledge-retrieval-mode.js'; +import type { KnowledgeRetrievalMode, KnowledgeSource } from '@objectstack/spec/ai'; /** The `knowledge` settings action that starts a rebuild of one source. */ export const KNOWLEDGE_REBUILD_ACTION = 'rebuild'; @@ -66,6 +71,9 @@ export type KnowledgeBuildActionsService = Pick< | 'syncStateOf' | 'hasDurableSyncState' | 'pendingRecordSyncs' + | 'describeRetrieval' + | 'listAdapters' + | 'getAdapter' >; /** One source in an `index_status` answer. */ @@ -88,6 +96,19 @@ export interface KnowledgeIndexStatusEntry { failures: KnowledgeSyncFailures | null; /** Why the sync state could not be read; absent when it was. */ syncStateError?: string; + /** + * The source's retrieval mode (#38692 phase 1a): the mode its searches run + * and where it came from, the modes its adapter runs, and whether its + * searches are refused. Absent while its adapter is not placed or mounted. + */ + retrieval?: KnowledgeRetrievalReading; +} + +/** One mounted adapter in an `index_status` answer, and the retrieval modes it reports. */ +export interface KnowledgeIndexStatusAdapter { + id: string; + /** The modes it runs and its default; absent: it reports none (Studio shows "驱动未声明"). */ + retrieval?: { modes: KnowledgeRetrievalMode[]; default: KnowledgeRetrievalMode }; } /** @@ -327,6 +348,7 @@ export function knowledgeIndexStatusActionHandler(service: KnowledgeBuildActions const sources: KnowledgeIndexStatusEntry[] = []; for (const source of targets) { const adapter = service.boundAdapterId(source.source); + const retrieval = service.describeRetrieval(source.source); sources.push({ id: source.id, label: source.source.label, @@ -334,8 +356,16 @@ export function knowledgeIndexStatusActionHandler(service: KnowledgeBuildActions ...(source.packageId === undefined ? {} : { packageId: source.packageId }), index: await service.readIndexState(source.id), ...(await readSyncState(service, source.id)), + ...(retrieval === undefined ? {} : { retrieval }), }); } + // The store a source that names none binds to (ADR-0161 K4), for a form + // that shows a new source's retrieval modes before it names a store. + const defaultAdapter = service.boundAdapterId({ name: '', label: '' } as unknown as KnowledgeSource); + const adapters: KnowledgeIndexStatusAdapter[] = service.listAdapters().map((id) => { + const report = service.getAdapter(id).capabilities?.retrieval; + return { id, ...(report === undefined ? {} : { retrieval: { modes: [...report.modes], default: report.default } }) }; + }); const queue = await readQueue(service); const due = sources.filter((s) => s.index.due).length; const running = sources.filter((s) => s.build?.status === 'running').length; @@ -345,7 +375,12 @@ export function knowledgeIndexStatusActionHandler(service: KnowledgeBuildActions ok: true, severity: 'info', message: `${sources.length} source(s): ${due} need a build, ${running} building, ${failing} with failed syncs${pending}.`, - details: { sources, ...(queue === undefined ? {} : { queue }) }, + details: { + sources, + adapters, + ...(defaultAdapter === undefined ? {} : { defaultAdapter }), + ...(queue === undefined ? {} : { queue }), + }, }; }; } diff --git a/packages/services/service-knowledge/src/knowledge-retrieval-mode.ts b/packages/services/service-knowledge/src/knowledge-retrieval-mode.ts new file mode 100644 index 00000000000..b36da162126 --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-retrieval-mode.ts @@ -0,0 +1,138 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A source's retrieval mode (ADR-0161, the dated note of 2026-11-30 under K8; + * ruling 7270218011 on #38692, phase 1a): which mode a search of the source + * runs, where that came from, and the refusal of a mode its adapter does not + * run. + * + * ## The effective mode + * + * The source's declaration (`source.retrieval.mode`), else the adapter's + * reported default (`capabilities.retrieval.default`). An adapter that + * reports no modes is never told one: a source on it that declares none is + * searched as before, and one that declares a mode is refused. + * + * ## The four refusal points + * + * A source that declares a mode its adapter does not list is refused, never + * searched another way: + * + * 1. at an author's save (Studio, REST, an MCP draft): `400 + * VALIDATION_ERROR`, listing the modes the adapter runs + * (`admitAuthoredSource`); + * 2. at registration in code, only when its adapter already resolves — a + * store registers in its own `start()`, after a source registered at + * `init()`, so "not registered yet" is no verdict (AGENTS.md, startup + * registry reads) (`registerSource`). 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 3 and 4 hold + * it (`registerMetadataSource`); + * 3. once after boot, at `error`, naming the source and the modes + * (`reportUnsupportedRetrieval`, beside `reportUnmountedAdapters`); + * 4. on every search: the source is listed in `refused` with + * {@link RETRIEVAL_UNSUPPORTED_CODE}, as a source whose adapter is not + * mounted is (`planSearches`). + * + * Such a source still builds and syncs its index: the mode is read by search + * alone, so changing it rebuilds nothing. + */ + +import type { KnowledgeRetrievalMode, KnowledgeSource } from '@objectstack/spec/ai'; +import type { IKnowledgeAdapter } from '@objectstack/spec/contracts'; + +/** + * The code of a search refused because the source declares a mode its + * adapter does not run: the code a source whose adapter is not mounted is + * refused with, since in both the deployment cannot serve the source as + * written (`503`). + */ +export const RETRIEVAL_UNSUPPORTED_CODE = 'SERVICE_UNAVAILABLE'; + +/** Where a search's effective mode came from. */ +export type RetrievalModeOrigin = 'source' | 'adapter'; + +/** {@link resolveRetrievalMode}'s answer. */ +export type RetrievalResolution = + /** Searched in `mode`, from `from`; absent `mode`: the adapter reports no modes and none is declared. */ + | { refused: false; mode?: KnowledgeRetrievalMode; from?: RetrievalModeOrigin } + /** The source declares `declared`, which the adapter does not list (`modes`; absent: it reports none). */ + | { refused: true; declared: KnowledgeRetrievalMode; modes?: readonly KnowledgeRetrievalMode[] }; + +/** + * A source's retrieval as the operator reads it (the `index_status` entry's + * `retrieval`): never in a search's answer to the caller. + */ +export interface KnowledgeRetrievalReading { + /** The mode the source declares; absent: it declares none. */ + declared?: KnowledgeRetrievalMode; + /** The mode its searches run; absent when refused, or when the adapter reports no modes and none is declared. */ + mode?: KnowledgeRetrievalMode; + /** Where {@link mode} came from. */ + from?: RetrievalModeOrigin; + /** The modes its adapter runs; absent: the adapter reports none (Studio shows "驱动未声明"). */ + modes?: readonly KnowledgeRetrievalMode[]; + /** Its adapter's default mode; absent with {@link modes}. */ + default?: KnowledgeRetrievalMode; + /** Every search of it is refused with {@link RETRIEVAL_UNSUPPORTED_CODE}: it declares a mode its adapter does not run. */ + refused?: true; +} + +/** {@link KnowledgeRetrievalReading} of `source` on `adapter`. */ +export function readRetrieval(source: Pick, adapter: IKnowledgeAdapter): KnowledgeRetrievalReading { + const report = adapter.capabilities?.retrieval; + const declared = declaredRetrievalMode(source); + const resolved = resolveRetrievalMode(source, adapter); + return { + ...(declared === undefined ? {} : { declared }), + ...(resolved.refused ? { refused: true as const } : {}), + ...(!resolved.refused && resolved.mode !== undefined ? { mode: resolved.mode, from: resolved.from } : {}), + ...(report === undefined ? {} : { modes: [...report.modes], default: report.default }), + }; +} + +/** The mode `source` declares, if any (`retrieval: {}` declares none). */ +export function declaredRetrievalMode(source: Pick): KnowledgeRetrievalMode | undefined { + return source.source?.retrieval?.mode; +} + +/** The effective mode of a search of `source` on `adapter`, or the refusal (see the module header). */ +export function resolveRetrievalMode(source: Pick, adapter: IKnowledgeAdapter): RetrievalResolution { + const report = adapter.capabilities?.retrieval; + const declared = declaredRetrievalMode(source); + if (declared === undefined) { + return report === undefined ? { refused: false } : { refused: false, mode: report.default, from: 'adapter' }; + } + if (report === undefined || !report.modes.includes(declared)) { + return { refused: true, declared, ...(report === undefined ? {} : { modes: report.modes }) }; + } + return { refused: false, mode: declared, from: 'source' }; +} + +/** The modes an adapter runs, as a sentence part: `'vector', 'keyword' and 'hybrid' (default 'hybrid')`, or that it reports none. */ +export function adapterModesText(adapterId: string, modes: readonly KnowledgeRetrievalMode[] | undefined, byDefault?: KnowledgeRetrievalMode): string { + if (modes === undefined || modes.length === 0) return `the store '${adapterId}' reports no retrieval modes, so a source on it may only leave \`retrieval.mode\` out`; + const listed = modes.map((m) => `'${m}'`); + const joined = listed.length === 1 ? listed[0] : `${listed.slice(0, -1).join(', ')} and ${listed[listed.length - 1]}`; + return `the store '${adapterId}' runs ${joined}${byDefault === undefined ? '' : ` (default '${byDefault}')`}`; +} + +/** + * Why a source declaring `declared` is refused on `adapterId`, and what to + * write: the rule, then the remedies. One text for every point; each point + * puts its own subject before it and its own consequence after it. + */ +export function retrievalRefusalText( + adapterId: string, + declared: KnowledgeRetrievalMode, + adapter: IKnowledgeAdapter, +): string { + const report = adapter.capabilities?.retrieval; + const remedies = report === undefined || report.modes.length === 0 + ? 'Remove `retrieval.mode`, or bind the source to a store that runs it' + : `Write one of ${report.modes.map((m) => `'${m}'`).join(', ')} as \`retrieval.mode\`, or remove it for the store's default, or bind the source to a store that runs '${declared}'`; + return ( + `its \`retrieval.mode\` is '${declared}', and ${adapterModesText(adapterId, report?.modes, report?.default)}; ` + + `a source is never searched in a mode other than the one it declares. ${remedies}.` + ); +} diff --git a/packages/services/service-knowledge/src/knowledge-service-admission.ts b/packages/services/service-knowledge/src/knowledge-service-admission.ts index eef37eca116..b1411c77172 100644 --- a/packages/services/service-knowledge/src/knowledge-service-admission.ts +++ b/packages/services/service-knowledge/src/knowledge-service-admission.ts @@ -65,6 +65,7 @@ import { unplacedSourceText, } from './knowledge-service-top-level.js'; import type { KnowledgeService } from './knowledge-service.js'; +import { resolveRetrievalMode, retrievalRefusalText } from './knowledge-retrieval-mode.js'; /** * The `KnowledgeService` members the bodies in this module read: every one @@ -75,7 +76,9 @@ import type { KnowledgeService } from './knowledge-service.js'; * body here assigns. */ export interface KnowledgeAdmissionHost { + readonly adapters: KnowledgeService['adapters']; readonly admissionDeps: KnowledgeService['admissionDeps']; + readonly boundAdapterId: KnowledgeService['boundAdapterId']; readonly handed: KnowledgeService['handed']; readonly handedSources: KnowledgeService['handedSources']; readonly held: KnowledgeService['held']; @@ -192,7 +195,14 @@ export function admissionDeps( export async function admitAuthoredSource( this: Pick< KnowledgeAdmissionHost, - 'admissionDeps' | 'held' | 'listAdapters' | 'options' | 'reportGateFailure' | 'unmountedAdapterSaveText' + | 'adapters' + | 'admissionDeps' + | 'boundAdapterId' + | 'held' + | 'listAdapters' + | 'options' + | 'reportGateFailure' + | 'unmountedAdapterSaveText' >, item: unknown, ctx: ExecutionContext | undefined, @@ -255,6 +265,22 @@ export async function admitAuthoredSource( if (typeof authoredAdapter === 'string' && !registeredAdapters.includes(authoredAdapter)) { return refuse(400, 'VALIDATION_ERROR', `${named}: ${this.unmountedAdapterSaveText(authoredAdapter, registeredAdapters, wording.again)}`); } + // [ADR-0161, the dated note of 2026-11-30 under K8; refusal point 1] A source + // that declares a retrieval mode its store does not run is refused at its + // save, listing the modes the store runs. The store is the one it names, + // else the deployment's: both are registered by now (above). A mode + // outside the three is the parse's to refuse. + const declaredMode = (declared as { retrieval?: { mode?: unknown } }).retrieval?.mode; + if (declaredMode === 'vector' || declaredMode === 'keyword' || declaredMode === 'hybrid') { + const adapterId = this.boundAdapterId({ adapter: typeof authoredAdapter === 'string' ? authoredAdapter : undefined } as KnowledgeSource); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + if (adapterId !== undefined && adapter !== undefined) { + const resolved = resolveRetrievalMode({ source: { retrieval: { mode: declaredMode } } } as KnowledgeSource, adapter); + if (resolved.refused) { + return refuse(400, 'VALIDATION_ERROR', `${named}: ${retrievalRefusalText(adapterId, declaredMode, adapter)}`); + } + } + } const engine = this.options.dataEngine; if (!engine) return unavailable('the knowledge service has no data engine'); diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts index db57d22e7a8..c129dc6dbc8 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -782,11 +782,13 @@ export class KnowledgeServicePlugin implements Plugin { } }); // Every store registers its adapter in its own start(), so the reading of - // which sources name an unmounted one is taken once all have started. + // which sources name an unmounted one, or a retrieval mode their store + // does not run, is taken once all have started. // Held, the one line of the held state names what is missing instead. ctx.hook('kernel:bootstrapped', () => { if (this.service?.heldReading()) return; this.service?.reportUnmountedAdapters(); + this.service?.reportUnsupportedRetrieval(); }); // [ADR-0161 K1] The daily reconcile. The job service may start after this // plugin: it is resolved once every plugin has started, when an absent diff --git a/packages/services/service-knowledge/src/knowledge-service-search.ts b/packages/services/service-knowledge/src/knowledge-service-search.ts index e2d2e8e440d..8a55d42a68b 100644 --- a/packages/services/service-knowledge/src/knowledge-service-search.ts +++ b/packages/services/service-knowledge/src/knowledge-service-search.ts @@ -38,6 +38,7 @@ import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; import type { TenancyPosture } from '@objectstack/spec/security'; import { refusal } from './knowledge-tools.js'; +import { RETRIEVAL_UNSUPPORTED_CODE, resolveRetrievalMode, retrievalRefusalText } from './knowledge-retrieval-mode.js'; import { type AffinityCallerFacts, affinityFactNeeds, @@ -62,6 +63,7 @@ import { SEARCH_FRESHNESS_ROUNDS, SEARCH_REFILL_FACTOR, type SearchTarget, + UNMOUNTED_ADAPTER_CODE, UNPROVEN_CALLER_TEXT, UNPROVEN_OPERATOR_TEXT, type UnprovenEnd, @@ -777,6 +779,33 @@ export async function planSearches( out.push({ ...entry, binding: { refusal: codedRefusalOf(err) } }); continue; } + // [#38692 phase 1a] The effective retrieval mode: the source's + // declaration, else the adapter's default. A declared mode the adapter + // does not run is refused like an adapter that cannot serve, never + // searched another way; the boot said so at `error` + // (`reportUnsupportedRetrieval`). The mode and where it came from are the + // operator's, at `debug`, never the caller's answer. + const retrieval = resolveRetrievalMode(entry.source, adapter); + if (retrieval.refused) { + out.push({ + ...entry, + binding: { + refusal: { + code: RETRIEVAL_UNSUPPORTED_CODE, + status: 503, + message: `Knowledge source '${this.label(entry.source)}' is not searched: ` + + retrievalRefusalText(adapterId, retrieval.declared, adapter), + }, + }, + }); + continue; + } + if (retrieval.mode !== undefined) { + this.options.logger?.debug?.( + `[knowledge] source '${this.label(entry.source)}' searched in '${retrieval.mode}' mode ` + + `(${retrieval.from === 'source' ? 'declared by the source' : `the default of adapter '${adapterId}'`}).`, + ); + } const plan = await this.planIndex(entry.source, adapter, chunkTarget); if (proveIndex === true) { const unproven = await this.unprovenIndex(plan); @@ -803,6 +832,7 @@ export async function planSearches( binding: { adapterId, adapter }, fingerprint: plan.index.fingerprint, ...(proveIndex === true ? { verifyHits: true as const } : {}), + ...(retrieval.mode === undefined ? {} : { retrieval: { mode: retrieval.mode } }), }); } return out; @@ -888,8 +918,12 @@ export async function unprovenIndex(plan: IndexPlan): Promise<{ why: string; end * the adapter returned (`answered`, before a hit naming another source or * outside the scope is dropped — what decides whether the adapter may hold * more). A source whose adapter is unknown or throws is absent from the - * answer: a coded refusal (ADR-0112 `code` and `status`) is added to - * `refused`, anything else is logged. + * answer and named in `refused`, never answered as no hits: a coded refusal + * (ADR-0112 `code` and `status`) keeps its code and message; any other throw + * (an embedder that cannot be reached, a timeout outside the store) is + * refused as ADR-0112 `SERVICE_UNAVAILABLE` (503) under a platform sentence + * naming the source, and its own message goes to the operator's `error` line + * only. * * Under a scope, the adapter is handed the source's terms, and every hit it * answers is checked against them ({@link scopeCheck}, fail closed). The first @@ -908,7 +942,7 @@ export async function searchRound( refused: KnowledgeSearchRefusal[], ): Promise> { const out = new Map(); - for (const { source, organizationIds, fingerprint, scope, binding } of sources) { + for (const { source, organizationIds, fingerprint, scope, binding, retrieval } of sources) { // Refused like an adapter that cannot serve: the caller is told which // source was not searched and why; the boot said so at `error` // (`reportUnmountedAdapters`), so no line per search. The adapter was @@ -927,6 +961,7 @@ export async function searchRound( ...(organizationIds === undefined ? {} : { organizationIds }), ...(fingerprint === undefined ? {} : { index: { fingerprint } }), ...(scope === undefined ? {} : { scope: scope.map((term) => ({ ...term, ids: [...term.ids] })) }), + ...(retrieval === undefined ? {} : { retrieval: { mode: retrieval.mode } }), }); // A hit is served as the source it was searched for. One whose // `sourceId` names another source (an adapter answering from a store @@ -956,6 +991,16 @@ export async function searchRound( ); continue; } + // Refused like an adapter that cannot serve, never answered as zero + // hits: the caller is told which source was not searched. The thrown + // message can carry hosts, SQL or keys, so the caller reads a platform + // sentence; the operator reads the adapter's own text here. + refused.push({ + sourceId: source.name, + code: UNMOUNTED_ADAPTER_CODE, + status: 503, + message: `[knowledge] source '${this.label(source)}' could not be searched: its adapter '${adapterId}' failed.`, + }); this.options.logger?.error?.( `[knowledge] adapter '${adapterId}' search failed for source '${this.label(source)}': ${(err as Error).message}`, ); diff --git a/packages/services/service-knowledge/src/knowledge-service-sources.ts b/packages/services/service-knowledge/src/knowledge-service-sources.ts index a46f5c61400..d82fce85087 100644 --- a/packages/services/service-knowledge/src/knowledge-service-sources.ts +++ b/packages/services/service-knowledge/src/knowledge-service-sources.ts @@ -8,7 +8,10 @@ * `onSourcesChanged`, `sourcesChanged`, `unregisterSource`, `dropMetadataSource`, * `forget`, `listSources`, `describeSources`, `getSource`, `describeSource`, * `handed`, `handedSources`, `adapterLabel`, `faceOfKey`, `requireEntry`, moved - * out of `knowledge-service.ts` whole. + * out of `knowledge-service.ts` whole. `reportUnsupportedRetrieval`, `describeRetrieval` and + * the registration refusal beside them were written here (#38692 phase 1a), the + * retrieval-mode counterparts of `reportUnmountedAdapters` and + * `refuseUnplacedSource`. * * A MOVE, not a redesign. Each function below is the body of the * `KnowledgeService` member of the same name as it stood, re-indented one @@ -51,6 +54,13 @@ import { unplacedSourceError, } from './knowledge-service-top-level.js'; import type { KnowledgeService } from './knowledge-service.js'; +import { + type KnowledgeRetrievalReading, + RETRIEVAL_UNSUPPORTED_CODE, + readRetrieval, + resolveRetrievalMode, + retrievalRefusalText, +} from './knowledge-retrieval-mode.js'; /** * The `KnowledgeService` members the bodies in this module read: every one @@ -187,6 +197,72 @@ export function reportUnmountedAdapters( return named; } +/** + * Refuse, at registration in code, a source that declares a retrieval mode its + * adapter does not run (#38692 phase 1a, refusal point 2) — only when that + * adapter already resolves: a store registers in its own `start()`, after a + * source registered at `init()`, so "not registered yet" is no verdict + * (AGENTS.md, startup registry reads). The boot's reading + * ({@link reportUnsupportedRetrieval}) and every search hold the rest. + * + * The code door alone: a published `knowledge_source` item (a package + * install, the stack's `knowledgeSources`, a peer's write) meets no save, and + * the loader always runs after every store has started, so a refusal there + * would drop the item whole. It is registered and indexed as any other, and + * points 3 and 4 hold it: named at `error` after boot, refused on every + * search. + */ +function refuseUnsupportedRetrieval( + this: Pick, + source: KnowledgeSource, + door: string, +): void { + if (source.source?.retrieval?.mode === undefined) return; + const adapterId = this.boundAdapterId(source); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + if (adapterId === undefined || adapter === undefined) return; + const resolved = resolveRetrievalMode(source, adapter); + if (!resolved.refused) return; + throw codedError( + 'VALIDATION_ERROR', + 400, + `[knowledge] ${door} refused source '${source.name}': ${retrievalRefusalText(adapterId, resolved.declared, adapter)}`, + ); +} + +/** The body of {@link KnowledgeService.reportUnsupportedRetrieval}; the member's docblock there is its contract. */ +export function reportUnsupportedRetrieval( + this: Pick, +): string[] { + const named: string[] = []; + for (const { id, source } of this.describeSources()) { + if (source.source?.retrieval?.mode === undefined) continue; + // A source this boot cannot place, or whose adapter is not mounted, is + // named by `reportUnmountedAdapters`; its mode has no adapter to read. + const adapterId = this.boundAdapterId(source); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + if (adapterId === undefined || adapter === undefined) continue; + const resolved = resolveRetrievalMode(source, adapter); + if (!resolved.refused) continue; + this.options.logger?.error?.( + `[knowledge] source '${id}' is not searched: ${retrievalRefusalText(adapterId, resolved.declared, adapter)} ` + + `Every search of it answers ${RETRIEVAL_UNSUPPORTED_CODE} until then; it is still indexed.`, + ); + named.push(id); + } + return named; +} + +/** The body of {@link KnowledgeService.describeRetrieval}; the member's docblock there is its contract. */ +export function describeRetrieval( + this: Pick, + source: KnowledgeSource, +): KnowledgeRetrievalReading | undefined { + const adapterId = this.boundAdapterId(source); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + return adapter === undefined ? undefined : readRetrieval(source, adapter); +} + /** The body of {@link KnowledgeService.listAdapters}; the member's docblock there is its contract. */ export function listAdapters(this: Pick): string[] { return [...this.adapters.keys()]; @@ -194,7 +270,10 @@ export function listAdapters(this: Pick): stri /** The body of {@link KnowledgeService.registerSource}; the member's docblock there is its contract. */ export function registerSource( - this: Pick, + this: Pick< + KnowledgeSourcesHost, + 'adapterLabel' | 'adapters' | 'boundAdapterId' | 'options' | 'refuseUnplacedSource' | 'registry' | 'sourcesChanged' + >, source: KnowledgeSource, ): void { const parsed = parseKnowledgeSource(source); @@ -206,6 +285,7 @@ export function registerSource( ); } this.refuseUnplacedSource(parsed.source, 'registerSource'); + refuseUnsupportedRetrieval.call(this, parsed.source, 'registerSource'); const packageId = packageIdOfItem(parsed.source); if (packageId !== undefined) { throw codedError( @@ -224,11 +304,17 @@ export function registerSource( /** The body of {@link KnowledgeService.registerMetadataSource}; the member's docblock there is its contract. */ export function registerMetadataSource( - this: Pick, + this: Pick< + KnowledgeSourcesHost, + 'adapterLabel' | 'adapters' | 'boundAdapterId' | 'options' | 'refuseUnplacedSource' | 'registry' | 'sourcesChanged' + >, source: KnowledgeSource, holder: KnowledgeSourceHolder = {}, ): KnowledgeSourceEntry { this.refuseUnplacedSource(source, 'The knowledge_source loader'); + // A mode its store does not run is not refused here (see + // refuseUnsupportedRetrieval): the item is registered and indexed, and the + // boot's reading and every search refuse it. const { entry, replaced } = this.registry.register(source, 'metadata', holder); this.options.logger?.info?.( `[knowledge] source ${replaced ? 'reloaded' : 'registered'}: ${entry.face} (adapter=${this.adapterLabel(entry.authored)}` + diff --git a/packages/services/service-knowledge/src/knowledge-service-top-level.ts b/packages/services/service-knowledge/src/knowledge-service-top-level.ts index 21c8398272a..dc0dc0034e5 100644 --- a/packages/services/service-knowledge/src/knowledge-service-top-level.ts +++ b/packages/services/service-knowledge/src/knowledge-service-top-level.ts @@ -22,7 +22,13 @@ import type { IQueueService, } from '@objectstack/spec/contracts'; import type { ExecutionContext } from '@objectstack/spec/kernel'; -import type { KnowledgeDocument, KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { + KnowledgeDocument, + KnowledgeHit, + KnowledgeRetrievalMode, + KnowledgeSource, + ObjectKnowledgeSource, +} from '@objectstack/spec/ai'; import { collectCredentialWriteResponseFields, collectInternalWriteResponseFields } from '@objectstack/core'; import { type TenancyPosture, postureEnforcesWall } from '@objectstack/spec/security'; import { resolveInjectedSystemColumns } from '@objectstack/spec/data'; @@ -281,15 +287,22 @@ export function describeName(input: unknown): string { /** * A source that refused a search (ADR-0161 K7, rule 5): its adapter answered * an ADR-0112 coded error — `KNOWLEDGE_REBUILD_REQUIRED` when its index holds - * another fingerprint than the one the search carried. + * another fingerprint than the one the search carried — or threw without both + * an ADR-0112 `code` and `status`. For such an uncoded throw, `code`, `status` + * and `message` are the platform's (`SERVICE_UNAVAILABLE`, 503, a sentence + * naming the source), and the message is deliberately not the adapter's text, + * which goes to the operator's `error` line only. */ export interface KnowledgeSearchRefusal { sourceId: string; - /** The adapter's error code. */ + /** The adapter's error code; `SERVICE_UNAVAILABLE` for an uncoded throw. */ code: string; - /** The adapter's HTTP-shaped status. */ + /** The adapter's HTTP-shaped status; 503 for an uncoded throw. */ status: number; - /** The adapter's message, which says what to do. */ + /** + * The adapter's message, which says what to do; for an uncoded throw, the + * platform's sentence naming the source, never the adapter's text. + */ message: string; } @@ -353,6 +366,11 @@ export interface SearchTarget { scope?: AdapterScopeTerm[]; /** Each hit is checked against its live record before it is served ({@link KnowledgeService.dropUnverifiedHits}). */ verifyHits?: true; + /** + * The effective retrieval mode the adapter is told (`knowledge-retrieval-mode.ts`): + * absent where the adapter reports no modes and the source declares none. + */ + retrieval?: { mode: KnowledgeRetrievalMode }; } /** An ADR-0112 coded refusal's code, status and message, or `undefined` for any other thrown value. */ diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 1382ceaf226..18477e18481 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -22,6 +22,7 @@ import { } from './knowledge-source-registry.js'; import type { KnowledgeAdmissionDeps } from './knowledge-source-admission.js'; import type { SearchScopeEntry } from './knowledge-search-scope.js'; +import type { KnowledgeRetrievalReading } from './knowledge-retrieval-mode.js'; import type { KnowledgeBuildFence, KnowledgeBuildProgress, @@ -285,6 +286,28 @@ export class KnowledgeService implements IKnowledgeService { return KnowledgeSourcesFacet.reportUnmountedAdapters.call(knowledgeServiceHost.of(this)); } + /** + * Say once, at `error`, which registered sources declare a retrieval mode + * (`source.retrieval.mode`) their mounted adapter does not run — the boot's + * reading, taken beside {@link reportUnmountedAdapters} (#38692 phase 1a, + * refusal point 3). Every search of such a source lists it in `refused`; + * it is still indexed. Answers the sources named. + */ + reportUnsupportedRetrieval(): string[] { + return KnowledgeSourcesFacet.reportUnsupportedRetrieval.call(knowledgeServiceHost.of(this)); + } + + /** + * `source`'s retrieval mode as the operator reads it: the mode it declares, + * the one its searches run and where that came from, the modes its adapter + * runs, and whether its searches are refused (`knowledge-retrieval-mode.ts`). + * `undefined` while its adapter is not placed or not mounted. For a status + * answer, never for a search's answer. + */ + describeRetrieval(source: KnowledgeSource): KnowledgeRetrievalReading | undefined { + return KnowledgeSourcesFacet.describeRetrieval.call(knowledgeServiceHost.of(this), source); + } + listAdapters(): string[] { return KnowledgeSourcesFacet.listAdapters.call(knowledgeServiceHost.of(this)); } @@ -978,16 +1001,21 @@ export class KnowledgeService implements IKnowledgeService { * Each source is searched under the fingerprint the service expects of its * index ({@link planIndex}). An adapter whose index holds another — the * source needs a rebuild, or is being rebuilt — refuses with an ADR-0112 - * coded error, and so may any adapter for a reason it codes. A coded refusal - * is not logged and dropped like a failure: the sources that can be searched - * answer, and when NONE can, the call is refused whole — this method throws - * a coded error naming each refused source with its code. When some answer, + * coded error, and so may any adapter for a reason it codes. An adapter + * that throws without both an ADR-0112 `code` and `status` (an embedder + * that cannot be reached, a timeout outside the store) is refused too, as + * `SERVICE_UNAVAILABLE` (503) under a platform sentence naming the source; + * its own message goes to the operator's `error` line only. No refused + * source is answered as no hits: the sources that can be searched answer, + * and when NONE can, the call is refused whole — this method throws a coded + * error naming each refused source with its code, its own `code` and + * `status` those of the first refusal in source order. When some answer, * the hits are theirs. A source that answers the first round and refuses the * refill is refused for the whole search, its first-round hits dropped: no - * source is both answered and named as refused. A refused source is named - * with its code and the adapter's one-sentence message; the adapter's - * `remedy`, operator text such as the SQL to run, goes to the `warn` log - * with it and never to the caller. The + * source is both answered and named as refused. A source refused with a + * code is named with that code and the adapter's one-sentence message; the + * adapter's `remedy`, operator text such as the SQL to run, goes to the + * `warn` log with it and never to the caller. The * return type of `IKnowledgeService.search` has no place to name them, so a * caller that must name them to its own caller (the `search_knowledge` tool) * reads {@link searchWithRefusals}. @@ -998,10 +1026,11 @@ export class KnowledgeService implements IKnowledgeService { /** * {@link search}, answering the refused sources beside the hits: each - * source whose adapter refused with an ADR-0112 coded error, with its code. - * Throws a coded error when no source could be searched and at least one - * refused (the call refused whole, ADR-0161 K7, rule 5); the thrown error's - * `refused` lists them all. + * source whose adapter refused with an ADR-0112 coded error, with its code, + * and each whose adapter threw without one, as `SERVICE_UNAVAILABLE` (503) + * under a platform sentence. Throws a coded error when no source could be + * searched and at least one refused (the call refused whole, ADR-0161 K7, + * rule 5); the thrown error's `refused` lists them all. */ searchWithRefusals(query: string, opts?: KnowledgeSearchOptions): Promise { return KnowledgeSearchFacet.searchWithRefusals.call(knowledgeServiceHost.of(this), query, opts); diff --git a/packages/services/service-knowledge/src/knowledge-tools.ts b/packages/services/service-knowledge/src/knowledge-tools.ts index 9cab070bb5a..698fa0dc008 100644 --- a/packages/services/service-knowledge/src/knowledge-tools.ts +++ b/packages/services/service-knowledge/src/knowledge-tools.ts @@ -142,7 +142,12 @@ export interface SearchKnowledgeHit { title?: string; /** The passage that matched. */ snippet: string; - /** Relevance, higher is better. */ + /** + * The hit's order among the hits of its own source in the store's ranking: not a + * measure of relevance, and not comparable across sources (ADR-0161, the + * dated note of 2026-11-30 under K8). Under a one-leg mode it reflects rank + * alone, and the first hit scores 1. + */ score: number; /** The record the passage was indexed from: read it with the record tools. */ record?: { object: string; id: string }; @@ -170,14 +175,18 @@ export interface SearchKnowledgeHit { /** * A source that could not be searched for this call (ADR-0161 K7, rule 5): * its index needs a rebuild, or is being rebuilt, or its store refused for - * another coded reason. Its passages are missing from `hits` — not absent + * another coded reason, or its adapter failed without a code (answered as + * `SERVICE_UNAVAILABLE`). Its passages are missing from `hits` — not absent * from the source. */ export interface SearchKnowledgeRefusedSource { sourceId: string; /** The refusal's ADR-0112 code, e.g. `KNOWLEDGE_REBUILD_REQUIRED`. */ code: string; - /** What the store said. */ + /** + * What the store said; for an adapter that failed without a code, the + * platform's sentence naming the source, never the adapter's own text. + */ message: string; } @@ -222,7 +231,8 @@ const SEARCH_KNOWLEDGE_DESCRIPTION = 'Search the knowledge sources this app indexes (policies, manuals, articles, records indexed for retrieval) by ' + 'meaning, and answer with the most relevant passages, each naming its source and, for an indexed record, the ' + 'record it came from. Use it before answering a question the app\'s own documents or knowledge base should ' - + 'answer, and cite the passages you used. Send `query` as a short natural-language statement of what you are ' + + 'answer, and cite the passages you used. A hit\'s `score` says only its order among the hits of its own ' + + 'source, not how relevant it is. Send `query` as a short natural-language statement of what you are ' + 'looking for. Omit `sourceIds` to search every source; every answer lists the sources this tool may search, ' + 'and `sourceIds` takes their ids. `topK` caps the passages (default ' + `${SEARCH_KNOWLEDGE_DEFAULT_TOP_K}, at most ${SEARCH_KNOWLEDGE_MAX_TOP_K}). Only passages the caller may read ` diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index f4e41c3d050..55202a5f3ca 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -79,6 +79,10 @@ * (`capabilities.retrieval`), and the same fixture is searched under each * mode it lists: `vector` leaves that passage out, `keyword` answers it * alone, and the default handed explicitly answers what no mode answers. + * Through a real `KnowledgeService`, every adapter is handed the mode a + * source declares, or its own default, or nothing when it reports no modes; + * a declared mode it does not list is refused at registration and at every + * search, and the source still indexes. */ import { describe, expect, it, vi } from 'vitest'; @@ -90,7 +94,7 @@ import type { AdapterScopeTerm, AdapterSearchOptions, } from '@objectstack/spec/contracts'; -import type { KnowledgeDocument, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { KnowledgeDocument, KnowledgeRetrievalMode, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; import { KNOWLEDGE_RETRIEVAL_MODES } from '@objectstack/spec/ai'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { TenancyPosture } from '@objectstack/spec/security'; @@ -708,6 +712,74 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); } + // objectstack#38692 phase 1a. + describe('the retrieval mode through KnowledgeService.search', () => { + const ROWS: Row[] = [{ id: 'r1', body: 'alpine meadow harbour', status: 'published' }]; + const withMode = (id: string, mode?: KnowledgeRetrievalMode): KnowledgeSource => + objectSource(id, mode === undefined ? {} : { retrieval: { mode } }); + + it('no mode declared: the adapter is handed its own default, or nothing when it reports no modes', async () => { + const source = withMode('mode_default'); + const h = await serviceOver(make, ROWS, source); + await h.svc.reindexSource(source.name); + await h.svc.search('alpine meadow', { topK: 1, executionContext: SYSTEM }); + const report = h.adapter.capabilities?.retrieval; + expect(lastOf(h.searched)?.retrieval).toEqual(report === undefined ? undefined : { mode: report.default }); + }); + + for (const mode of KNOWLEDGE_RETRIEVAL_MODES) { + it(`'${mode}' declared: handed to the adapter when it lists it; when it does not, refused at registration in code and at every search, and a published item still indexes`, async () => { + const source = withMode(`mode_${mode}`, mode); + const probe: IKnowledgeAdapter = await make(); + const listed = probe.capabilities?.retrieval?.modes.includes(mode) === true; + if (listed) { + const h = await serviceOver(make, ROWS, source); + await h.svc.reindexSource(source.name); + await h.svc.search('alpine meadow', { topK: 1, executionContext: SYSTEM }); + expect(lastOf(h.searched)?.retrieval).toEqual({ mode }); + return; + } + // Its adapter already registered: registration refuses it. + const refused = await serviceOver(make, ROWS, source).then( + () => undefined, + (err: unknown) => err, + ); + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + // Registered before its store: it still indexes, and every search refuses it, never run another way. + const svc = new KnowledgeService({ dataEngine: rowsEngine(ROWS) }); + svc.registerSource(source); + const adapter: IKnowledgeAdapter = await make(); + const search = vi.spyOn(adapter, 'search'); + svc.registerAdapter('under_test', adapter); + expect(await svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 1 }); + expect(svc.reportUnsupportedRetrieval()).toEqual([source.name]); + // The only source asked for is refused, so the search answers the refusal, naming it. + const alone = await svc.search('alpine meadow', { topK: 1, executionContext: SYSTEM }).catch((e: unknown) => e); + expect(alone).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect((alone as { refused?: unknown }).refused).toEqual([ + expect.objectContaining({ sourceId: source.name, code: 'SERVICE_UNAVAILABLE', status: 503 }), + ]); + expect(search).not.toHaveBeenCalled(); + + // A published item, loaded after its store started (the loader's door): never refused + // there, it is registered and indexes, and the boot's reading and every search refuse it. + const published = new KnowledgeService({ dataEngine: rowsEngine(ROWS) }); + const store: IKnowledgeAdapter = await make(); + const storeSearch = vi.spyOn(store, 'search'); + published.registerAdapter('under_test', store); + published.registerMetadataSource(source); + expect(published.getSource(source.name)).toBeDefined(); + expect(await published.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 1 }); + expect(published.reportUnsupportedRetrieval()).toEqual([source.name]); + const refusedSearch = await published + .search('alpine meadow', { topK: 1, executionContext: SYSTEM }) + .catch((e: unknown) => e); + expect(refusedSearch).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(storeSearch).not.toHaveBeenCalled(); + }); + } + }); + describe('the organization filter through KnowledgeService.search', () => { for (const posture of ['isolated', 'group'] as const) { it(`${posture}: a search from organization A never ranks or returns B's documents`, async () => { diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index dd0891c1994..f4cece22a59 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -222,6 +222,7 @@ "IPubSub (interface)", "IQueueService (interface)", "IRealtimeService (interface)", + "IReranker (interface)", "IRlsMembershipResolver (interface)", "ISchemaDiffService (interface)", "ISchemaDriver (interface)", @@ -332,6 +333,7 @@ "QueueMessage (interface)", "QueueMessageRecord (interface)", "QueuePublishOptions (interface)", + "RERANKER_SERVICE (const)", "RESERVED_RLS_MEMBERSHIP_KEYS (const)", "RESUME_AUTHORITY_SERVICE (const)", "RLS_MEMBERSHIP_RESOLVER_SERVICE (const)", diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index b587763393f..f27f1619f48 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -630,6 +630,9 @@ "ObjectFieldGroup (type)", "ObjectFieldGroupParsed (type)", "ObjectFieldGroupSchema (const)", + "ObjectFieldTab (type)", + "ObjectFieldTabParsed (type)", + "ObjectFieldTabSchema (const)", "ObjectIndex (type)", "ObjectIndexParsed (type)", "ObjectOwnership (type)", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 3b8efc28646..10404df0f62 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -695,6 +695,7 @@ "data/Object:external", "data/Object:externalSharingModel [RETIRED]", "data/Object:fieldGroups", + "data/Object:fieldTabs", "data/Object:fields", "data/Object:fileAccessDelegate", "data/Object:highlightFields", @@ -792,6 +793,8 @@ "data/ObjectFieldGroup:relatedList", "data/ObjectFieldGroup:requiresFeature", "data/ObjectFieldGroup:visibleWhen", + "data/ObjectFieldTab:groups", + "data/ObjectFieldTab:key", "data/OracleConfig:connectString", "data/OracleConfig:host", "data/OracleConfig:password [RETIRED]", diff --git a/packages/spec/declaration-map/data.json b/packages/spec/declaration-map/data.json index a1fe37afb61..27ba55ab2c0 100644 --- a/packages/spec/declaration-map/data.json +++ b/packages/spec/declaration-map/data.json @@ -244,6 +244,8 @@ "ObjectExternalBindingSchema": "data/ObjectExternalBinding", "ObjectFieldGroup": "data/ObjectFieldGroup", "ObjectFieldGroupSchema": "data/ObjectFieldGroup", + "ObjectFieldTab": "data/ObjectFieldTab", + "ObjectFieldTabSchema": "data/ObjectFieldTab", "ObjectOwnershipEnum": "data/ObjectOwnershipEnum", "ObjectRequiredPermissions": "data/ObjectRequiredPermissions", "ObjectRequiredPermissionsSchema": "data/ObjectRequiredPermissions", diff --git a/packages/spec/docs/references/api/metadata.md b/packages/spec/docs/references/api/metadata.md index 600320a39cf..abab9a8a1fb 100644 --- a/packages/spec/docs/references/api/metadata.md +++ b/packages/spec/docs/references/api/metadata.md @@ -965,6 +965,7 @@ Metadata query with filtering, sorting, and pagination | **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) | diff --git a/packages/spec/docs/references/system/migration.md b/packages/spec/docs/references/system/migration.md index 55ae2e44c60..6b253c0cf78 100644 --- a/packages/spec/docs/references/system/migration.md +++ b/packages/spec/docs/references/system/migration.md @@ -364,6 +364,7 @@ Create a new object | **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) | diff --git a/packages/spec/docs/references/system/migration.part-2.md b/packages/spec/docs/references/system/migration.part-2.md index 19833ed2c79..1cb7541d1d3 100644 --- a/packages/spec/docs/references/system/migration.part-2.md +++ b/packages/spec/docs/references/system/migration.part-2.md @@ -208,6 +208,7 @@ Create a new object | **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) | diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index e2d26712da4..d92eba97ca4 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -222,6 +222,7 @@ "IPubSub": "src/contracts/cluster-service.ts#IPubSub (interface)", "IQueueService": "src/contracts/queue-service.ts#IQueueService (interface)", "IRealtimeService": "src/contracts/realtime-service.ts#IRealtimeService (interface)", + "IReranker": "src/contracts/reranker.ts#IReranker (interface)", "IRlsMembershipResolver": "src/contracts/rls-membership-resolver.ts#IRlsMembershipResolver (interface)", "ISchemaDiffService": "src/contracts/schema-diff-service.ts#ISchemaDiffService (interface)", "ISchemaDriver": "src/contracts/schema-driver.ts#ISchemaDriver (interface)", @@ -332,6 +333,7 @@ "QueueMessage": "src/contracts/queue-service.ts#QueueMessage (interface)", "QueueMessageRecord": "src/contracts/queue-service.ts#QueueMessageRecord (interface)", "QueuePublishOptions": "src/contracts/queue-service.ts#QueuePublishOptions (interface)", + "RERANKER_SERVICE": "src/contracts/reranker.ts#RERANKER_SERVICE (const)", "RESERVED_RLS_MEMBERSHIP_KEYS": "src/contracts/rls-membership-resolver.ts#RESERVED_RLS_MEMBERSHIP_KEYS (const)", "RESUME_AUTHORITY_SERVICE": "src/contracts/automation-service.ts#RESUME_AUTHORITY_SERVICE (const)", "RLS_MEMBERSHIP_RESOLVER_SERVICE": "src/contracts/rls-membership-resolver.ts#RLS_MEMBERSHIP_RESOLVER_SERVICE (const)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 04a164f2e3f..0c1597cc347 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -619,6 +619,9 @@ "ObjectFieldGroup": "src/data/object.zod.ts#ObjectFieldGroup (type)", "ObjectFieldGroupParsed": "src/data/object.zod.ts#ObjectFieldGroupParsed (type)", "ObjectFieldGroupSchema": "src/data/object.zod.ts#ObjectFieldGroupSchema (const)", + "ObjectFieldTab": "src/data/object.zod.ts#ObjectFieldTab (type)", + "ObjectFieldTabParsed": "src/data/object.zod.ts#ObjectFieldTabParsed (type)", + "ObjectFieldTabSchema": "src/data/object.zod.ts#ObjectFieldTabSchema (const)", "ObjectIndex": "src/data/object.zod.ts#ObjectIndex (type)", "ObjectIndexParsed": "src/data/object.zod.ts#ObjectIndexParsed (type)", "ObjectOwnership": "src/data/object.zod.ts#ObjectOwnership (type)", diff --git a/packages/spec/json-schema.manifest/data.json b/packages/spec/json-schema.manifest/data.json index 0b931c87222..a5518b3debc 100644 --- a/packages/spec/json-schema.manifest/data.json +++ b/packages/spec/json-schema.manifest/data.json @@ -131,6 +131,7 @@ "data/ObjectExtensionRelatedListEntryObject", "data/ObjectExternalBinding", "data/ObjectFieldGroup", + "data/ObjectFieldTab", "data/ObjectOwnershipEnum", "data/ObjectRequiredPermissions", "data/OracleConfig", diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index f50d75d32b5..3be78301bfd 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -122,16 +122,18 @@ } }, "retrieval": { - "status": "planned", + "status": "live", "verifiedAt": "2026-11-30", - "authorWarn": true, - "authorHint": "Keep it, but nothing reads it yet: until the knowledge service reads it, a source is searched in its store's default mode whatever it declares, and a mode the store does not run is not refused.", - "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note of 2026-11-30 under K8): `retrieval: { mode }`, how a source is searched. CARRIED today: it parses at every door (strict, `retrieval: {}` allowed) and is kept by the parse. ACTED ON by nothing yet: the knowledge service resolves the effective mode (the source's declaration, else the adapter's `capabilities.retrieval.default`), refuses a mode the adapter does not list at the four points the ruling names, and hands it to the adapter as `AdapterSearchOptions.retrieval`; knowledge-turso and knowledge-pgvector run one leg or both. Those are the phase-1a PRs that follow this one. Flip to `live` on the commit that lands the service's reader, citing it, and drop `authorWarn` / `authorHint` in that same edit (a warned `live` row reds this gate). Enters neither the index fingerprint nor the recipe hash.", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-retrieval-mode.ts#resolveRetrievalMode — the effective mode: the source's declaration, else the adapter's `capabilities.retrieval.default`; packages/services/service-knowledge/src/knowledge-service-search.ts#planSearches — every search resolves it, hands it to the adapter as `AdapterSearchOptions.retrieval` (`searchRound`) and refuses a mode the adapter does not list in `refused` (SERVICE_UNAVAILABLE); packages/services/service-knowledge/src/knowledge-service-admission.ts#admitAuthoredSource — the save refuses it (400 VALIDATION_ERROR, listing the modes the store runs); packages/services/service-knowledge/src/knowledge-service-sources.ts#registerSource — registration in code refuses it when the adapter already resolves (a published item is registered and indexed through #registerMetadataSource, and the next two refuse it); packages/services/service-knowledge/src/knowledge-service-sources.ts#reportUnsupportedRetrieval — the boot's reading names it at `error`.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload).", + "note": "Ruling 7270218011 on #38692, phase 1a (ADR-0161, the dated note of 2026-11-30 under K8). Strict, `retrieval: {}` allowed. Read by search alone: enters neither the index fingerprint nor the recipe hash, so changing it rebuilds nothing, and a source whose mode is refused still indexes. knowledge-turso and knowledge-pgvector run each mode; an adapter that reports no modes (knowledge-memory) takes a source that leaves the mode out.", "children": { "mode": { - "status": "planned", + "status": "live", "verifiedAt": "2026-11-30", - "note": "Planned with its container `retrieval` (see that row): `vector`, `keyword` or `hybrid`; omitted means the adapter's default." + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-retrieval-mode.ts#resolveRetrievalMode — `vector`, `keyword` or `hybrid`, handed to the adapter as `AdapterSearchOptions.retrieval.mode`; omitted means the adapter's default." } } }, diff --git a/packages/spec/liveness/object.json b/packages/spec/liveness/object.json index f733a186244..495f4e80c70 100644 --- a/packages/spec/liveness/object.json +++ b/packages/spec/liveness/object.json @@ -170,6 +170,30 @@ "producer": "ui/packages/app-shell/src/views/RecordDetailView.tsx#RecordDetailView (threads the served object's `pinOverview` into `RecordPageColumns` on the desktop full record page; not on a phone)", "note": "ADR-0085 Note of 2026-11-27: a ruled exception (an object key that only re-arranges the synthesized record page). Not an object-extension key and not in CUSTOM_ARRANGEMENT_KEYS." }, + "fieldTabs": { + "status": "live", + "verifiedAt": "2026-11-30", + "evidenceScope": "in-repo", + "evidence": "ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts#fieldTabPlacement (each entry's groups come out of the overview's sections, in its order; a group the object does not declare or another tab took is skipped, a tab left with none is not placed); ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts#buildDefaultTabs (a `fields:` tab per entry right after the overview, before every related and built-in tab, its title and icon its first group's); ui/packages/plugin-detail/src/RecordPageColumns.tsx#RecordPageColumns (the laid-out page draws each tab whose groups are drawn, with its own empty-field row; the reader's arrangement neither moves nor hides it); ui/packages/app-shell/src/views/RecordDetailView.tsx#RecordDetailView (a `?section=` cited inside a field tab opens that tab first); packages/lint/src/data-model-rules.ts#lintDataModel (`object/field-tabs-empty-overview` warns when every field is moved out)", + "producer": "ui/packages/app-shell/src/views/RecordDetailView.tsx#RecordDetailView (synthesizes the standard record page from the served object, its `fieldTabs` included)", + "note": "ADR-0085 Note of 2026-11-27: a ruled exception (an object key that only re-arranges the synthesized record page), the second key of that ruling beside pinOverview. Not an object-extension key and not in CUSTOM_ARRANGEMENT_KEYS. Not the form-level FormSchema.fieldTabs.", + "children": { + "key": { + "status": "live", + "verifiedAt": "2026-11-30", + "evidenceScope": "in-repo", + "evidence": "ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts#buildDefaultTabs (the tab's value `fields:`, the `?related=` address); ui/packages/plugin-detail/src/synth/recordPageColumns.ts#recordPageColumnOfTab (`fields:` lays out as a field tab)", + "note": "The tab's address on the record page; unique within the object." + }, + "groups": { + "status": "live", + "verifiedAt": "2026-11-30", + "evidenceScope": "in-repo", + "evidence": "ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts#fieldTabPlacement (the named groups' sections, in this order, are the tab's body and leave the overview); packages/spec/src/data/object.zod.ts#refuseDishonestFieldTabs (an undeclared group, a group two tabs name and a related-list group are refused)", + "note": "Keys of the object's own fieldGroups." + } + } + }, "stageField": { "status": "live", "proof": "packages/qa/dogfood/test/semantic-roles.dogfood.test.ts#semantic-roles-served", diff --git a/packages/spec/liveness/state-counts/knowledge_source.md b/packages/spec/liveness/state-counts/knowledge_source.md index 1fcc479c9f3..011bd5fd35d 100644 --- a/packages/spec/liveness/state-counts/knowledge_source.md +++ b/packages/spec/liveness/state-counts/knowledge_source.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `knowledge_source` | 26 | 0 | 0 | 6 | 1 | 33 | +| `knowledge_source` | 27 | 0 | 0 | 6 | 0 | 33 | diff --git a/packages/spec/liveness/state-counts/object.md b/packages/spec/liveness/state-counts/object.md index cdbb59457b5..b5ca968ce9f 100644 --- a/packages/spec/liveness/state-counts/object.md +++ b/packages/spec/liveness/state-counts/object.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `object` | 99 | 0 | 0 | 1 | 1 | 101 | +| `object` | 101 | 0 | 0 | 1 | 1 | 103 | diff --git a/packages/spec/src/ai/knowledge-source.metadata-form.ts b/packages/spec/src/ai/knowledge-source.metadata-form.ts index 75a86d7d7df..9ddb111cf74 100644 --- a/packages/spec/src/ai/knowledge-source.metadata-form.ts +++ b/packages/spec/src/ai/knowledge-source.metadata-form.ts @@ -25,8 +25,14 @@ import { defineMetadataForm } from '../ui/view.zod'; * - `source.affinity` is the JSON editor too: a list of `{ field, caller, * mode, places? }` entries whose cross-key rules (a `field` listed in * `metadataFields`, `places` on a `boost` alone) no list widget states. - * - `source.retrieval.mode` is a select of the three modes, blank for the - * store's default; which modes the store runs is judged at save. + * - `source.retrieval.mode` is the `knowledge-retrieval-mode` picker: Studio + * offers the modes the source's store runs and names its default, or says + * the store declares none. A host whose widget registry lacks that picker + * draws its unregistered-widget face for this row (the JSON editor with its + * notice), not a select: the hint is read before `options`. The three + * `options` stay because the form's generated translations carry their + * labels; no renderer reads them while the hint is set. Which modes the + * store runs is judged at save either way. * * ADR-0161 K5 and K10 rule 5: embedding is egress, so `content` offers named * fields only, and its help says beside it what a build sends and to whom. @@ -88,6 +94,7 @@ export const knowledgeSourceForm = defineMetadataForm({ { field: 'mode', label: 'Retrieval mode', + widget: 'knowledge-retrieval-mode', options: [ { label: 'Vector only (by meaning)', value: 'vector' }, { label: 'Keyword only (by words)', value: 'keyword' }, diff --git a/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts b/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts index a43c90ed324..b9ddeeeff1b 100644 --- a/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts +++ b/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts @@ -257,6 +257,7 @@ describe('MAIN — the preprocess-wrapped collection key is IN the refusal set', 'closedStates', 'highlightFields', 'relatedLists', + 'fieldTabs', 'listViews', 'searchableFields', 'membershipKeys', @@ -321,6 +322,7 @@ describe("TODAY-INVARIANCE — the fix moves no key on today's ObjectSchema", () 'closedStates', 'highlightFields', 'relatedLists', + 'fieldTabs', 'listViews', 'searchableFields', 'membershipKeys', diff --git a/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts b/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts index bce81d2b0bb..9a0e4a59e23 100644 --- a/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts +++ b/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts @@ -70,6 +70,7 @@ const COLLECTION_KEYS_IN_SHAPE_ORDER = [ 'closedStates', 'highlightFields', 'relatedLists', + 'fieldTabs', 'listViews', 'searchableFields', 'membershipKeys', @@ -144,6 +145,7 @@ describe("composeStacks objectConflict: 'merge' — a collection both objects de ['searchableFields', ['title'], ['title', 'body']], ['highlightFields', ['title'], ['body']], ['relatedLists', ['task'], ['event']], + ['fieldTabs', [{ key: 'content', groups: ['content'] }], [{ key: 'content', groups: ['content', 'import'] }]], ['activityMilestones', [{ name: 'm_a' }], [{ name: 'm_b' }]], ['requiredPermissions', ['crm.read'], ['billing.read']], ['attachedOnRead', { viewer: { can_act: 'boolean' } }, { viewer: { can_act: 'boolean', is_submitter: 'boolean' } }], diff --git a/packages/spec/src/contracts/index.ts b/packages/spec/src/contracts/index.ts index b21cc6d9438..6958a53f0dc 100644 --- a/packages/spec/src/contracts/index.ts +++ b/packages/spec/src/contracts/index.ts @@ -77,6 +77,7 @@ export * from './attachment-doors-service.js'; export * from './print-door-service.js'; export * from './package-service.js'; export * from './knowledge-service.js'; +export * from './reranker.js'; export * from './knowledge-adapter.js'; export * from './embedder.js'; diff --git a/packages/spec/src/contracts/reranker.test.ts b/packages/spec/src/contracts/reranker.test.ts new file mode 100644 index 00000000000..0dc2b1484f9 --- /dev/null +++ b/packages/spec/src/contracts/reranker.test.ts @@ -0,0 +1,74 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// `IReranker` / `RERANKER_SERVICE`: the reranker contract the knowledge +// service resolves per search. The card asks for a type-level pin of the +// ruled shape: `IReranker { id; rerank(query, documents, opts?: { signal }) }` +// returning an array of `{ index, score }`, and the `'reranker'` service token, +// both reachable from the `contracts` barrel. +// +// Optionality is pinned with `{} extends Pick<…>` aliases, not `expectTypeOf`: +// `toEqualTypeOf` cannot tell an optional member from a REQUIRED one typed +// `T | undefined`. The aliases are exported so TS6196 does not flag them as +// unused; `check:test-typecheck` compiles this file. + +import { describe, it, expect } from 'vitest'; +import { RERANKER_SERVICE, type IReranker } from './reranker'; +import { + RERANKER_SERVICE as RERANKER_SERVICE_FROM_BARREL, + type IReranker as IRerankerFromBarrel, +} from './index'; + +type Eq = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false; +type Assert = T; + +type Rerank = IReranker['rerank']; +type RerankOpts = NonNullable[2]>; + +/** Exactly two members: `id` and `rerank` (no `model`, no preset list). */ +export type MembersAreIdAndRerank = Assert>; + +/** `id` is a readonly string, as `IEmbedder.id`. */ +export type IdIsAString = Assert>; +export type IdIsReadonly = Assert>, Pick>>; + +/** `rerank(query, documents, opts?)`: a string query, string documents. */ +export type RerankTakesQueryDocumentsOpts = Assert< + Eq, [query: string, documents: string[], opts?: { signal?: AbortSignal }]> +>; + +/** The options bag carries only the caller's `AbortSignal`. */ +export type OptsCarryOnlyASignal = Assert>; + +/** `opts` itself is optional: `rerank(query, documents)` is a valid call. */ +export type OptsAreOptional = Assert<[string, string[]] extends Parameters ? true : false>; + +/** The answer: an array of `{ index, score }`, asynchronously. */ +export type RerankAnswersIndexAndScore = Assert< + Eq, Promise>> +>; + +/** The barrel (`@objectstack/spec/contracts`) exports this contract, not a look-alike. */ +export type BarrelExportsTheContract = Assert>; + +/** The service token is the literal `'reranker'`. */ +export type TokenIsTheLiteral = Assert>; + +describe('IReranker contract', () => { + it('registers under the `reranker` service token, exported from the contracts barrel', () => { + expect(RERANKER_SERVICE).toBe('reranker'); + expect(RERANKER_SERVICE_FROM_BARREL).toBe(RERANKER_SERVICE); + }); + + it('is satisfied by an implementation that answers index + score per document', async () => { + const reranker: IReranker = { + id: 'fixture', + async rerank(_query, documents) { + return documents.map((_, index) => ({ index, score: 1 / (index + 1) })); + }, + }; + await expect(reranker.rerank('q', ['a', 'b'])).resolves.toEqual([ + { index: 0, score: 1 }, + { index: 1, score: 0.5 }, + ]); + }); +}); diff --git a/packages/spec/src/contracts/reranker.ts b/packages/spec/src/contracts/reranker.ts new file mode 100644 index 00000000000..f7aaa48ec5e --- /dev/null +++ b/packages/spec/src/contracts/reranker.ts @@ -0,0 +1,50 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `IReranker` — protocol-level contract for providers that score a set of + * passages against a query, so the knowledge service can re-order a search's + * candidates. + * + * Mirrors `IEmbedder` (`./embedder.ts`): a deployment registers one + * implementation under {@link RERANKER_SERVICE}, and the knowledge service + * resolves it per search, as knowledge adapters resolve the embedder. The + * reader lands with `retrieval.rerank` (#38750, row 2); until then nothing + * resolves this service. + * + * Conventions: + * - The model always comes from the deployment, never from a knowledge + * source. + * - The caller makes one call per search and sends at most 50 documents. + * - The caller passes an `AbortSignal` (`opts.signal`) for its time limit. + * - Each returned entry names one document by its position in the + * `documents` input (`index`) and carries the score the reranker gave 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. + */ +export interface IReranker { + /** Stable id for logs and diagnostics. */ + readonly id: string; + /** + * Score `documents` against `query`. Each entry's `index` is the + * document's position in `documents`; `score` is 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. + */ + rerank( + query: string, + documents: string[], + opts?: { signal?: AbortSignal }, + ): Promise>; +} + +/** + * DI service token for the kernel-registered `IReranker` instance. + * + * The knowledge service is to resolve this service per search, the way + * knowledge adapters resolve `EMBEDDER_SERVICE` (`./embedder.ts`); the + * deployment configures the reranker once, and no knowledge source names one. + * The reader lands with `retrieval.rerank` (#38750, row 2). + */ +export const RERANKER_SERVICE = 'reranker' as const; diff --git a/packages/spec/src/data/object.metadata-form.ts b/packages/spec/src/data/object.metadata-form.ts index 5f68b568188..5bd6c0c7770 100644 --- a/packages/spec/src/data/object.metadata-form.ts +++ b/packages/spec/src/data/object.metadata-form.ts @@ -85,6 +85,21 @@ export const objectForm = defineMetadataForm({ // the tab list it lays out. A boolean row: an untouched switch writes // nothing, so an object keeps the derived pin until an author sets it. { field: 'pinOverview', type: 'boolean', colSpan: 1, helpText: 'Whether the wide desktop record page pins the overview (the record\'s own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way.' }, + // ADR-0085 (Note of 2026-11-27, objectstack#37802) — the field tabs, + // the second key of that ruling, beside the layout switch: a repeater + // over the entry's two keys, as `fieldGroups` below. `groups` is a list + // of the object's own group keys, a `tags` row as a group's `fields` + // is; the parse refuses a key no group declares. + { + field: 'fieldTabs', + type: 'repeater', + colSpan: 2, + helpText: 'Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused.', + fields: [ + { field: 'key', label: 'Key', type: 'text', required: true, helpText: 'Machine key in snake_case, unique among this object\'s field tabs; the tab\'s address on the record page (fields:key).' }, + { field: 'groups', label: 'Groups', type: 'tags', required: true, helpText: 'The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here.' }, + ], + }, { field: 'searchableFields', widget: 'string-tags', colSpan: 2, helpText: 'Field names the $search query matches (ADR-0061): the default for the record picker, list quick-search and global search; a view may narrow it. Unset, search uses the name/title field plus short-text fields. Each entry must name a stored field of this object — an unknown name or a virtual formula field is refused at publish.' }, // #19332 (flight G2a of ruling record 5861442317) — the object's field // groups, the ADR-0085 layout role beside `nameField` / `highlightFields`. diff --git a/packages/spec/src/data/object.test.ts b/packages/spec/src/data/object.test.ts index febbfe99305..4fb2ed589bd 100644 --- a/packages/spec/src/data/object.test.ts +++ b/packages/spec/src/data/object.test.ts @@ -2042,6 +2042,105 @@ describe('ObjectSchema.pinOverview — the record page layout switch', () => { }); }); +describe('ObjectSchema.fieldTabs — field groups drawn as record page tabs', () => { + const policy = (extra: Record) => ({ + name: 'policy', + fields: { + title: { type: 'text', group: 'basic' }, + body: { type: 'textarea', group: 'content' }, + source_file: { type: 'text', group: 'import' }, + }, + fieldGroups: [ + { key: 'basic', label: 'Basic' }, + { key: 'content', label: 'Content' }, + { key: 'import', label: 'Original' }, + { key: 'lines', label: 'Lines', relatedList: 'policy_line' }, + ], + ...extra, + }); + const issuesOf = (input: unknown) => { + const result = ObjectSchema.safeParse(input); + expect(result.success).toBe(false); + return result.success ? [] : result.error.issues; + }; + + it('parses absent, and a valid two-tab declaration end to end, keeping order', () => { + expect(ObjectSchema.parse(policy({})).fieldTabs).toBeUndefined(); + const tabs = [ + { key: 'content', groups: ['content', 'import'] }, + { key: 'basics', groups: ['basic'] }, + ]; + expect(ObjectSchema.parse(policy({ fieldTabs: tabs })).fieldTabs).toEqual(tabs); + expect(ObjectSchema.create(policy({ fieldTabs: tabs }) as never).fieldTabs).toEqual(tabs); + }); + + it('refuses a group the object does not declare, at the groups entry', () => { + const issues = issuesOf(policy({ fieldTabs: [{ key: 'content', groups: ['content', 'terms'] }] })); + expect(issues).toHaveLength(1); + expect(issues[0].path).toEqual(['fieldTabs', 0, 'groups', 1]); + expect(issues[0].message).toContain("'terms'"); + expect(issues[0].message).toContain('FormSchema.fieldTabs'); + }); + + it('refuses every group on an object that declares no fieldGroups', () => { + const issues = issuesOf({ name: 'policy', fields: {}, fieldTabs: [{ key: 'content', groups: ['content'] }] }); + expect(issues.map((i) => i.path)).toEqual([['fieldTabs', 0, 'groups', 0]]); + }); + + it('refuses a group two tabs name, naming the first tab', () => { + const issues = issuesOf(policy({ + fieldTabs: [ + { key: 'content', groups: ['content'] }, + { key: 'more', groups: ['import', 'content'] }, + ], + })); + expect(issues).toHaveLength(1); + expect(issues[0].path).toEqual(['fieldTabs', 1, 'groups', 1]); + expect(issues[0].message).toContain("'content' and 'more'"); + }); + + it('refuses a group that places a related table', () => { + const issues = issuesOf(policy({ fieldTabs: [{ key: 'lines', groups: ['lines'] }] })); + expect(issues).toHaveLength(1); + expect(issues[0].path).toEqual(['fieldTabs', 0, 'groups', 0]); + expect(issues[0].message).toContain('policy_line'); + }); + + it('refuses a repeated key', () => { + const issues = issuesOf(policy({ + fieldTabs: [ + { key: 'content', groups: ['content'] }, + { key: 'content', groups: ['import'] }, + ], + })); + expect(issues).toHaveLength(1); + expect(issues[0].path).toEqual(['fieldTabs', 1, 'key']); + expect(issues[0].message).toContain("'content' is already a field tab's key"); + }); + + it('refuses an entry with no group, a non-snake_case key, and the form-level shape by name', () => { + expect(issuesOf(policy({ fieldTabs: [{ key: 'content', groups: [] }] }))[0].path).toEqual(['fieldTabs', 0, 'groups']); + expect(issuesOf(policy({ fieldTabs: [{ key: 'Content', groups: ['content'] }] }))[0].path).toEqual(['fieldTabs', 0, 'key']); + const formShape = issuesOf(policy({ fieldTabs: [{ key: 'content', groups: ['content'], fields: ['body'] }] })); + const unknown = formShape.find((i) => i.code === 'unrecognized_keys'); + expect(unknown).toBeDefined(); + expect(unknown!.message).toContain('FormSchema.fieldTabs'); + const labelled = issuesOf(policy({ fieldTabs: [{ key: 'content', groups: ['content'], label: 'Body' }] })); + expect(labelled.find((i) => i.code === 'unrecognized_keys')!.message).toContain('first group'); + }); + + it('an object extension refuses it, naming the object key and the form-level one', () => { + const result = ObjectExtensionSchema.safeParse({ extend: 'crm_account', fieldTabs: [{ key: 'content', groups: ['content'] }] }); + expect(result.success).toBe(false); + if (!result.success) { + const issue = result.error.issues.find((i) => i.code === 'unrecognized_keys'); + expect(issue).toBeDefined(); + expect(issue!.message).toContain('ObjectSchema.fieldTabs'); + expect(issue!.message).toContain('FormSchema.fieldTabs'); + } + }); +}); + describe('ObjectSchema.fieldGroups', () => { it('should accept an object without fieldGroups (fully optional)', () => { const result = ObjectSchema.safeParse({ diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index c9d057a4c56..24f451fea03 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -1654,9 +1654,59 @@ export const ObjectFieldGroupSchema = lazySchema(() => strictObject({ // group's slot name; the key never reaches the output. }).transform((group, ctx) => lowerRequiresFeature(group, ctx, 'visibleWhen'))); +/** + * [ADR-0085, Note of 2026-11-27] One `ObjectSchema.fieldTabs` entry: a tab of + * the standard record page holding some of this object's field groups. + * + * Deliberately not the form-level `FormSchema.fieldTabs` entry + * (`@object-ui/types`), which shares the key name and claims FIELD names: + * a record-page field tab claims GROUPS, so a field keeps its group on every + * surface and only where the group is drawn changes. Each shape's refusal + * names the other key. No `label` or `icon` (v1): the tab's title and icon + * are its first group's, whose `label` is already translated. + */ +export const ObjectFieldTabSchema = lazySchema(() => strictObject({ + surface: 'this fieldTabs entry', + history: + 'An unknown key here would be dropped silently: the tab would still draw, so the author would believe ' + + 'the setting they wrote had been applied.', + aliases: { + name: 'key', + id: 'key', + fieldGroups: 'groups', + }, + guidance: { + fields: + '`fields` is the form-level `FormSchema.fieldTabs` shape (`@object-ui/types`), which claims field names. ' + + 'An object\'s `fieldTabs` entry (`ObjectSchema.fieldTabs`, the record page\'s field tabs) names field ' + + 'GROUPS: write `groups: [, …]`, and put the fields in those groups.', + label: + '`label` is not a fieldTabs entry key: a record-page field tab takes its title from its first group\'s ' + + '`label`. Order `groups` so the group whose label should title the tab comes first.', + icon: + '`icon` is not a fieldTabs entry key: a record-page field tab takes its icon from its first group\'s `icon`.', + visibleWhen: + '`visibleWhen` is not a fieldTabs entry key: a field tab is drawn when at least one of its groups is, so ' + + 'gate the groups (`fieldGroups[].visibleWhen`).', + }, +}, { + key: z.string().regex(FIELD_GROUP_KEY_PATTERN, { + message: 'A fieldTabs key must be lowercase snake_case (e.g., "content", "terms")', + }).describe('The tab\'s key (snake_case). The record page addresses the tab as fields:.').meta({ title: 'Key' }), + groups: z.array(z.string().regex(FIELD_GROUP_KEY_PATTERN, { + message: 'A fieldTabs groups entry is a fieldGroups key of this object, in snake_case (e.g., "content")', + })).min(1, { + message: 'A fieldTabs entry names at least one field group in `groups`', + }).describe('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.').meta({ title: 'Groups' }), +})); + export type ObjectFieldGroup = z.input; /** Post-parse shape of {@link ObjectFieldGroup} — defaults applied, transforms run (ADR-0122). */ export type ObjectFieldGroupParsed = z.infer; +/** One `ObjectSchema.fieldTabs` entry (objectstack#37802): a record-page field tab, `{ key, groups }`. */ +export type ObjectFieldTab = z.input; +/** Post-parse shape of {@link ObjectFieldTab} (ADR-0122). */ +export type ObjectFieldTabParsed = z.infer; /** * Base Object Schema Definition @@ -3583,6 +3633,95 @@ function refuseFieldsInRelatedListGroups(fieldGroups: unknown, fields: unknown, } } +/** + * [ADR-0085, Note of 2026-11-27] Each `fieldTabs` entry names field groups this + * object declares, each group at most once across the tabs, and none that + * places a related table. One located issue per offending `groups` entry, at + * `['fieldTabs', i, 'groups', j]`: + * + * - a key `fieldGroups` does not declare (an object with no `fieldGroups` + * declares none); + * - a group an earlier tab (or an earlier position of the same tab) already + * names, naming where it was first named; + * - a group carrying `relatedList`: a body table stays in the overview in v1. + * + * Judged here, in the object's `superRefine`, for the reason + * {@link refuseFieldsInRelatedListGroups} gives: only the object holds both + * lists. A repeated tab `key` is refused here too, at the second entry's `key` + * (`['fieldTabs', i, 'key']`): one place judges the whole list, and a + * refinement on the array itself would be one more rule the published JSON + * Schema drops. + */ +function refuseDishonestFieldTabs(fieldTabs: unknown, fieldGroups: unknown, ctx: z.RefinementCtx): void { + if (!Array.isArray(fieldTabs)) return; + const declared = new Map(); + if (Array.isArray(fieldGroups)) { + for (const group of fieldGroups) { + if (group !== null && typeof group === 'object' && typeof (group as { key?: unknown }).key === 'string') { + const key = (group as { key: string }).key; + if (!declared.has(key)) declared.set(key, group as { relatedList?: unknown }); + } + } + } + const namedBy = new Map(); + const tabKeys = new Set(); + fieldTabs.forEach((tab: unknown, index: number) => { + if (tab === null || typeof tab !== 'object') return; + const { key, groups } = tab as { key?: unknown; groups?: unknown }; + if (typeof key === 'string') { + if (tabKeys.has(key)) { + ctx.addIssue({ + code: 'custom', + path: ['fieldTabs', index, 'key'], + message: `fieldTabs[].key must be unique within an object: '${key}' is already a field tab's key, and each record-page field tab has its own`, + }); + } + tabKeys.add(key); + } + if (!Array.isArray(groups)) return; + const tabName = typeof key === 'string' ? `'${key}'` : `#${index + 1}`; + groups.forEach((group: unknown, at: number) => { + if (typeof group !== 'string') return; + const path = ['fieldTabs', index, 'groups', at]; + const declaration = declared.get(group); + if (!declaration) { + ctx.addIssue({ + code: 'custom', + path, + message: + `Field tab ${tabName} names the field group '${group}', which this object's \`fieldGroups\` does not declare. ` + + 'A fieldTabs entry (`ObjectSchema.fieldTabs`) names keys of the object\'s own `fieldGroups`: declare the ' + + 'group, or name a declared one. (A form\'s tabbed field layout lists field names; that is the form-level ' + + '`FormSchema.fieldTabs`.)', + }); + return; + } + const first = namedBy.get(group); + if (first !== undefined) { + ctx.addIssue({ + code: 'custom', + path, + message: + `The field group '${group}' is named by two field tabs, ${first} and ${tabName}. A group is drawn in one ` + + 'place: remove it from one of the two `groups` lists.', + }); + return; + } + namedBy.set(group, tabName); + if (typeof declaration.relatedList === 'string') { + ctx.addIssue({ + code: 'custom', + path, + message: + `Field tab ${tabName} names the field group '${group}', which places the related list ` + + `'${declaration.relatedList}' (its \`relatedList\`). A body table stays in the overview: name only ` + + 'groups of fields in `fieldTabs`.', + }); + } + }); + }); +} + /** * A field group's `fields` list and a field's own `group` are two spellings of * one membership (`ObjectFieldGroupSchema.fields`), so where both speak they @@ -4990,6 +5129,29 @@ const ObjectSchemaBase = strictObject( * object it is the base package's to write. */ pinOverview: z.boolean().optional().describe('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.'), + /** + * [ADR-0085, Note of 2026-11-27, a ruled exception] Field groups the + * standard record page draws as tabs of their own instead of in the + * overview. Each entry names one tab (`key`, the `fields:` tab id in + * the page address) and the field groups it holds (`groups`, keys of this + * object's `fieldGroups`, drawn in that order). + * + * The tabs come right after the overview, in declared order, before every + * related-list and built-in tab; the reader cannot move or hide them. A tab + * takes its title and icon from its first group. The overview keeps every + * group no tab names, the ungrouped fields, the approval band and the + * record's meta line. On a pinned page (`pinOverview`) the first field tab + * is the tab open beside the overview. + * + * Refused at parse: a group this object does not declare, a group two tabs + * name, a group that places a related table (`relatedList`; body tables stay + * in the overview), and a repeated `key`. Absent: the page is unchanged. + * Read by the standard record page alone: the entry form, print pages and + * authored `kind: 'full' | 'html' | 'react'` pages lay out every group as + * before. Not an object-extension key, and not the form-level + * `FormSchema.fieldTabs` (`@object-ui/types`), which lists field names. + */ + fieldTabs: z.array(ObjectFieldTabSchema).optional().describe('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.'), /** * [ADR-0085] Semantic role: the field that represents the record's LINEAR * lifecycle (an ordered pipeline / stage progression). A string names the @@ -5483,6 +5645,9 @@ const ObjectSchemaBase = strictObject( // A group's `fields` list and a field's own `group` agree where both speak. // See the helper's docblock. refuseFieldGroupMembershipConflicts(object.fieldGroups, object.fields, ctx); + // [ADR-0085, Note of 2026-11-27] Each field tab names declared groups of + // fields, each once. See the helper's docblock. + refuseDishonestFieldTabs(object.fieldTabs, object.fieldGroups, ctx); // [ADR-0055 §1 · #23100 ruling B, as amended by #30905 ruling A] Exactly one // master `master_detail` under `controlled_by_parent` (the required one, or // the only one declared `required: false`) — the one master relation the @@ -7166,6 +7331,12 @@ export const ObjectExtensionSchema = lazySchema(() => strictObject({ '`pinOverview` cannot be contributed through an object extension: whether the record page pins ' + 'the overview is declared on the object itself (`ObjectSchema.pinOverview`) by the package that ' + 'defines it.', + // [ADR-0085, Note of 2026-11-27] The record page's field tabs are the + // object's own, like `pinOverview`: not in `CUSTOM_ARRANGEMENT_KEYS`. + fieldTabs: + '`fieldTabs` cannot be contributed through an object extension: which field groups the record page ' + + 'draws as tabs is declared on the object itself (`ObjectSchema.fieldTabs`) by the package that ' + + 'defines it. (A form\'s tabbed field layout is a different key, the form-level `FormSchema.fieldTabs`.)', membershipKeys: '`membershipKeys` cannot be contributed through an object extension: a membership key is ' + 'declared by the package that owns the roster object whose rows define it. Declare the key on ' + diff --git a/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts b/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts index 5cb8412caa4..fd4d43f80f1 100644 --- a/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts +++ b/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts @@ -2,7 +2,7 @@ import type { SemanticMigration } from '../../types.js'; -// #37815 — an authored L2 hook body that calls a member the QuickJS sandbox gates +// #37815 — an L2 hook body that calls a member the QuickJS sandbox gates // without that member's token in `body.capabilities`, and an L2 action body // that does so for a token other than `api.write`, are refused at error as // `hook-body-capability-undeclared` / `action-body-capability-undeclared` @@ -18,9 +18,8 @@ export const entry: SemanticMigration = { 'hooks[].body and actions[].body (an object\'s inline actions[] included) whose body.language is js, on a hook ' + 'or action saved or published through the metadata doors (PUT /api/v1/meta/hook/NAME, PUT ' + '/api/v1/meta/action/NAME, an object write, POST /api/v1/packages/PKG/publish-drafts and the per-item publish) ' - + 'or loaded by os validate / os build / os lint, only a body the author wrote (a hook body lowered from an ' - + 'inline handler is not judged, and an action body lowered from an inline target function is judged for its ' - + 'writes alone, as before): a source ' + + 'or loaded by os validate / os build / os lint, whether the author wrote the body or os build lowered it from ' + + 'an inline handler or target function: a source ' + 'that calls a member the sandbox gates without its token in body.capabilities. The gates: the ' + 'ctx.api.object(…) read leaves (api.read), its write leaves (api.write), ctx.api.transaction (api.transaction), ' + 'ctx.log.debug / info / warn / error (log), ctx.crypto.randomUUID (crypto.uuid), ctx.email.send (email.send), ' @@ -32,18 +31,20 @@ export const entry: SemanticMigration = { + 'Refused at error as `hook-body-capability-undeclared` or `action-body-capability-undeclared` (422 ' + 'INVALID_METADATA at the hook and action doors); an action body\'s write without api.write stays ' + '`action-body-write-capability-undeclared`. A hook written as a handler, or an action written as a target ' - + 'function, needs no change for the other tokens: its lowered body is not judged for them (a later ' - + 'change carries the lowered reading).', + + 'function, needs no change: os 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, and ' + + 'that lowered body is judged like an authored one.', reason: 'The sandbox installs each gated member behind its token and refuses a call the body was not granted with 403 ' + 'INSUFFICIENT_PRIVILEGES at the call site. Every authoring door accepted such a body (only an action body\'s ' + 'writes were judged), so it deployed clean and then failed at the call every time the hook or action reached ' + 'it; under a hook\'s default onError abort, the write that ran the hook failed with it. The rule reads the ' + 'source with strings and comments blanked, without parsing or running it, and judges exactly the gates the ' - + 'sandbox runner installs. A hook body os build lowered from an inline handler is not judged, and an action ' - + 'body it lowered from an inline target function is judged only for api.write, as before: such a grant is the ' - + 'build\'s inference, not the author\'s, and the inference does not yet read every gated shape, so a hook ' - + 'written as a handler and an action written as a target function are unchanged. Stored metadata is not rewritten or ' + + 'sandbox runner installs. A hook body os build lowered from an inline handler, and an action body it lowered ' + + 'from an inline target function, are judged the same way: their grant is the build\'s inference, which reads ' + + 'each gated call in each spelling the rule reads, pinned spelling by spelling against the rule, so a hook ' + + 'written as a handler and an action written as a target function build clean. Stored metadata is not ' + + 'rewritten or ' + 'refused at boot; the next publish of the hook, action or object is refused with the token named. Such a call ' + 'never succeeded, so no stored row changes shape. There is no mechanical rewrite: granting a token widens what ' + 'the body may do, which is the author\'s decision.', diff --git a/packages/spec/src/migrations/entries/semantic/19.knowledge-search-uncoded-adapter-throw-refused.ts b/packages/spec/src/migrations/entries/semantic/19.knowledge-search-uncoded-adapter-throw-refused.ts new file mode 100644 index 00000000000..1af8e3ecd49 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.knowledge-search-uncoded-adapter-throw-refused.ts @@ -0,0 +1,46 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #38728 — a knowledge search (@objectstack/service-knowledge) whose 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) now refuses that source as SERVICE_UNAVAILABLE (503) +// instead of answering it as no hits. It narrows what a search answers with +// success; no metadata key or schema changes, so there is no tombstone and no +// stored row to rewrite. Not converted: what a caller does with a refused +// source is the caller's code, not metadata. +export const entry: SemanticMigration = { + id: 'knowledge-search-uncoded-adapter-throw-refused', + surface: + 'A knowledge search through the search_knowledge tool (its executor, and its MCP HTTP and stdio faces) or the ' + + 'in-process KnowledgeService.search / searchWithRefusals, when a searched source\'s adapter throws from search ' + + 'with an error that does not carry both an ADR-0112 code and status: (a) no searched source answers and at ' + + 'least one threw without a code, in two cells: (a1) every searched source throws without a code (one source, ' + + 'or several failing on the same embedder outage), which answered success with no hits; (a2) a source throws ' + + 'without a code beside a source refused with a code, none answering, which was rejected with the coded ' + + 'source\'s code and status and refused naming it alone; (b) a source that answered the first round throws on ' + + 'the refill, whose first-round survivors were served', + replacement: + 'Read refused and the 503 instead of treating an empty answer as no match: (a1) 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); (a2) the search is rejected with refused naming both sources, and the ' + + 'rejection\'s own code and status are those of the first refusal in source order, so a 409 ' + + 'KNOWLEDGE_REBUILD_REQUIRED rejection may now read 503 SERVICE_UNAVAILABLE: read each source\'s code in ' + + 'refused, not only the top-level code. When any searched source answers, its hits are still served and the ' + + 'failing one is listed in refused. (b) the source\'s first-round hits are dropped and it is refused for the ' + + 'whole search, as a coded refusal of the refill already was. An operator repairs the adapter or embedder the ' + + 'service\'s error log line names.', + reason: + 'An adapter that throws did not search its source, so answering it as no hits told the caller that nothing ' + + 'matched when nothing was looked at. A coded refusal was already named in refused; an uncoded throw now is ' + + 'too, under the code this service already answers for an adapter that cannot serve. The caller reads a ' + + 'platform sentence naming the source, never the thrown message, which can carry hosts, SQL or keys; the ' + + 'operator\'s error line keeps it. No stored metadata changes shape and nothing is refused at boot or at save.', + acceptanceCriteria: + 'With every knowledge source\'s adapter and embedder reachable, a search answers as before: hits, and refused ' + + 'empty. A search whose adapter is made to throw answers refused naming that source with code ' + + 'SERVICE_UNAVAILABLE; when no searched source answers and at least one threw without a code, it rejects, with ' + + 'status 503 when every searched source threw without a code, and with refused naming every refused source.', +}; diff --git a/packages/spec/src/migrations/entries/semantic/19.lowered-hook-and-action-bodies-capabilities-judged.ts b/packages/spec/src/migrations/entries/semantic/19.lowered-hook-and-action-bodies-capabilities-judged.ts new file mode 100644 index 00000000000..f26773980f2 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.lowered-hook-and-action-bodies-capabilities-judged.ts @@ -0,0 +1,58 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #38690 — `hook-body-capability-undeclared` and +// `action-body-capability-undeclared` (@objectstack/lint) now judge an L2 body +// beside a string hook `handler` or action `target`, lowered by the build or +// written by hand, the way they judge any other body. Until now such a body +// was taken for one the build lowered and skipped (a lowered action body was +// judged for `api.write` alone), because the build's capability inference did +// not yet read every gated call the rule reads; it does now, in each spelling +// the rule reads (`api.transaction` and reads through a bound handle since +// #38653; the member aliases, `?.`, whitespace, the optional call and a +// comment between steps since #38690). It narrows what the authoring doors +// accept; no key is removed, so there is no tombstone. Measured first-party +// exposure at this change: zero (the example apps and the first-party +// connector apps, loaded, normalized and lowered as `os validate` does). Not +// converted: whether the body should hold the grant or drop the call is the +// author's choice. +export const entry: SemanticMigration = { + id: 'lowered-hook-and-action-bodies-capabilities-judged', + surface: + 'hooks[].body and actions[].body (an object\'s inline actions[] included) whose body.language is js and that sit ' + + 'beside a string hook handler or action target, lowered by the build (os build / os verify, from an inline ' + + 'handler or target function) or written by hand, as loaded by os validate / os build / os lint or saved ' + + 'through the metadata doors (PUT /api/v1/meta/hook/NAME, PUT /api/v1/meta/action/NAME, an object write, the ' + + 'package publish doors): a source that calls a member the sandbox gates without its token in ' + + 'body.capabilities, for every token (an action body\'s writes were already judged)', + replacement: + 'A body written by hand beside a string handler or target: declare the token the finding names in ' + + 'body.capabilities (body.capabilities: [\'api.write\', \'api.transaction\'] for a body that writes inside ' + + 'ctx.api.transaction), or remove the call. A handler or target function the build lowers needs no change: os ' + + 'build infers the grant from each gated call in each spelling the rule reads (ctx.MEMBER, a local bound once ' + + 'to it, a destructure off ctx, a handle bound once to ctx.api.object(…), a hook handler\'s destructured ' + + 'context; ?. or whitespace or a comment between steps, the optional call), so its lowered body ' + + 'carries the token. A build artifact whose lowered body lost a token is refused at error as ' + + '`hook-body-capability-undeclared` or `action-body-capability-undeclared` (422 INVALID_METADATA at the hook ' + + 'and action doors): rebuild it, or declare the token. A hook body is never granted email.send: a hook handler ' + + 'that calls ctx.email.send, in any of those spellings, is refused at build by the hook parse; send the mail ' + + 'from an action, a job or a flow.', + reason: + 'The sandbox refuses a call the body was not granted with 403 INSUFFICIENT_PRIVILEGES at the call site, whether ' + + 'the author or the build wrote the grant. A body beside a string handler or target was exempt from the check ' + + 'because the rule took it for a lowered one, whose grant was the build\'s inference, and that inference missed ' + + 'calls the rule reads, so a finding there would have named a grant the build forgot. The inference now reads ' + + 'each gate of the rule\'s own table, through each receiver and in each spelling the rule reads, pinned ' + + 'spelling by spelling against the rule (each judged ungranted, drawing the finding, and lowered, drawing ' + + 'none), so a lowered body the rule refuses is one whose grant was lost after the build and that fails at the ' + + 'call every time it runs, and a hand-written body it refuses is one that fails the same way. The exemption ' + + 'only hid that failure until runtime. Stored metadata is not rewritten or refused at boot; the next publish of ' + + 'the hook, action or object is refused with the token named. Such a call never succeeded, so no stored row ' + + 'changes shape.', + acceptanceCriteria: + 'Run `os validate` or `os build` over a stack with inline hook handlers and action target functions: no ' + + '`hook-body-capability-undeclared` finding and no `action-body-capability-undeclared` finding. PUT ' + + '/api/v1/meta/hook/NAME and PUT /api/v1/meta/action/NAME with a rebuilt artifact\'s hook or action, or with a ' + + 'hand-written body beside a string handler or target that declares each token it calls, answer 200.', +}; diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 95419ecaa85..a94d37689ff 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -564,7 +564,13 @@ export const CEILINGS = new Map([ // text is 28990 -> ceil(28990 / 4) = 7248; the row moves +48, the measured // remainder only. Pinned AT the measurement. // ceil(($(wc -c < skills/objectstack-ai/SKILL.md) - 27) / 4) == ceil(28990 / 4) - ['skills/objectstack-ai/SKILL.md', 7248], + // -1 (was 7248): #38692 phase 1a added the `source.retrieval.mode` row and + // paid for it in the same file: the `adapter` row's save refusal names the + // mounted stores alone, the one-slot sentence of the source's identity went + // (the registry's 409 names both doors), and "Rerank and hybrid weighting" + // became one clause. Banked at the measurement. + // ceil(($(wc -c < skills/objectstack-ai/SKILL.md) - 27) / 4) == ceil(28987 / 4) + ['skills/objectstack-ai/SKILL.md', 7247], // -12 (was 6331): the `http.server` decision-table row dropped a trailing // clause that taught `contributes.routes` as a key that "parses but serves // nothing". The key is retired — an authored entry is now REFUSED, carrying diff --git a/skills/objectstack-ai/SKILL.md b/skills/objectstack-ai/SKILL.md index 9ea69808248..3a153de575b 100644 --- a/skills/objectstack-ai/SKILL.md +++ b/skills/objectstack-ai/SKILL.md @@ -239,8 +239,7 @@ in `@objectstack/spec/ai`). Ship it in a package (`knowledgeSources`, `KnowledgeServicePlugin({ sources })` and `registerSource` are a second door for the same schema. A source is identified by its package and `name`; the ☁️ `search_knowledge` tool lists a package's source to agents as `NAMESPACE-NAME` -(bare for one no package holds), and a code registration and an environment -item of one name are one slot, the second refused. A shipped item mounts the +(bare for one no package holds). A shipped item mounts the knowledge service and its store; where an app ships none, a run-time save is refused (`503 SERVICE_UNAVAILABLE`, nothing written) until you add `requires: ['knowledge']` to the stack and restart the server. @@ -255,13 +254,14 @@ object or field, when you may not search that object or query a field it reads. |:----|:--------| | `name` | Snake_case source name | | `label` / `description` | Display metadata | -| `adapter` | Store id (`pgvector`, `turso`, `memory`). Omitted: the deployment's store (`pgvector` on PostgreSQL, `turso` otherwise), else the only one registered; several and none the deployment's is refused, naming them. A run-time save naming one the deployment does not mount is refused (`400 VALIDATION_ERROR`, nothing written), naming the source, the adapter and the mounted ones: name a mounted one, or mount the store and save again | +| `adapter` | Store id (`pgvector`, `turso`, `memory`). Omitted: the deployment's store (`pgvector` on PostgreSQL, `turso` otherwise), else the only one registered; several and none the deployment's is refused, naming them. A run-time save naming a store not mounted is refused (`400`), naming the mounted ones | | `source.kind` | `'object'`, the one kind | | `source.object` | The object whose records are indexed | | `source.content` | Non-empty list of the fields whose text is indexed, in order. `'*'` is refused: it would also send fields added later. Never ids or system fields | | `source.metadataFields` | Fields kept for search-time filtering (`status`, `owner_id`, `tags`) | | `source.where` | ObjectQL `where`: keeps drafts and archived rows out | | `source.split` | How documents are cut into passages (below) | +| `source.retrieval.mode` | `'vector'` (by meaning), `'keyword'` (by words: codes, clause numbers) or `'hybrid'`; omitted: the store's default (`hybrid` on `turso`, `pgvector`). A mode the store lacks fails a run-time save; shipped, every search (503). `memory` runs none | | `refresh.onRecordChange` | Sync from record events (default `true`); `false` leaves the index to an external indexer | | `aiExposed` | May `search_knowledge` expose it (default `true`) | @@ -347,8 +347,8 @@ Retired: the `knowledge.chunk_overlap` setting (`400 UNKNOWN_KEY`; passages never overlap) and `KnowledgeChunk.metadata` (parse error; a passage takes its document's `metadata`). -`topK` is a `search_knowledge` argument. Rerank and hybrid weighting are no -source key, and no shipped store has a setting for either. +`topK` is a `search_knowledge` argument; rerank and leg weights are no source +key. --- diff --git a/skills/objectstack-platform/evals/config-plugins-ops.json b/skills/objectstack-platform/evals/config-plugins-ops.json index bdbacba6744..36eca684c74 100644 --- a/skills/objectstack-platform/evals/config-plugins-ops.json +++ b/skills/objectstack-platform/evals/config-plugins-ops.json @@ -343,9 +343,7 @@ "must_contain": [ "--preset minimal" ], - "must_not_contain": [ - "requires: ['storage', 'settings']" - ] + "must_not_contain": [] } }, { diff --git a/ui/packages/app-shell/src/views/RecordDetailView.citedSectionFieldTab-37802.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.citedSectionFieldTab-37802.test.tsx new file mode 100644 index 00000000000..7bd8a205109 --- /dev/null +++ b/ui/packages/app-shell/src/views/RecordDetailView.citedSectionFieldTab-37802.test.tsx @@ -0,0 +1,218 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37802 — a cited section (`?section=ANCHOR`, ADR-0160 D9) whose + * field sits in one of the object's field tabs (`ObjectSchema.fieldTabs`) + * opens that tab first, then scrolls to and marks the heading, through the + * REAL `RecordDetailView` (the harness is objectstack#37365's): + * + * - the `body` group drawn as the tab `fields:body`: `?section=scope` opens + * that tab (`?related=fields:body` beside `?section=` in the address) + * and marks `Scope` in it; + * - CONTROL: the same object without `fieldTabs` marks the heading in the + * overview and opens no tab; + * - a cited field the overview draws (`notes`, the `basic` group) opens no tab + * beside the field tab. + */ + +import * as React from 'react'; +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, cleanup, within, act, waitFor } from '@testing-library/react'; +import { MemoryRouter, useLocation } from 'react-router-dom'; + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u-ada', name: 'Ada', image: null }, activeOrganization: null }), + createAuthenticatedFetch: () => vi.fn(), +})); +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ + ...(await importOriginal>()), + useRecordPresence: () => [], + PresenceAvatars: () => null, +})); +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), + error: vi.fn(), + info: vi.fn(), + warning: vi.fn(), + loading: vi.fn(), + dismiss: vi.fn(), + }), +})); +vi.mock('./ActionParamDialog', () => ({ ActionParamDialog: () => null })); +vi.mock('./ActionResultDialog', () => ({ ActionResultDialog: () => null })); +vi.mock('./FlowRunner', () => ({ FlowRunner: () => null })); +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), +})); + +// The markdown face is lazily loaded by the cell renderer; importing it here +// moves its load into the import phase (ui/AGENTS.md, flaky-test discipline). +import '../../../fields/src/widgets/MarkdownContent'; +import { I18nProvider } from '@object-ui/i18n'; +import { MetadataCtx } from '@object-ui/react'; +import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; +import { RecordDetailView } from './RecordDetailView'; +import { RECORD_SECTION_TARGET_ATTR } from './recordSectionAnchor'; + +const OBJECT_NAME = 'policy'; +const RECORD_ID = 'pol_7'; + +const BODY = ['# Intro', '', 'Hello.', '', '## Scope', '', 'Everyone.'].join('\n'); +const NOTES = ['# Steps', '', 'Sign the sheet.'].join('\n'); + +const FIELDS = { + id: { type: 'text', label: 'Id' }, + title: { type: 'text', label: 'Title', group: 'basic' }, + content: { type: 'markdown', label: 'Content', group: 'body' }, + notes: { type: 'textarea', label: 'Notes', group: 'basic' }, +}; +const FIELD_GROUPS = [ + { key: 'basic', label: 'Basic' }, + { key: 'body', label: 'Body' }, +]; +/** The policy as served: its body group drawn as a field tab, or (CONTROL) in the overview. */ +const objectsWith = (fieldTabs?: unknown) => [ + { name: OBJECT_NAME, label: 'Policy', fields: FIELDS, fieldGroups: FIELD_GROUPS, enable: { feeds: false }, ...(fieldTabs ? { fieldTabs } : {}) }, +]; +let OBJECTS = objectsWith(); + +function makeDataSource(content = BODY) { + return { + find: vi.fn(async () => ({ data: [] })), + findOne: vi.fn(async (_o: string, id: string) => ({ id, title: `Policy ${id}`, content, notes: NOTES })), + create: vi.fn(async (_o: string, data: any) => ({ id: 'x', ...data })), + update: vi.fn(async (_o: string, id: string, patch: any) => ({ id, ...patch })), + delete: vi.fn(async () => true), + } as any; +} + +function metadata() { + return { + objects: OBJECTS, + pages: [], + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => [], + getItem: async () => null, + getItemsByType: (type: string) => (type === 'object' ? OBJECTS : []), + getTypeStatus: () => 'ready', + } as any; +} + +const FULL = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; +const PERMS = { + authenticated: true, + userId: 'u-ada', + tenantId: null, + positions: ['member'], + hasAnyQueue: false, + objectsUsingQueues: [], + permissionSets: ['member'], + objects: { [OBJECT_NAME]: FULL }, + fields: {}, +} as MePermissionsAuthenticatedResponse; + +/** The router's current search, written after each render the probe makes. */ +const probe = { search: '' }; +function LocationProbe() { + const location = useLocation(); + React.useEffect(() => { + probe.search = location.search; + }); + return null; +} + +async function mount(search: string) { + // The page opens a tab off the window's address (`openEnlargedRelated`), as + // the browser router keeps it: the memory router's entry is mirrored there. + window.history.replaceState(null, '', `/apps/compliance/${OBJECT_NAME}/record/${RECORD_ID}${search}`); + const rendered = render( + + + + + + {}} + objectNameOverride={OBJECT_NAME} + recordIdOverride={RECORD_ID} + /> + + + + , + ); + await within(rendered.container) + .findAllByText(`Policy ${RECORD_ID}`, undefined, { timeout: 4000 }) + .catch(() => undefined); + await act(async () => {}); + return rendered; +} + +let scrolled: HTMLElement[] = []; +const originalScroll = HTMLElement.prototype.scrollIntoView; + +beforeEach(() => { + scrolled = []; + probe.search = ''; + HTMLElement.prototype.scrollIntoView = function (this: HTMLElement) { + scrolled.push(this); + }; + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } })), + ); +}); + +afterEach(async () => { + cleanup(); + // The page forgets the section it opened once it has stayed unmounted (objectstack#37487 S5). + await new Promise((resolve) => setTimeout(resolve, 0)); + HTMLElement.prototype.scrollIntoView = originalScroll; + vi.unstubAllGlobals(); + vi.clearAllMocks(); + OBJECTS = objectsWith(); + window.history.replaceState(null, '', '/'); +}); + +const marked = (root: HTMLElement) => Array.from(root.querySelectorAll(`[${RECORD_SECTION_TARGET_ATTR}]`)); +const openTab = () => new URLSearchParams(probe.search).get('related'); +const citedSection = () => new URLSearchParams(probe.search).get('section'); + +describe('a cited section inside a field tab (objectstack#37802)', () => { + it('opens the field tab first, then marks the heading in it', async () => { + OBJECTS = objectsWith([{ key: 'body', groups: ['body'] }]); + const { container } = await mount('?section=scope'); + await waitFor(() => expect(openTab()).toBe('fields:body'), { timeout: 4000 }); + // The citation stays in the address beside the open tab. + expect(citedSection()).toBe('scope'); + await waitFor(() => expect(marked(container)).toHaveLength(1), { timeout: 4000 }); + const heading = marked(container)[0]; + expect(heading.textContent).toBe('Scope'); + expect(heading.closest('[data-record-field-tab="fields:body"]')).not.toBeNull(); + expect(scrolled).toEqual([heading]); + }); + + it('CONTROL: without fieldTabs the heading is marked in the overview and no tab opens', async () => { + const { container } = await mount('?section=scope'); + await waitFor(() => expect(marked(container)).toHaveLength(1), { timeout: 4000 }); + expect(marked(container)[0].closest('[data-record-field-tab]')).toBeNull(); + expect(openTab()).toBeNull(); + }); + + it('a cited field the overview draws opens no tab beside the field tab', async () => { + OBJECTS = objectsWith([{ key: 'body', groups: ['body'] }]); + await mount('?section=steps'); + await waitFor(() => expect(scrolled).toHaveLength(1), { timeout: 4000 }); + expect(scrolled[0].getAttribute('data-detail-field')).toBe('notes'); + expect(openTab()).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index eafcaf7c495..494590a6ffa 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -10,7 +10,7 @@ import { useState, useEffect, useLayoutEffect, useCallback, useContext, useMemo, useRef, type ReactElement } from 'react'; import { useParams, useNavigate, useLocation, useSearchParams, Link } from 'react-router-dom'; -import { activityRowToFeedItem, buildCommentThreads, CommentsButton, CommentsPage, RecordCommentsInPanelContext, composeImpersonatedActor, IMPERSONATED_ACTOR_FALLBACK, auditEntriesToFeedItems, bodyTableIdsOf, claimQueuedRecord, RECORD_PAGE_TIMELINE_PANEL, RECORD_TIMELINE_PANEL_MAX_ENTRIES, RecordFieldChangesContext, RecordFieldHistoryContext, RecordTimelineTotalContext, RecordViewApprovalsContext, DefaultRecordPageContext, EMPTY_RELATED_ARRANGEMENT, InlineEditSaveBar, RECORD_PAGE_DETAILS_WIDTH, RecordBodyTablesContext, RecordMetaFooter, RecordPageColumns, buildDefaultPageColumns, buildDefaultPageSchema, extractMentions, recordSitsInQueue, resolveTitleField, useQueueClaimOffered, useRecordEditable, useRecordPageTier } from '@object-ui/plugin-detail'; +import { activityRowToFeedItem, buildCommentThreads, CommentsButton, CommentsPage, RecordCommentsInPanelContext, composeImpersonatedActor, IMPERSONATED_ACTOR_FALLBACK, auditEntriesToFeedItems, bodyTableIdsOf, claimQueuedRecord, RECORD_PAGE_TIMELINE_PANEL, RECORD_TIMELINE_PANEL_MAX_ENTRIES, RecordFieldChangesContext, RecordFieldHistoryContext, RecordTimelineTotalContext, RecordViewApprovalsContext, DefaultRecordPageContext, EMPTY_RELATED_ARRANGEMENT, InlineEditSaveBar, RECORD_PAGE_DETAILS_WIDTH, RecordBodyTablesContext, RecordMetaFooter, RecordPageColumns, buildDefaultPageColumns, buildDefaultPageSchema, extractMentions, fieldTabIdOfField, recordSitsInQueue, resolveTitleField, useQueueClaimOffered, useRecordEditable, useRecordPageTier } from '@object-ui/plugin-detail'; import { isRefusedFeedRead } from '@object-ui/plugin-detail/core'; // objectstack#36075 — the comment panel's unresolved count and the moderator's verdict. import { unresolvedThreadCount, useRecordVerdict } from '@object-ui/plugin-detail'; @@ -925,6 +925,29 @@ const ignoreArrangementChange = (): void => {}; let lastCitedSectionOpen: { target: string; opened: string } | null = null; let mountedRecordPages = 0; +/** + * objectstack#37802 — opens the field tab a cited section sits in, once per + * citation (`citation` spells the record, anchor and chip click, as the + * section effect's key does), in place of the entry: a tab switch afterwards + * keeps the citation and opens nothing. Draws nothing. + */ +function OpenCitedFieldTab({ + tab, + citation, + open, +}: { + tab: string; + citation: string; + open: (id: string, options?: { replace?: boolean }) => void; +}): null { + useEffect(() => { + open(tab, { replace: true }); + // Once per citation: `open` is re-made on every navigation. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [tab, citation]); + return null; +} + /** Whether a cited-section open is a new one, and record it when it is. */ function claimCitedSectionOpen(target: string, opened: string): boolean { const last = lastCitedSectionOpen; @@ -5835,6 +5858,16 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // page and for a page whose strip the partition cannot read, which is drawn // as written, tabs and all. const pageColumns = pageColumnsEligible ? buildDefaultPageColumns(renderedPage) : null; + // objectstack#37802 — a cited section (`?section=`) whose field sits in one + // of the object's field tabs (`fieldTabs`): that tab opens first + // (`OpenCitedFieldTab`, drawn beside the laid-out page), and the section + // effect above finds the heading once the tab draws it. A cited field the + // overview draws opens nothing. + const citedFieldTab = + pageColumns && citedSectionCandidates.length > 0 + && citedSectionCandidates.every((c) => fieldTabIdOfField(pageColumns, objectDef, c.field) !== null) + ? fieldTabIdOfField(pageColumns, objectDef, citedSectionCandidates[0].field) + : null; // The child objects' field definitions this view already holds, for the // related counts asked up front (objectstack#27056): the relationship's // arity is read off them instead of a schema read first. @@ -6581,6 +6614,9 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri + {citedFieldTab && citedSectionKey && ( + + )} { + // Radix Select reads pointer capture and scrolls the open item into view; jsdom has neither. + for (const m of ['hasPointerCapture', 'setPointerCapture', 'releasePointerCapture'] as const) { + if (!(m in Element.prototype)) { + (Element.prototype as unknown as Record)[m] = m === 'hasPointerCapture' ? () => false : () => {}; + } + } + if (!Element.prototype.scrollIntoView) Element.prototype.scrollIntoView = () => {}; +}); + +const Picker = WIDGETS['knowledge-retrieval-mode']; + +function contextOf(store: KnowledgeStoreRetrieval | 'loading' | 'error'): WidgetContext { + return { + conditionScope: 'none', + knowledgeRetrieval: + store === 'loading' + ? { status: 'loading' } + : store === 'error' + ? { status: 'error', message: 'index_status answered 403' } + : { status: 'loaded', data: store }, + }; +} + +function open() { + fireEvent.pointerDown(screen.getByTestId('knowledge-retrieval-mode'), { button: 0, ctrlKey: false, pointerType: 'mouse' }); +} + +const optionNames = () => screen.getAllByRole('option').map((o) => o.textContent); + +describe('the published retrieval-mode row (objectstack#38692)', () => { + it('names the picker, under source.retrieval', () => { + type Row = { field?: string; widget?: string; fields?: Row[] }; + const found: Array<{ path: string; widget?: string }> = []; + const walk = (list: Row[] | undefined, path: string) => { + for (const row of list ?? []) { + const at = path ? `${path}.${row.field}` : String(row.field); + if (row.widget === 'knowledge-retrieval-mode') found.push({ path: at, widget: row.widget }); + walk(row.fields, at); + } + }; + for (const section of (knowledgeSourceForm as { sections?: Array<{ fields?: Row[] }> }).sections ?? []) walk(section.fields, ''); + expect(found).toEqual([{ path: 'source.retrieval.mode', widget: 'knowledge-retrieval-mode' }]); + }); + + it('declares control labelling, so the host label names the trigger', () => { + expect(WIDGET_LABELLING['knowledge-retrieval-mode']).toBe('control'); + }); +}); + +describe('knowledge-retrieval-mode widget (objectstack#38692)', () => { + const turso: KnowledgeStoreRetrieval = { adapter: 'turso', mounted: true, modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' }; + + it("offers the store's modes, and names which one its default is", async () => { + render( {}} schema={{}} context={contextOf(turso)} />); + expect(screen.getByTestId('knowledge-retrieval-mode')).toHaveTextContent('Store default (Hybrid (both))'); + open(); + await screen.findAllByRole('option'); + expect(optionNames()).toEqual([ + 'Store default (Hybrid (both))', + 'Vector only (by meaning)', + 'Keyword only (by words)', + 'Hybrid (both)', + ]); + }); + + it('offers only the modes a store lists', async () => { + render( + {}} + schema={{}} + context={contextOf({ adapter: 'vec', mounted: true, modes: ['vector'], default: 'vector' })} + />, + ); + open(); + await screen.findAllByRole('option'); + expect(optionNames()).toEqual(['Store default (Vector only (by meaning))', 'Vector only (by meaning)']); + }); + + it('a store that reports no modes: the default alone, and the sentence that it declares none', async () => { + render( {}} schema={{}} context={contextOf({ adapter: 'memory', mounted: true })} />); + expect(screen.getByTestId('knowledge-retrieval-mode-undeclared')).toHaveTextContent( + 'The store memory declares no retrieval modes, so leave this blank.', + ); + open(); + await screen.findAllByRole('option'); + expect(optionNames()).toEqual(['Store default']); + }); + + it('a stored mode the store does not run is kept as its own option, flagged', async () => { + render( {}} schema={{}} context={contextOf({ adapter: 'memory', mounted: true })} />); + expect(screen.getByTestId('knowledge-retrieval-mode')).toHaveTextContent('Keyword only (by words) (this store does not run it)'); + }); + + it('without the store answer (refused read, unmounted store, no host): the three modes', async () => { + for (const context of [contextOf('error'), contextOf({ adapter: 'pgvector', mounted: false }), undefined]) { + render( {}} schema={{}} context={context} />); + expect(screen.queryByTestId('knowledge-retrieval-mode-undeclared')).toBeNull(); + open(); + await screen.findAllByRole('option'); + expect(optionNames()).toEqual(['Store default', 'Vector only (by meaning)', 'Keyword only (by words)', 'Hybrid (both)']); + cleanup(); + } + }); + + it('a mode writes its name; the default removes the key', async () => { + const onChange = vi.fn(); + render(); + open(); + fireEvent.click(await screen.findByRole('option', { name: 'Keyword only (by words)' })); + expect(onChange).toHaveBeenLastCalledWith('keyword'); + cleanup(); + render(); + open(); + fireEvent.click(await screen.findByRole('option', { name: 'Store default (Hybrid (both))' })); + expect(onChange).toHaveBeenLastCalledWith(undefined); + }); + + it('is disabled while loading and read-only', () => { + render( {}} schema={{}} context={contextOf('loading')} />); + expect(screen.getByDisplayValue('vector')).toBeDisabled(); + cleanup(); + render( {}} schema={{}} readOnly context={contextOf(turso)} />); + expect(screen.getByTestId('knowledge-retrieval-mode')).toBeDisabled(); + }); +}); + +describe('storeRetrievalOf — the store a source binds to, from an index_status answer', () => { + const body = { + success: true, + data: { + ok: true, + details: { + sources: [], + adapters: [ + { id: 'turso', retrieval: { modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' } }, + { id: 'memory' }, + ], + defaultAdapter: 'turso', + }, + }, + }; + + it("the named store, else the deployment's", () => { + expect(storeRetrievalOf(body, 'memory')).toEqual({ adapter: 'memory', mounted: true }); + expect(storeRetrievalOf(body, undefined)).toEqual({ + adapter: 'turso', + mounted: true, + modes: ['vector', 'keyword', 'hybrid'], + default: 'hybrid', + }); + }); + + it('a store not mounted, or none placed, is not mounted', () => { + expect(storeRetrievalOf(body, 'pgvector')).toEqual({ adapter: 'pgvector', mounted: false }); + const unplaced = { success: true, data: { details: { adapters: [] } } }; + expect(storeRetrievalOf(unplaced, undefined)).toEqual({ mounted: false }); + }); + + it('a body with no list of stores is a failed read, never an empty one', () => { + expect(() => storeRetrievalOf({ success: true, data: { details: {} } }, undefined)).toThrow(/no list of stores/); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx index 448ab7027ed..7b217ee0ab5 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx @@ -111,6 +111,7 @@ import { conditionSubjectsForMetadataType, } from './conditionScope.js'; import { mapLoaded, usePickerLoad } from './loadState.js'; +import { fetchStoreRetrieval, type KnowledgeStoreRetrieval } from './knowledgeRetrieval.js'; import { useCapabilityAudienceLoader } from './useCapabilityAudienceLoader.js'; import { useMetadataClient, @@ -1409,6 +1410,26 @@ function MetadataResourceEditPageImpl({ ), ); + // objectstack#38692 phase 1a — the store a knowledge source binds to (the + // one its `adapter` names, else the deployment's) and the retrieval modes it + // runs, for the `knowledge-retrieval-mode` picker. Loaded only when the form + // on screen declares that widget, and again when the source names another + // store. + const declaresRetrievalMode = formDeclaresWidget( + createMode && config.createSchema ? undefined : entry?.form, + 'knowledge-retrieval-mode', + ); + const draftAdapter = + typeof (draft as { adapter?: unknown } | null)?.adapter === 'string' && (draft as { adapter: string }).adapter.trim() + ? (draft as { adapter: string }).adapter.trim() + : undefined; + const knowledgeRetrievalState = usePickerLoad( + React.useMemo( + () => (declaresRetrievalMode ? () => fetchStoreRetrieval(draftAdapter) : null), + [declaresRetrievalMode, draftAdapter], + ), + ); + // objectstack#34908 — the audience catalog for the `ref-multi:capability` // picker (a list view's or a dashboard's `requiredPermissions`): the // capabilities the environment knows, the permission sets granting each and @@ -1476,8 +1497,18 @@ function MetadataResourceEditPageImpl({ componentIds, permissionSets: permissionSetsState, loadCapabilityAudience, + knowledgeRetrieval: knowledgeRetrievalState, }), - [type, objectsState, objectCatalogState, objectViewsState, componentIds, permissionSetsState, loadCapabilityAudience], + [ + type, + objectsState, + objectCatalogState, + objectViewsState, + componentIds, + permissionSetsState, + loadCapabilityAudience, + knowledgeRetrievalState, + ], ); // Load layered view + initial draft. diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.authoredPackageSource-38150.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.authoredPackageSource-38150.test.tsx index ef6e26b005b..655b65fd6d5 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.authoredPackageSource-38150.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.authoredPackageSource-38150.test.tsx @@ -56,6 +56,13 @@ const fixture = vi.hoisted(() => ({ packagesStatus: 200, /** How many times the package list was asked for. */ packagesReads: 0, + /** + * The package list does not answer within the case: an order that waits on + * it is never ready. Each held answer is released after the case, so the + * shared package-list read never carries a held request into the next one. + */ + packagesHang: false, + heldPackages: [] as Array<() => void>, })); const CLIENT = { @@ -99,6 +106,9 @@ const fetchMock = vi.fn(async (url: string) => { const u = String(url); if (u === '/api/v1/packages') { fixture.packagesReads += 1; + if (fixture.packagesHang) { + return new Promise((resolve) => fixture.heldPackages.push(() => resolve(json(503, { success: false })))); + } if (fixture.packagesStatus !== 200) return json(fixture.packagesStatus, { success: false }); return json(200, { success: true, @@ -134,9 +144,12 @@ beforeEach(() => { fixture.locale = 'en-US'; fixture.packagesStatus = 200; fixture.packagesReads = 0; + fixture.packagesHang = false; }); -afterEach(() => { +afterEach(async () => { cleanup(); + for (const release of fixture.heldPackages.splice(0)) release(); + await new Promise((resolve) => setTimeout(resolve, 0)); vi.unstubAllGlobals(); }); @@ -301,6 +314,19 @@ describe('on /studio/~all/metadata/flow, the source filter and ‹ › agree wit }); }); +describe('objectstack#38620 — ‹ › under "Loose" never ask for the package list', () => { + it('source=loose walks the package-less flows with no package-list request, and does not wait on one', async () => { + fixture.packagesHang = true; + expect(await orderedNames('?source=loose')).toEqual(['loose_flow']); + expect(fixture.packagesReads).toBe(0); + }); + + it('CONTROL — a source value the package verdict narrows still asks for the package list', async () => { + expect(await orderedNames('?source=runtime')).toEqual(['authored_flow', 'loose_flow']); + expect(fixture.packagesReads).toBeGreaterThan(0); + }); +}); + describe("on the authored package's own leg", () => { it('its flow is under "modified and new", and "system-shipped" is empty', async () => { mount(ON_AUTHORED, '?source=runtime'); 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.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/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/useListOrderedNames.ts b/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts index ecc3de8d342..689e9573efd 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts @@ -110,9 +110,12 @@ export function useListOrderedNames(type: string): ListOrderedNames { return pair.ok ? pair.value : null; }, [host?.packageId, envScope]); const customizations = usePackageCustomizations(host?.packageId ?? null); - // objectstack#38150 — the Studio list's Source reads whether a row's package - // is one the author can write; asked only when the order is narrowed by it. - const sourceNarrowed = studioList && state.source !== 'all'; + // 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); 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/fields/src/widgets/MarkdownContent.tsx b/ui/packages/fields/src/widgets/MarkdownContent.tsx index a6a4548844d..64c2197abb3 100644 --- a/ui/packages/fields/src/widgets/MarkdownContent.tsx +++ b/ui/packages/fields/src/widgets/MarkdownContent.tsx @@ -5,6 +5,7 @@ import { RICH_TEXT_CELL_FACE_CLASS, RICH_TEXT_DOCUMENT_CLASS, cellFaceHeadings, + documentFaceTables, type RichTextFace, } from './richTextDisplay.js'; @@ -28,40 +29,11 @@ export { MARKDOWN_REHYPE_PLUGINS, MARKDOWN_REMARK_PLUGINS, drawnMarkdownHeadings const CELL_COMPONENTS: Components = cellFaceHeadings('data-markdown-heading'); /** - * The box a document-face GFM table is drawn in (objectstack#38702). - * - * A table sitting straight in the prose box has nowhere to go when it is - * wider than the text column: the typography scale gives it `width: 100%`, so - * the table layout first squeezes every column down to its min-content width - * (a CJK cell can break between any two characters, so 「考核内容」 is drawn - * one character per line), and a table whose min-content is still wider than - * the column overflows the prose box and scrolls the whole record page - * sideways, its header and tab bar with it. - * - * - `max-w-full overflow-x-auto` makes the box its own horizontal scroller, - * bounded by the text column, so a wide table scrolls inside it and never - * past it. - * - `min-w-[6em]` on every `th` / `td` is the floor a column is squeezed to: - * four CJK characters after the cell padding, so a short phrase stays on one - * line and a table with many columns becomes wider than the column, which is - * what lets the box scroll instead of the cells breaking. A longer cell - * still wraps at its own words; ordinary paragraphs keep `break-words`. - * - * The cell face draws no such box: a grid cell is one line of its own text. - * `@object-ui/plugin-markdown` (`MarkdownImpl.tsx`) draws the same box; the - * two packages do not depend on each other, so change the two together. + * In the document face every GFM table is drawn in its own horizontal scroll + * box, the box the html / richtext document face draws too (see + * `documentFaceTables`, objectstack#38702). */ -const DOCUMENT_TABLE_SCROLL_CLASS = 'max-w-full overflow-x-auto [&_td]:min-w-[6em] [&_th]:min-w-[6em]'; - -const DOCUMENT_COMPONENTS: Components = { - table({ node: _node, ...rest }) { - return ( -
- - - ); - }, -}; +const DOCUMENT_COMPONENTS: Components = documentFaceTables('data-markdown-table-scroll'); /** * Heavy markdown renderer, split into its own module so it can be lazy-loaded diff --git a/ui/packages/fields/src/widgets/__tests__/sanitizedHtml.test.tsx b/ui/packages/fields/src/widgets/__tests__/sanitizedHtml.test.tsx index 72abbf19ad5..4319300b577 100644 --- a/ui/packages/fields/src/widgets/__tests__/sanitizedHtml.test.tsx +++ b/ui/packages/fields/src/widgets/__tests__/sanitizedHtml.test.tsx @@ -27,7 +27,7 @@ import React from 'react'; import { describe, it, expect, afterEach } from 'vitest'; import { render, cleanup } from '@testing-library/react'; import '@testing-library/jest-dom'; -import { HtmlCellRenderer, RICH_TEXT_CELL_RENDERERS } from '../richTextDisplay'; +import { DOCUMENT_TABLE_SCROLL_CLASS, HtmlCellRenderer, RICH_TEXT_CELL_RENDERERS } from '../richTextDisplay'; import { RICH_TEXT_SANITIZE_SCHEMA } from '../sanitizedHtml'; afterEach(cleanup); @@ -180,9 +180,20 @@ const FORMATTED_DOCUMENT = [ '
More

Hidden detail.

', ].join(''); +/** + * The same document as the document face draws it: byte for byte, except that + * the table sits in its own scroll box (objectstack#38717). The box's class is + * written the way `innerHTML` serialises an attribute, `&` as `&`. + */ +const DRAWN_DOCUMENT = FORMATTED_DOCUMENT.replace( + '
', + `
`, +).replace('
', '
'); + describe('html / richtext display: a formatted document keeps its formatting', () => { it('round-trips byte for byte', () => { - expect(renderHtml(FORMATTED_DOCUMENT).innerHTML).toBe(FORMATTED_DOCUMENT); + expect(DRAWN_DOCUMENT).not.toBe(FORMATTED_DOCUMENT); + expect(renderHtml(FORMATTED_DOCUMENT).innerHTML).toBe(DRAWN_DOCUMENT); }); it('keeps the safe part of a mixed value', () => { @@ -202,3 +213,72 @@ describe('html / richtext display: a formatted document keeps its formatting', ( expect(renderHtml('5 < 6 & 7 > 3').textContent).toBe('5 < 6 & 7 > 3'); }); }); + +/** + * objectstack#38717 — in the document face (the record page, a readonly form + * field) a stored table is drawn in its own horizontal scroll box, bounded by + * the text column, and its cells keep a minimum width: the box the markdown + * document face draws (objectstack#38702). Before, the table sat straight in + * the prose box, so a many-column table was squeezed until its CJK cells broke + * one character per line, and a wider one scrolled the whole page sideways. + * + * jsdom does no layout, so these pins read the element and class contract the + * scrolling rests on; the browser readings are in the pull request. + */ +describe('html / richtext display: a document-face table scrolls inside its own box', () => { + const header = Array.from({ length: 11 }, (_, i) => `考核指标${i + 1}`).join(''); + const row = Array.from({ length: 11 }, () => '考核内容').join(''); + const WIDE_TABLE = `${header}${row}
`; + + it('wraps the table in a width-bounded horizontal scroll box with a cell minimum width', () => { + const prose = renderHtml(`

Intro.

${WIDE_TABLE}

After.

`); + expect(prose).toHaveAttribute('data-html-face', 'document'); + const table = prose.querySelector('table'); + expect(table).not.toBeNull(); + const box = table!.parentElement!; + expect(box).toHaveAttribute('data-html-table-scroll'); + expect(box).toHaveClass('max-w-full', 'overflow-x-auto', '[&_th]:min-w-[6em]', '[&_td]:min-w-[6em]'); + // The box sits in the prose box itself, between the two paragraphs. + expect(box.parentElement).toBe(prose); + expect(box.previousElementSibling?.textContent).toBe('Intro.'); + expect(box.nextElementSibling?.textContent).toBe('After.'); + // The table keeps its content: 11 header cells, one body row. + expect(table!.querySelectorAll('thead th')).toHaveLength(11); + expect(table!.querySelectorAll('tbody tr')).toHaveLength(1); + }); + + it('draws one box per table, a nested table included', () => { + const prose = renderHtml( + `${WIDE_TABLE}

text

inner
`, + ); + const tables = prose.querySelectorAll('table'); + expect(tables).toHaveLength(3); + for (const table of tables) expect(table.parentElement).toHaveAttribute('data-html-table-scroll'); + }); + + it('draws the box after the sanitiser: what a stored table carries is still neutralised', () => { + const prose = renderHtml( + '
x
', + ); + expect(prose.querySelector('[data-html-table-scroll] > table')).not.toBeNull(); + expectInert(prose, 'table inside the scroll box'); + }); + + it('CONTROL — a value with no table draws no box', () => { + const prose = renderHtml('

Just a paragraph.

  • one
'); + expect(prose).toHaveClass('break-words'); + expect(prose.querySelector('[data-html-table-scroll]')).toBeNull(); + }); + + it('CONTROL — the cell face (a grid column) draws no box', () => { + const { container } = render( + , + ); + const face = container.querySelector('[data-html-face]')!; + expect(face).toHaveAttribute('data-html-face', 'cell'); + const table = face.querySelector('table'); + expect(table).not.toBeNull(); + expect(table!.parentElement).toBe(face); + expect(face.querySelector('[data-html-table-scroll]')).toBeNull(); + }); +}); diff --git a/ui/packages/fields/src/widgets/richTextDisplay.tsx b/ui/packages/fields/src/widgets/richTextDisplay.tsx index 2522ff93699..41a7b7c73ef 100644 --- a/ui/packages/fields/src/widgets/richTextDisplay.tsx +++ b/ui/packages/fields/src/widgets/richTextDisplay.tsx @@ -109,9 +109,66 @@ export function cellFaceHeadings( return { h1: CellHeading, h2: CellHeading, h3: CellHeading, h4: CellHeading, h5: CellHeading, h6: CellHeading }; } +/** + * The box a document-face table is drawn in, by both pipelines + * (objectstack#38702 for markdown, objectstack#38717 for html / richtext). + * + * A table sitting straight in the prose box has nowhere to go when it is + * wider than the text column: the typography scale gives it `width: 100%`, so + * the table layout first squeezes every column down to its min-content width + * (a CJK cell can break between any two characters, so 「考核内容」 is drawn + * one character per line), and a table whose min-content is still wider than + * the column overflows the prose box and scrolls the whole record page + * sideways, its header and tab bar with it. + * + * - `max-w-full overflow-x-auto` makes the box its own horizontal scroller, + * bounded by the text column, so a wide table scrolls inside it and never + * past it. + * - `min-w-[6em]` on every `th` / `td` is the floor a column is squeezed to: + * four CJK characters after the cell padding, so a short phrase stays on one + * line and a table with many columns becomes wider than the column, which is + * what lets the box scroll instead of the cells breaking. A longer cell + * still wraps at its own words; ordinary paragraphs keep `break-words`. + * + * The cell face draws no such box: a grid cell is one line of its own text. + * `@object-ui/plugin-markdown` (`MarkdownImpl.tsx`) draws the same box; the + * two packages do not depend on each other, so change the two together. + */ +export const DOCUMENT_TABLE_SCROLL_CLASS = 'max-w-full overflow-x-auto [&_td]:min-w-[6em] [&_th]:min-w-[6em]'; + +type DocumentTableComponent = ( + props: React.ComponentPropsWithoutRef<'table'> & { node?: unknown }, +) => React.ReactElement; + +/** + * The element map the document face draws tables with: every `table` inside + * its own {@link DOCUMENT_TABLE_SCROLL_CLASS} box, the box carrying `marker` + * so the pipeline's own pins can find it. The markdown pipeline hands it to + * react-markdown; the HTML pipeline hands it to {@link renderSanitizedHtml}, + * which applies it after the sanitiser has run, so the box changes how a kept + * table is drawn and never what is kept. + * + * Call it once per pipeline at module scope, for the reason + * {@link cellFaceHeadings} gives. + */ +export function documentFaceTables( + marker: 'data-markdown-table-scroll' | 'data-html-table-scroll', +): { table: DocumentTableComponent } { + // react-markdown passes the hast `node`; it is not a DOM attribute. + const DocumentTable: DocumentTableComponent = ({ node: _node, ...rest }) => ( +
+ + + ); + return { table: DocumentTable }; +} + /** The HTML pipeline's cell-face headings. */ const HTML_CELL_HEADINGS = cellFaceHeadings('data-html-heading'); +/** The HTML pipeline's document-face tables, each in its own scroll box. */ +const HTML_DOCUMENT_TABLES = documentFaceTables('data-html-table-scroll'); + /** * The text a rich-content cell formats, or `undefined` when the record holds * nothing to format (objectui#8580). @@ -209,7 +266,9 @@ export function MarkdownCellRenderer({ value, inGridColumn }: CellRendererProps) * is drawn with; what the sanitiser keeps and drops is the same in both * faces. Every other caller — the record page, a readonly form field — keeps * the `document` face and its heading elements, at the face's sizes - * (objectstack#37801). + * (objectstack#37801), and draws each stored table in its own horizontal + * scroll box ({@link documentFaceTables}, objectstack#38717), the box the + * markdown document face draws too. * * The parse is memoised on the text and the face for cost only (a grid * renders many cells); nothing depends on the identity of the memoised value. @@ -221,7 +280,7 @@ export function HtmlCellRenderer({ value, inGridColumn }: CellRendererProps): Re () => text === undefined ? undefined - : renderSanitizedHtml(text, face === 'cell' ? HTML_CELL_HEADINGS : undefined), + : renderSanitizedHtml(text, face === 'cell' ? HTML_CELL_HEADINGS : HTML_DOCUMENT_TABLES), [text, face], ); if (text === undefined) return ; diff --git a/ui/packages/fields/src/widgets/sanitizedHtml.tsx b/ui/packages/fields/src/widgets/sanitizedHtml.tsx index 3969ed9efe8..386cb1d11db 100644 --- a/ui/packages/fields/src/widgets/sanitizedHtml.tsx +++ b/ui/packages/fields/src/widgets/sanitizedHtml.tsx @@ -151,7 +151,8 @@ function childrenOf(parent: ParentNode): HastChild[] { * sanitizing path. * * `components` maps element names to the components the SANITIZED tree is - * drawn with — the grid cell face draws headings as bold lines with it. It is + * drawn with — the grid cell face draws headings as bold lines with it, and + * the document face draws each table inside its own scroll box. It is * applied after the sanitiser has run, so it changes how a kept element is * drawn and never what is kept. */ diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index cf146df04cf..66a931a27c0 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -1813,6 +1813,13 @@ const STUDIO_EN: Record = { 'engine.form.invalid': '(invalid)', 'engine.form.notPublished': '(not published)', 'engine.form.flaggedValue': '{value} {flag}', + 'engine.form.retrievalMode.vector': 'Vector only (by meaning)', + 'engine.form.retrievalMode.keyword': 'Keyword only (by words)', + 'engine.form.retrievalMode.hybrid': 'Hybrid (both)', + 'engine.form.retrievalMode.default': 'Store default', + 'engine.form.retrievalMode.defaultIs': 'Store default ({mode})', + 'engine.form.retrievalMode.notRun': '(this store does not run it)', + 'engine.form.retrievalMode.undeclared': 'The store {store} declares no retrieval modes, so leave this blank.', 'engine.form.searchIcons': 'Search icons…', 'engine.form.chooseIcon': 'Choose an icon', // objectstack#35985: the object colour palette in the icon picker. diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index e675999afee..b759c452128 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -1608,6 +1608,13 @@ const STUDIO_ZH: Record = { 'engine.form.invalid': '(无效)', 'engine.form.notPublished': '(未发布)', 'engine.form.flaggedValue': '{value}{flag}', + 'engine.form.retrievalMode.vector': '仅向量(按意思)', + 'engine.form.retrievalMode.keyword': '仅关键词(按字词)', + 'engine.form.retrievalMode.hybrid': '混合(两者都用)', + 'engine.form.retrievalMode.default': '存储默认', + 'engine.form.retrievalMode.defaultIs': '存储默认({mode})', + 'engine.form.retrievalMode.notRun': '(此存储不支持)', + 'engine.form.retrievalMode.undeclared': '驱动未声明检索方式({store}),此项请留空。', 'engine.form.searchIcons': '搜索图标…', 'engine.form.chooseIcon': '选择图标', // objectstack#35985: the object colour palette in the icon picker. diff --git a/ui/packages/plugin-detail/README.md b/ui/packages/plugin-detail/README.md index 282fb8d978c..58d25f6f501 100644 --- a/ui/packages/plugin-detail/README.md +++ b/ui/packages/plugin-detail/README.md @@ -926,6 +926,18 @@ drawer, a pane and a phone draw the same either way (the host does not pass the key on a phone). `recordPagePinsDetails` takes the same value as its optional fourth argument. +An object's `fieldTabs` (`ObjectSchema.fieldTabs`) draws named field groups as +tabs of their own: `buildDefaultPageSchema` takes their sections out of the +overview and places one `fields:` tab per entry right after it, before +every related and built-in tab (`fieldTabPlacement`), and +`buildDefaultPageColumns` hands them to `RecordPageColumns` as +`columns.fieldTabs`. The laid-out page draws a tab whose groups are drawn on +this record (a group's `visibleWhen` is judged where the tab row is built), +gives each tab its own empty-field row, draws a one-group tab without its +group's heading, and offers no move or hide on it. They count as other tabs +for the pin. `fieldTabIdOfField` names the tab a field sits in, which the host +opens for a cited `?section=`. + On a pinned page the left column narrows on its own to leave the tabs 400 px, never below 320 px; under that the page is no longer pinned and the details become its first tab again. The divider between the column and the tabs is a diff --git a/ui/packages/plugin-detail/src/RecordPageColumns.tsx b/ui/packages/plugin-detail/src/RecordPageColumns.tsx index ac5eb7ac617..89386edae43 100644 --- a/ui/packages/plugin-detail/src/RecordPageColumns.tsx +++ b/ui/packages/plugin-detail/src/RecordPageColumns.tsx @@ -9,7 +9,9 @@ import * as React from 'react'; import { cn } from '@object-ui/components'; import type { FieldContainerLike } from '@object-ui/core'; -import { SchemaRenderer, toRenderableSchema, useRecordContext, useRecordPagePreferences } from '@object-ui/react'; +import { SchemaRenderer, toRenderableSchema, usePredicateScope, useRecordContext, useRecordPagePreferences, useSafeFieldLabel } from '@object-ui/react'; +import { pickLocalized, useObjectTranslation } from '@object-ui/i18n'; +import type { FieldRulePredicate } from '@object-ui/core'; import { RECORD_PAGE_DETAILS_MIN_WIDTH, RECORD_PAGE_DETAILS_WIDTH, @@ -20,11 +22,14 @@ import { recordPagePinsDetails, relatedListIdsIn, type DefaultPageColumns, + type RecordPageFieldTab, type RecordPageTier, } from './synth/recordPageColumns'; +import { deriveFieldGroupDetailEntries } from './synth/buildDefaultPageSchema'; +import { fieldGroupPredicateVisible, lazyPredicateRecord } from './fieldPredicateVisibility'; import { useDetailTranslation } from './useDetailTranslation'; import { RecordBodyTablesContext, RelatedEnlargeContext, RelatedListEnlargedContext } from './relatedListCompact'; -import { ApprovalBandOnceScope, DefaultRecordPageContext, DetailsColumnCapContext } from './defaultRecordPage'; +import { ApprovalBandOnceScope, DefaultRecordPageContext, DetailsColumnCapContext, FieldTabTitledGroupContext } from './defaultRecordPage'; import { RECORD_TAB_OVERVIEW, RecordTabRow, type RecordTab, type RecordTabArrangeEdit } from './RecordTabRow'; import { RECORD_TAB_APPROVALS, @@ -275,6 +280,68 @@ function drawDetailsNodes(nodes: any[]): React.ReactNode { return {drawNodes(nodes)}; } +/** + * The field groups of the object's field tabs (objectstack#37802) the record + * page draws: a tab is drawn when at least one of its groups is — declared on + * the object the page reads, holding a field (the shared derivation drops an + * empty group) and admitted by its `visibleWhen` on this record, judged by the + * call `record:details` makes for the same group (fail-closed). The verdict is + * lifted here, where the tab row is built, so a tab whose groups are all + * hidden or missing (a `.custom` package's `fieldGroups` replaced them) draws + * no tab at all. Without an object definition on the record context (nothing + * to judge against) every tab is kept, as its body is. + */ +function useDrawnFieldTabs(tabs: readonly RecordPageFieldTab[]): RecordPageFieldTab[] { + const ctx = useRecordContext(); + const scope = usePredicateScope(); + if (tabs.length === 0) return []; + const objSchema = (ctx as { objectSchema?: any } | null)?.objectSchema; + if (!objSchema) return [...tabs]; + const entries = new Map(); + for (const entry of deriveFieldGroupDetailEntries(objSchema) ?? []) { + if (typeof entry.key === 'string') entries.set(entry.key, entry); + } + const record = lazyPredicateRecord((ctx as { data?: Record } | null)?.data, objSchema?.fields); + const objectName = typeof ctx?.objectName === 'string' ? ctx.objectName : ''; + const drawn = (group: string): boolean => { + const entry = entries.get(group); + if (!entry) return false; + if (entry.visibleWhen == null) return true; + return fieldGroupPredicateVisible( + entry.visibleWhen as FieldRulePredicate, + record(), + scope, + `group '${group}' of the field tab on object '${objectName}'`, + ); + }; + return tabs.filter((tab) => tab.groups.some(drawn)); +} + +/** + * A field tab's body (objectstack#37802): its `record:details` nodes as a + * field list of their own — its empty fields counted by its own 「显示 N 个空字段」 + * row at its foot, shown or not by the reader's one per-object choice the + * overview's row reads too — and, for a tab of one group, that group drawn + * without the heading the tab's title already is. + */ +const FieldTabBody: React.FC<{ tab: RecordPageFieldTab; fieldList: Omit }> = ({ + tab, + fieldList, +}) => { + const [emptyFields] = React.useState(createEmptyFieldTally); + const list = React.useMemo(() => ({ ...fieldList, emptyFields }), [fieldList, emptyFields]); + return ( + + +
+ {drawDetailsNodes(tab.children)} + +
+
+
+ ); +}; + const LINE_BUTTON = 'rounded-sm font-medium text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'; @@ -604,7 +671,23 @@ export const RecordPageColumns: React.FC = ({ enlargedRelated && !panelNodes.has(enlargedRelated) ? columns.details.find((n) => relatedNodeId(n) === enlargedRelated) : undefined; - const otherTabs: RecordTab[] = resolved.order.map(arrangedTab); + // objectstack#37802 — the object's field tabs, right after the overview, in + // declared order, before every related and built-in tab. Fixed: the reader's + // arrangement neither moves nor hides them (they carry no `arrange`). + const fieldTabs = useDrawnFieldTabs(columns.fieldTabs ?? []); + const { sectionLabel } = useSafeFieldLabel(); + const { language } = useObjectTranslation(); + const fieldTabTitle = (tab: RecordPageFieldTab): string => { + const raw = tab.label != null ? pickLocalized(tab.label as any, language) : undefined; + const fallback = typeof raw === 'string' && raw ? raw : tab.groups[0] ?? tab.id; + return preferenceObject && tab.groups[0] ? sectionLabel(preferenceObject, tab.groups[0], fallback) : fallback; + }; + const otherTabs: RecordTab[] = fieldTabs.map((tab) => ({ + id: tab.id, + label: fieldTabTitle(tab), + ...(tab.icon ? { icon: tab.icon } : {}), + })); + otherTabs.push(...resolved.order.map(arrangedTab)); if (bodyTableNode) otherTabs.push({ id: enlargedRelated!, label: relatedNodeTitle(bodyTableNode) }); if (attachmentsNode) otherTabs.push({ id: RECORD_TAB_ATTACHMENTS, label: attachmentsTitle, count: attachmentCount }); if (approvalsNode) otherTabs.push({ id: RECORD_TAB_APPROVALS, label: approvalsTitle, dot: approvalPending }); @@ -660,6 +743,13 @@ export const RecordPageColumns: React.FC = ({ ); + } else if (openTab && fieldTabs.some((tab) => tab.id === openTab)) { + const tab = fieldTabs.find((t) => t.id === openTab)!; + face = ( + + + + ); } else if (openTab === RECORD_TAB_ATTACHMENTS && attachmentsNode) { face = blockFace(RECORD_TAB_ATTACHMENTS, attachmentsTitle, attachmentsNode); } else if (openTab === RECORD_TAB_APPROVALS && approvalsNode) { diff --git a/ui/packages/plugin-detail/src/RecordTabRow.tsx b/ui/packages/plugin-detail/src/RecordTabRow.tsx index fb8f2529c50..f91108e3434 100644 --- a/ui/packages/plugin-detail/src/RecordTabRow.tsx +++ b/ui/packages/plugin-detail/src/RecordTabRow.tsx @@ -14,6 +14,7 @@ import { DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, + LazyIcon, cn, } from '@object-ui/components'; import { ArrowLeft, ArrowRight, ChevronDown, EyeOff, RotateCcw } from 'lucide-react'; @@ -48,6 +49,11 @@ export interface RecordTab { * Absent: a fixed tab (概览, 附件, 审批, 动态, an open body table). */ arrange?: { before: boolean; after: boolean }; + /** + * A Lucide icon name drawn before the label — a field tab's, its first + * group's `icon` (objectstack#37802). Absent: no icon, as on every other tab. + */ + icon?: string; } /** What a related tab's menu asks of the reader's arrangement (objectstack#35783). */ @@ -99,12 +105,25 @@ const hasCount = (tab: RecordTab): tab is RecordTab & { count: number } => /** Whether a tab's list is known to be empty: a count of `0`. */ export const isEmptyRecordTab = (tab: RecordTab): boolean => tab.count === 0; +/** + * A tab's icon (objectstack#37802): a Lucide name draws the real icon, as a + * field group's section header does (`DetailSection`'s `SectionIcon`); any + * other text (an emoji from hand-authored metadata) is drawn as text. + */ +const TabIcon: React.FC<{ name: string }> = ({ name }) => ( + + {/^[a-z0-9][a-z0-9-]*$/i.test(name) ? : name} + +); + /** * A tab's face, shared by the row's button, the dropdown's items and the - * measuring copy: the label, then the count chip (above 0) or the dot. + * measuring copy: the icon (a field tab's), the label, then the count chip + * (above 0) or the dot. */ const TabFace: React.FC<{ tab: RecordTab; muted?: boolean; menu?: boolean }> = ({ tab, muted, menu }) => ( <> + {tab.icon && } {tab.label} @@ -159,7 +178,7 @@ export const RecordTabRow: React.FC = ({ // What the tabs draw, as a value: re-measure when a label or a count moves. const facesKey = JSON.stringify([ - tabs.map((tab) => [tab.id, tab.label, tab.count ?? null, tab.dot === true]), + tabs.map((tab) => [tab.id, tab.label, tab.count ?? null, tab.dot === true, tab.icon ?? null]), hiddenTabs.length, activeId, !!onArrange, diff --git a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.fieldTabs-37802.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.fieldTabs-37802.test.tsx new file mode 100644 index 00000000000..f53415ee226 --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.fieldTabs-37802.test.tsx @@ -0,0 +1,318 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#37802 — the object's `fieldTabs` (`ObjectSchema.fieldTabs`, + * ADR-0085's Note of 2026-11-27) on the laid-out record page. + * + * The page is the REAL synthesized one (`buildDefaultPageSchema` → + * `buildDefaultPageColumns`) drawn through the REAL registry, so each + * `record:details` node resolves its `{ group }` sections the way the running + * app does. What it pins, each beside its control (the same object without + * `fieldTabs`, or the same tab without the condition): + * + * - a two-group tab draws its groups in its order, and the overview no longer + * draws them; the related lists and attachments keep their tabs; + * - the tab row runs overview → field tabs → the rest, and the reader's + * arrangement offers no move or hide on a field tab; + * - a tab whose every group is hidden by `visibleWhen`, or missing from the + * object the page reads, draws no tab; + * - each field tab counts its own empty fields in its own row; + * - a one-group tab draws no second heading under its title; + * - a tab carries its first group's icon before its title (none without one); + * - inline edit is the page's one session: a draft made on a field tab's field + * survives switching to the overview and back, and is what Save writes; a + * server refusal naming a field in a tab not open is still listed by the + * save bar. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, cleanup, within, fireEvent, waitFor } from '@testing-library/react'; +import { InlineEditProvider, RecordContextProvider, useInlineEdit } from '@object-ui/react'; +// The registry must hold the record renderers and the field widgets before the +// first render (AGENTS.md 测试纪律). +import '@object-ui/components'; +import '@object-ui/fields'; +import '../index'; +import { RecordPageColumns } from '../RecordPageColumns'; +import { InlineEditSaveBar } from '../InlineEditSaveBar'; +import { buildDefaultPageSchema, type ObjectDefLike } from '../synth/buildDefaultPageSchema'; +import { buildDefaultPageColumns } from '../synth/recordPageColumns'; + +/** `useRecordEditable`'s explain probe, answered with its fail-open 501 (the binding suites do the same). */ +vi.stubGlobal('fetch', (async () => new Response(null, { status: 501 })) as unknown as typeof globalThis.fetch); + +let width = 0; +beforeEach(() => { + width = 0; + vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(() => width); +}); +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +const policy = { + name: 'policy', + label: 'Policy', + enable: { files: true }, + fieldGroups: [ + { key: 'basic', label: 'Basic' }, + { key: 'content', label: 'Content' }, + { key: 'import', label: 'Original' }, + { key: 'review', label: 'Review', visibleWhen: "record.status == 'in_review'" }, + ], + fields: { + name: { name: 'name', label: 'Name', type: 'text' }, + owner: { name: 'owner', label: 'Owner', type: 'text', group: 'basic' }, + body: { name: 'body', label: 'Body text', type: 'textarea', group: 'content' }, + summary: { name: 'summary', label: 'Summary', type: 'text', group: 'content' }, + source_file: { name: 'source_file', label: 'Source file', type: 'text', group: 'import' }, + checksum: { name: 'checksum', label: 'Checksum', type: 'text', group: 'import' }, + imported_by: { name: 'imported_by', label: 'Imported by', type: 'text', group: 'import' }, + reviewer: { name: 'reviewer', label: 'Reviewer', type: 'text', group: 'review' }, + status: { name: 'status', label: 'Status', type: 'text' }, + }, +}; + +/** A policy with its body and source written; `summary`, `checksum`, `imported_by` left empty. */ +const RECORD = { id: 'p1', name: 'Travel policy', owner: 'Ada', body: 'Long body text', source_file: 'travel.pdf', status: 'active', reviewer: 'Lin' }; + +const related = [{ objectName: 'task', relationshipField: 'policy_id', title: 'Tasks' }]; + +function draw( + def: Record, + { + open, + schema = def, + data = RECORD, + }: { open?: string; schema?: Record; data?: Record } = {}, +) { + const page = buildDefaultPageSchema(def as ObjectDefLike, { related, hideDiscussion: true }); + const columns = buildDefaultPageColumns(page)!; + expect(columns, 'the synthesized page lays out').not.toBeNull(); + const onEnlargeRelated = vi.fn(); + const utils = render( + + + , + ); + return { ...utils, onEnlargeRelated }; +} + +const tabIds = () => screen.queryAllByRole('tab').map((tab) => tab.getAttribute('data-record-tab')); +const detailsColumn = (container: HTMLElement) => + container.querySelector('[data-record-column="details"]') as HTMLElement | null; +const fieldTab = (container: HTMLElement, id: string) => + container.querySelector(`[data-record-field-tab="${id}"]`) as HTMLElement | null; +const labelsIn = (el: HTMLElement | null) => (el?.textContent ?? ''); +const order = (text: string, ...words: string[]) => words.map((w) => text.indexOf(w)); + +const withTabs = (fieldTabs: unknown) => ({ ...policy, fieldTabs }); + +describe('RecordPageColumns — the object\'s field tabs (objectstack#37802)', () => { + it('CONTROL: without fieldTabs the overview draws every group; the tabs are the related ones', () => { + const { container } = draw(policy); + expect(tabIds()).toEqual(['overview', 'task.policy_id', 'attachments']); + const overview = labelsIn(detailsColumn(container)); + expect(overview).toContain('Body text'); + expect(overview).toContain('Source file'); + }); + + it('a two-group tab draws its groups in its order; the overview no longer draws them; related and attachments keep their tabs', () => { + const def = withTabs([{ key: 'content', groups: ['import', 'content'] }]); + const first = draw(def); + expect(tabIds()).toEqual(['overview', 'fields:content', 'task.policy_id', 'attachments']); + const overview = labelsIn(detailsColumn(first.container)); + expect(overview).toContain('Owner'); + expect(overview).not.toContain('Body text'); + expect(overview).not.toContain('Source file'); + first.unmount(); + + const { container } = draw(def, { open: 'fields:content' }); + const body = fieldTab(container, 'fields:content'); + expect(body).not.toBeNull(); + const text = labelsIn(body); + const [original, content, source, bodyText] = order(text, 'Original', 'Content', 'Source file', 'Body text'); + expect(original).toBeGreaterThanOrEqual(0); + expect(content).toBeGreaterThan(original); + expect(source).toBeGreaterThan(original); + expect(bodyText).toBeGreaterThan(content); + expect(text).not.toContain('Owner'); + // The tab's title is its first group's label. + expect(screen.getByRole('tab', { name: /Original/ }).getAttribute('data-record-tab')).toBe('fields:content'); + }); + + it("the tab draws its first group's icon before its title; a group with no icon draws none", () => { + const iconed = { ...policy, fieldGroups: policy.fieldGroups.map((g) => (g.key === 'content' ? { ...g, icon: 'file-text' } : g)) }; + const { container } = draw({ ...iconed, fieldTabs: [{ key: 'content', groups: ['content'] }, { key: 'original', groups: ['import'] }] }); + const contentTab = container.querySelector('[data-record-tab="fields:content"]')!; + const icon = contentTab.querySelector('[data-record-tab-icon]'); + expect(icon?.getAttribute('data-record-tab-icon')).toBe('file-text'); + // The icon comes before the title on the tab's face. + expect(icon!.compareDocumentPosition(contentTab.querySelector('[data-record-tab-label]')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + // CONTROL: `import` declares no icon, and no other tab draws one. + expect(container.querySelector('[data-record-tab="fields:original"] [data-record-tab-icon]')).toBeNull(); + expect(screen.getAllByRole('tab').filter((tab) => tab.querySelector('[data-record-tab-icon]'))).toHaveLength(1); + }); + + it("the reader's arrangement offers no move or hide on a field tab; a related tab carries it", () => { + const { container } = draw(withTabs([{ key: 'content', groups: ['content'] }]), { open: 'fields:content' }); + // The open field tab is no menu trigger (no chevron); the related tab, opened, is. + const fieldTabButton = container.querySelector('[data-record-tab="fields:content"]')!; + expect(fieldTabButton.getAttribute('aria-selected')).toBe('true'); + expect(fieldTabButton.querySelector('[data-record-tab-menu-chevron]')).toBeNull(); + cleanup(); + const control = draw(withTabs([{ key: 'content', groups: ['content'] }]), { open: 'task.policy_id' }); + const relatedButton = control.container.querySelector('[data-record-tab="task.policy_id"]')!; + expect(relatedButton.querySelector('[data-record-tab-menu-chevron]')).not.toBeNull(); + }); + + it('a tab whose every group visibleWhen hides draws no tab; shown, it does', () => { + const def = withTabs([{ key: 'review', groups: ['review'] }]); + draw(def); + expect(tabIds()).not.toContain('fields:review'); + cleanup(); + draw(def, { data: { ...RECORD, status: 'in_review' } }); + expect(tabIds()).toContain('fields:review'); + }); + + it('a group missing from the object the page reads is skipped; a tab left with none draws no tab', () => { + const def = withTabs([{ key: 'content', groups: ['content'] }, { key: 'original', groups: ['import'] }]); + // The served object lost `import` (a `.custom` package replaced `fieldGroups`). + const served = { ...policy, fieldGroups: policy.fieldGroups.filter((g) => g.key !== 'import') }; + draw(def, { schema: served }); + expect(tabIds()).toEqual(['overview', 'fields:content', 'task.policy_id', 'attachments']); + cleanup(); + // CONTROL: the object as declared draws both. + draw(def); + expect(tabIds()).toEqual(['overview', 'fields:content', 'fields:original', 'task.policy_id', 'attachments']); + }); + + it('each field tab counts its own empty fields in its own row', () => { + const def = withTabs([{ key: 'content', groups: ['content'] }, { key: 'original', groups: ['import'] }]); + const content = draw(def, { open: 'fields:content' }); + const row = fieldTab(content.container, 'fields:content')!.querySelector('[data-empty-fields-row]'); + expect(row?.getAttribute('data-empty-fields-count')).toBe('1'); + content.unmount(); + const original = draw(def, { open: 'fields:original' }); + const row2 = fieldTab(original.container, 'fields:original')!.querySelector('[data-empty-fields-row]'); + expect(row2?.getAttribute('data-empty-fields-count')).toBe('2'); + }); + + it('pinned beside the overview, the tab and the overview each count only their own empty fields', () => { + width = 1600; + const def = { + ...withTabs([{ key: 'content', groups: ['content'] }]), + fields: { ...policy.fields, phone: { name: 'phone', label: 'Phone', type: 'text', group: 'basic' } }, + }; + const { container } = draw(def, { open: 'fields:content' }); + expect(container.querySelector('[data-record-page-pinned]')).not.toBeNull(); + const overviewRow = detailsColumn(container)!.querySelector('[data-empty-fields-row]'); + const tabRow = fieldTab(container, 'fields:content')!.querySelector('[data-empty-fields-row]'); + // The overview's empty fields are `phone`, `checksum` and `imported_by`; the tab's is `summary`. + expect(overviewRow?.getAttribute('data-empty-fields-count')).toBe('3'); + expect(tabRow?.getAttribute('data-empty-fields-count')).toBe('1'); + }); + + it('a one-group tab draws no second heading under its title; a two-group tab keeps both headings', () => { + const one = draw(withTabs([{ key: 'original', groups: ['import'] }]), { open: 'fields:original' }); + const body = fieldTab(one.container, 'fields:original')!; + expect(within(body).queryByText('Original')).toBeNull(); + expect(labelsIn(body)).toContain('Source file'); + one.unmount(); + const two = draw(withTabs([{ key: 'content', groups: ['import', 'content'] }]), { open: 'fields:content' }); + const both = fieldTab(two.container, 'fields:content')!; + expect(within(both).queryByText('Original')).not.toBeNull(); + expect(within(both).queryByText('Content')).not.toBeNull(); + }); +}); + +describe('RecordPageColumns — field tabs and the page\'s one inline-edit session (objectstack#37802)', () => { + const def = withTabs([{ key: 'content', groups: ['content'] }]); + const LABELS: Record = { body: 'Body text', owner: 'Owner' }; + + function Edits() { + const inline = useInlineEdit()!; + return ( + <> + + + + ); + } + + function page(open: string | undefined, update: ReturnType) { + const columns = buildDefaultPageColumns(buildDefaultPageSchema(def as ObjectDefLike, { related, hideDiscussion: true }))!; + return ( + + + + + LABELS[n]} + /> + + + ); + } + + it('a draft on a field tab survives switching to the overview and back, and Save writes it', async () => { + const update = vi.fn(async (_o: string, _id: string, patch: Record) => ({ ...RECORD, ...patch })); + const { rerender } = render(page('fields:content', update)); + fireEvent.click(screen.getByText('edit-enter')); + fireEvent.click(screen.getByText('edit-body')); + // To the overview: the tab's body is gone from the page, the session is not. + rerender(page(undefined, update)); + expect(document.querySelector('[data-record-field-tab="fields:content"]')).toBeNull(); + expect(screen.getByRole('button', { name: 'Save' })).toBeTruthy(); + // Back on the tab: the field draws the draft. + rerender(page('fields:content', update)); + const tabBody = document.querySelector('[data-record-field-tab="fields:content"]') as HTMLElement; + expect((within(tabBody).getByDisplayValue('Rewritten body') as HTMLTextAreaElement).value).toBe('Rewritten body'); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(update).toHaveBeenCalledTimes(1)); + expect(update.mock.calls[0][2]).toMatchObject({ body: 'Rewritten body' }); + }); + + it('a server refusal naming a field in a tab not open is still listed by the save bar', async () => { + const update = vi.fn().mockRejectedValue({ + code: 'VALIDATION_FAILED', + message: 'VALIDATION_FAILED: Validation failed for policy', + details: { error: 'Validation failed', code: 'VALIDATION_FAILED', fields: [{ field: 'body', code: 'max', message: 'Body is too long' }] }, + }); + const { rerender } = render(page('fields:content', update)); + fireEvent.click(screen.getByText('edit-enter')); + fireEvent.click(screen.getByText('edit-body')); + // The reader went back to the overview before saving: the field's tab is not open. + rerender(page(undefined, update)); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(update).toHaveBeenCalledTimes(1)); + await waitFor(() => + expect( + Array.from(document.querySelectorAll('[data-inline-field-error]')).map((li) => [ + li.getAttribute('data-inline-field-error'), + li.textContent, + ]), + ).toEqual([['body', 'Body text: Body is too long']]), + ); + expect(document.querySelector('[data-record-field-tab="fields:content"]')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-detail/src/defaultRecordPage.ts b/ui/packages/plugin-detail/src/defaultRecordPage.ts index c930b89e62d..268c5d010fd 100644 --- a/ui/packages/plugin-detail/src/defaultRecordPage.ts +++ b/ui/packages/plugin-detail/src/defaultRecordPage.ts @@ -147,3 +147,15 @@ export function framelessSectionColumns(visibleFieldCount: number, cap: 1 | 2 | if (visibleFieldCount <= 5 || cap === 2) return 2; return 3; } + +/** + * objectstack#37802 — the field group whose heading a field tab already draws + * as its title: a tab of the object's `fieldTabs` that holds ONE group is + * titled by that group (`RecordPageColumns`), so `record:details` draws the + * group's fields under the tab without its heading, its card or its fold. + * `null` (the default) everywhere else: every group keeps its heading. + * + * Module-internal, like `DetailsColumnCapContext`: neither a prop nor a + * schema key. + */ +export const FieldTabTitledGroupContext = React.createContext(null); diff --git a/ui/packages/plugin-detail/src/fieldPredicateVisibility.ts b/ui/packages/plugin-detail/src/fieldPredicateVisibility.ts index 9e5f3813a9d..699cb83a3ab 100644 --- a/ui/packages/plugin-detail/src/fieldPredicateVisibility.ts +++ b/ui/packages/plugin-detail/src/fieldPredicateVisibility.ts @@ -16,6 +16,7 @@ import { columnIdentity, + evalFieldPredicate, resolveFieldRuleState, toPredicateRecord, type FieldRulePredicate, @@ -52,6 +53,24 @@ export function assemblePredicateRecord( return out; } +/** + * Does a field GROUP's `visibleWhen` admit the group on this record? The one + * call `record:details` makes for a `{ group }` section (its + * `sectionPredicateVisible` docblock says why: the form's engine, the form's + * three inputs, fail-CLOSED), and the one the laid-out record page makes for + * a field tab's groups before it draws the tab (objectstack#37802). + */ +export function fieldGroupPredicateVisible( + visibleWhen: FieldRulePredicate, + record: Record, + scope: Record, + where: string, +): boolean { + return evalFieldPredicate(visibleWhen, record, false, record, scope, { + context: `visibleWhen of ${where} — fail-closed, the group is hidden`, + }); +} + /** * {@link assemblePredicateRecord}, assembled on first use and then reused — so * a surface whose fields declare no predicate does no extra work. diff --git a/ui/packages/plugin-detail/src/index.tsx b/ui/packages/plugin-detail/src/index.tsx index 4d8bcdb9be4..4fdbd5a09f4 100644 --- a/ui/packages/plugin-detail/src/index.tsx +++ b/ui/packages/plugin-detail/src/index.tsx @@ -247,12 +247,15 @@ export { buildDefaultPageColumns, bodyTableIdsOf, RECORD_PAGE_TIMELINE_PANEL, + // objectstack#37802 — the field tab a cited field sits in. + fieldTabIdOfField, } from './synth/recordPageColumns'; // objectstack#27069 — the one reading of a related-list entry. export { relatedListEntryNames } from './synth/relatedListEntry'; export type { RecordPageTier, DefaultPageColumns, + RecordPageFieldTab, } from './synth/recordPageColumns'; export { useRecordPageTier } from './useRecordPageTier'; export type { UseRecordPageTierOptions } from './useRecordPageTier'; diff --git a/ui/packages/plugin-detail/src/renderers/record-details.tsx b/ui/packages/plugin-detail/src/renderers/record-details.tsx index ccf0aeffa65..614ba6b4c0e 100644 --- a/ui/packages/plugin-detail/src/renderers/record-details.tsx +++ b/ui/packages/plugin-detail/src/renderers/record-details.tsx @@ -27,19 +27,18 @@ import { resolveAffordance, type FieldRulePredicate, recordDisplayValueAt, - evalFieldPredicate, resolveNameField, withoutDeniedFields, } from '@object-ui/core'; import { DetailView } from '../DetailView'; import { hasCellValue } from '../emptiness'; -import { EmptySectionsLineContext } from '../defaultRecordPage'; +import { EmptySectionsLineContext, FieldTabTitledGroupContext } from '../defaultRecordPage'; import { RecordPageProvenanceContext } from '../recordPageProvenance'; import { RecordFieldAccessForRecord } from '../recordFieldAccess'; import { deriveFieldGroupDetailEntries, type FieldGroupDetailEntry } from '../synth/buildDefaultPageSchema'; import { useRecordAriaProps } from './recordComponentAria'; import { recordBindingBlock } from './recordBinding'; -import { dropFieldPredicateHidden, lazyPredicateRecord } from '../fieldPredicateVisibility'; +import { dropFieldPredicateHidden, fieldGroupPredicateVisible, lazyPredicateRecord } from '../fieldPredicateVisibility'; /** Normalize a field entry (string | {field} | {name}) to its machine name. */ const fieldName = (entry: any): string | null => columnIdentity(entry) ?? null; @@ -225,9 +224,7 @@ function sectionPredicateVisible( scope: Record, where: string, ): boolean { - return evalFieldPredicate(visibleWhen, record, false, record, scope, { - context: `visibleWhen of ${where} — fail-closed, the group is hidden`, - }); + return fieldGroupPredicateVisible(visibleWhen, record, scope, where); } /** @@ -365,6 +362,9 @@ const RecordDetailsBody: React.FC = ({ // same predicate (objectui#11630). Called here with the other hooks because // the returns below are conditional. const predicateScope = usePredicateScope(); + // objectstack#37802 — the group a one-group field tab is titled by: drawn + // without its own heading (`FieldTabTitledGroupContext`). + const tabTitledGroup = React.useContext(FieldTabTitledGroupContext); // Phase N.4b: field names registered live by a mounted `record:highlights` // instance via HighlightFieldsContext (used to dedupe them out of the grid). @@ -1090,7 +1090,12 @@ const RecordDetailsBody: React.FC = ({ hideEmpty: s.hideEmpty ?? true, fields: dropPredicateHidden(dropHidden(normaliseList(filterList(s.fields)))), }); - }) + }).map((s) => + // objectstack#37802 — the tab's title is this group's heading already: + // no second heading, card or fold under it. + tabTitledGroup !== null && s.name === tabTitledGroup + ? { ...s, title: undefined, showBorder: false, collapsible: false, defaultCollapsed: false } + : s) : schema.sections; // A pointer pair's type half is drawn by its id half's card, not as a row diff --git a/ui/packages/plugin-detail/src/synth/__tests__/fieldTabs-37802.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/fieldTabs-37802.test.ts new file mode 100644 index 00000000000..bdb3d5b5d65 --- /dev/null +++ b/ui/packages/plugin-detail/src/synth/__tests__/fieldTabs-37802.test.ts @@ -0,0 +1,153 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#37802 — the object's `fieldTabs` (`ObjectSchema.fieldTabs`, + * ADR-0085's Note of 2026-11-27), as the synthesized record page places them. + * + * Pure and read off `buildDefaultPageSchema`'s real output: a field tab takes + * its groups' sections out of the overview and sits right after it, in + * declared order, before every related and built-in tab; its `fields:` + * id lays out as a column of its own; a group the object does not declare is + * skipped, and a tab left with none is not placed. Each fact sits beside its + * control: the same object without `fieldTabs`. + */ + +import { describe, it, expect } from 'vitest'; +import { buildDefaultPageSchema, fieldTabPlacement, type ObjectDefLike } from '../buildDefaultPageSchema'; +import { + buildDefaultPageColumns, + fieldTabIdOfField, + recordPageColumnOfTab, + recordPagePinsDetails, +} from '../recordPageColumns'; + +const policy: ObjectDefLike = { + name: 'policy', + label: 'Policy', + fieldGroups: [ + { key: 'basic', label: 'Basic' }, + { key: 'content', label: 'Content', icon: 'file-text' }, + { key: 'import', label: 'Original' }, + ], + fields: { + name: { name: 'name', label: 'Name', type: 'text' }, + owner: { name: 'owner', label: 'Owner', type: 'text', group: 'basic' }, + body: { name: 'body', label: 'Body', type: 'textarea', group: 'content' }, + source_file: { name: 'source_file', label: 'Source file', type: 'text', group: 'import' }, + }, +} as ObjectDefLike; + +const related = [{ objectName: 'task', relationshipField: 'policy_id', title: 'Tasks' }]; + +const itemsOf = (page: any): any[] => page.regions[0].components.find((n: any) => n.type === 'page:tabs').properties.items; +const values = (page: any): string[] => itemsOf(page).map((item: any) => item.value); +const groupsOf = (node: any): string[] => + (node?.properties?.sections ?? []).map((s: any) => s.group ?? (s.fields ? `[${s.fields.join(',')}]` : s.name)); +const overviewGroups = (page: any): string[] => + itemsOf(page)[0].children.filter((n: any) => n.type === 'record:details').flatMap(groupsOf); + +describe('fieldTabs — the synthesized page places the field tabs (objectstack#37802)', () => { + it('CONTROL: without fieldTabs the overview holds every group and the tabs are the related ones', () => { + const page = buildDefaultPageSchema(policy, { related, hideDiscussion: true }); + expect(values(page)).toEqual(['details', 'related:task.policy_id']); + expect(overviewGroups(page)).toEqual(['basic', 'content', 'import', '[name]']); + }); + + it('a two-group tab takes both groups, in its order, out of the overview, right after it', () => { + const def = { ...policy, fieldTabs: [{ key: 'content', groups: ['import', 'content'] }] }; + const page = buildDefaultPageSchema(def, { related, hideDiscussion: true }); + expect(values(page)).toEqual(['details', 'fields:content', 'related:task.policy_id']); + // The overview keeps the groups no tab names and the ungrouped fields. + expect(overviewGroups(page)).toEqual(['basic', '[name]']); + const tab = itemsOf(page)[1]; + expect(tab.children.map((n: any) => n.type)).toEqual(['record:details']); + expect(groupsOf(tab.children[0])).toEqual(['import', 'content']); + // Its title and icon are its first group's (no label/icon of its own in v1). + expect(tab.label).toBe('Original'); + expect(tab.icon).toBeUndefined(); + }); + + it('two tabs keep their declared order, before the related lists, attachments and the stream', () => { + const def = { + ...policy, + enable: { files: true }, + fieldTabs: [ + { key: 'original', groups: ['import'] }, + { key: 'content', groups: ['content'] }, + ], + }; + const page = buildDefaultPageSchema(def, { related }); + expect(values(page)).toEqual(['details', 'fields:original', 'fields:content', 'related:task.policy_id', 'attachments', 'timeline']); + expect(itemsOf(page)[2].icon).toBe('file-text'); + // A declared `relatedLists` places the related tabs only: no entry moves a field tab. + const declared = buildDefaultPageSchema({ ...def, relatedLists: [{ list: 'task' }] } as ObjectDefLike, { related }); + expect(values(declared).slice(0, 4)).toEqual(['details', 'fields:original', 'fields:content', 'related:task.policy_id']); + }); + + it('a group the object does not declare is skipped; a tab left with none is not placed', () => { + const def = { + ...policy, + fieldTabs: [ + { key: 'gone', groups: ['no_such_group'] }, + { key: 'content', groups: ['no_such_group', 'content'] }, + ], + }; + const page = buildDefaultPageSchema(def, { related, hideDiscussion: true }); + expect(values(page)).toEqual(['details', 'fields:content', 'related:task.policy_id']); + expect(groupsOf(itemsOf(page)[1].children[0])).toEqual(['content']); + expect(overviewGroups(page)).toEqual(['basic', 'import', '[name]']); + }); + + it('a group named by two tabs is drawn once, in the first', () => { + const placed = fieldTabPlacement( + { ...policy, fieldTabs: [{ key: 'a', groups: ['content'] }, { key: 'b', groups: ['content', 'import'] }] }, + // The `{ group }` reference form `resolveDetailSections` hands it. + [{ group: 'basic' }, { group: 'content' }, { group: 'import' }], + )!; + expect(placed.tabs.map((t) => [t.key, t.sections.map((s) => s.group)])).toEqual([ + ['a', ['content']], + ['b', ['import']], + ]); + expect(placed.overview).toEqual([{ group: 'basic' }]); + }); + + it('every group moved out leaves the overview an empty field body, still the first tab', () => { + const def = { ...policy, fields: { ...policy.fields, name: { ...policy.fields!.name, group: 'basic' } }, fieldTabs: [{ key: 'all', groups: ['basic', 'content', 'import'] }] }; + const page = buildDefaultPageSchema(def as ObjectDefLike, { related, hideDiscussion: true }); + expect(values(page)).toEqual(['details', 'fields:all', 'related:task.policy_id']); + const overview = itemsOf(page)[0].children; + expect(overview.map((n: any) => n.type)).toEqual(['record:details']); + expect(overview[0].properties.sections).toEqual([]); + }); + + it('the layout reads the field tabs as their own column; they count as other tabs for the pin', () => { + expect(recordPageColumnOfTab('fields:content')).toBe('fields'); + expect(recordPageColumnOfTab('fields:')).toBeNull(); + const def = { ...policy, fieldTabs: [{ key: 'content', groups: ['content', 'import'] }] }; + const columns = buildDefaultPageColumns(buildDefaultPageSchema(def, { hideDiscussion: true }))!; + expect(columns).not.toBeNull(); + expect(columns.related).toEqual([]); + expect(columns.fieldTabs!.map((t) => [t.id, t.groups])).toEqual([['fields:content', ['content', 'import']]]); + // A field tab alone is an "other tab": the wide full page pins… + expect(recordPagePinsDetails(1600, columns, true)).toBe(true); + // …CONTROL: the same page without the tab has nothing to pin beside. + const bare = buildDefaultPageColumns(buildDefaultPageSchema(policy, { hideDiscussion: true }))!; + expect(recordPagePinsDetails(1600, bare, true)).toBe(false); + }); + + it('a cited field opens the field tab that holds its group; an overview field opens none', () => { + const def = { ...policy, fieldTabs: [{ key: 'content', groups: ['content', 'import'] }] }; + const columns = buildDefaultPageColumns(buildDefaultPageSchema(def, { hideDiscussion: true }))!; + expect(fieldTabIdOfField(columns, def, 'source_file')).toBe('fields:content'); + expect(fieldTabIdOfField(columns, def, 'body')).toBe('fields:content'); + expect(fieldTabIdOfField(columns, def, 'owner')).toBeNull(); + expect(fieldTabIdOfField(columns, def, 'name')).toBeNull(); + expect(fieldTabIdOfField(columns, def, 'no_such_field')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts index 891afc4b11f..443045840ba 100644 --- a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts +++ b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts @@ -123,6 +123,13 @@ export interface ObjectDefLike { * whether an empty `relatedLists` is a declared list with every tab hidden). */ _relatedListsArrangement?: unknown; + /** + * The spec's `fieldTabs` (`ObjectSchema.fieldTabs`, ADR-0085's Note of + * 2026-11-27): field groups the record page draws as tabs of their own, + * right after the overview. Each entry names its tab's `key` and its + * `groups` (keys of `fieldGroups`). See {@link fieldTabPlacement}. + */ + fieldTabs?: ReadonlyArray<{ key?: unknown; groups?: unknown }>; // NOTE: the per-surface `detail` hints block was REMOVED from the spec by // ADR-0085 — presentation intent is declared via the top-level semantic // roles above (stageField / highlightFields / fieldGroups). Per-page @@ -842,6 +849,89 @@ function sectionDrawnClosed(def: ObjectDefLike | undefined): (section: Record`. */ +export const RECORD_PAGE_FIELD_TAB_PREFIX = 'fields:'; + +/** One field tab the synthesized page draws (see {@link fieldTabPlacement}). */ +export interface FieldTabPlacement { + /** The entry's `key`; the tab's value is `fields:`. */ + key: string; + /** The first drawn group's label, as the object declares it (translated where drawn). */ + label: unknown; + /** The first drawn group's icon, when it declares one. */ + icon?: string; + /** The sections the tab draws, in the entry's `groups` order. */ + sections: Array>; +} + +/** + * The object's `fieldTabs` (`ObjectSchema.fieldTabs`, ADR-0085's Note of + * 2026-11-27, objectstack#37802) laid over the Details sections the page + * draws: each tab takes the sections of the groups it names, in its `groups` + * order, out of the overview. `null` when the object declares no field tab + * that draws anything, so the page is exactly what it was without the key. + * + * A section belongs to a group by `group` (the spec's reference form, which the + * host and the synthesizer write) or by `name` (a resolved section a caller + * passes). Read at runtime, not judged (the object's parse refuses an + * unknown group, a group two tabs name and a body-table group): a group no + * section draws — undeclared, empty, or replaced by a `.custom` package's + * `fieldGroups` — is skipped, a group an earlier tab took is not drawn twice, + * and a tab left with no section is not drawn. A body-table group is never a + * section, so it stays where `bodyTablePlacement` puts it, in the overview. + */ +export function fieldTabPlacement( + def: ObjectDefLike | undefined, + // The Details body's sections: `{ group }` references, enumerated ones, or both. + sections: ReadonlyArray> | undefined, +): { overview: Array>; tabs: FieldTabPlacement[] } | null { + const declared = Array.isArray(def?.fieldTabs) ? def!.fieldTabs : []; + if (declared.length === 0 || !Array.isArray(sections) || sections.length === 0) return null; + const groups = new Map>(); + for (const group of Array.isArray(def?.fieldGroups) ? def!.fieldGroups : []) { + if (group && typeof group.key === 'string' && !groups.has(group.key)) groups.set(group.key, group as Record); + } + const groupOf = (section: Record): string | undefined => { + const key = typeof section?.group === 'string' ? section.group : typeof section?.name === 'string' ? section.name : undefined; + return key !== undefined && groups.has(key) ? key : undefined; + }; + const sectionOfGroup = new Map>(); + for (const section of sections as Array>) { + const key = groupOf(section); + if (key !== undefined && !sectionOfGroup.has(key)) sectionOfGroup.set(key, section); + } + const taken = new Set(); + const tabKeys = new Set(); + const tabs: FieldTabPlacement[] = []; + for (const entry of declared) { + const key = entry?.key; + if (typeof key !== 'string' || key.length === 0 || tabKeys.has(key) || !Array.isArray(entry?.groups)) continue; + const drawn: string[] = []; + for (const group of entry.groups as unknown[]) { + if (typeof group !== 'string' || taken.has(group) || !sectionOfGroup.has(group)) continue; + taken.add(group); + drawn.push(group); + } + if (drawn.length === 0) continue; + tabKeys.add(key); + const first = groups.get(drawn[0])!; + tabs.push({ + key, + label: first.label ?? drawn[0], + ...(typeof first.icon === 'string' && first.icon ? { icon: first.icon } : {}), + sections: drawn.map((group) => sectionOfGroup.get(group)!), + }); + } + if (tabs.length === 0) return null; + return { + overview: (sections as Array>).filter((section) => { + const key = groupOf(section); + return key === undefined || !taken.has(key); + }), + tabs, + }; +} + /** Rows on the first page of a body table (objectstack#27055, Target 8). */ export const BODY_TABLE_PAGE_SIZE = 10; @@ -1059,13 +1149,34 @@ function synthTabs( // objectstack#35595 — the first tab is 「概览」 (the token the tab strip // localizes as `detail.recordTabOverview`); its value stays `details`, the // URL token a `?tab=` link already names. + // objectstack#37802 — the object's field tabs (`fieldTabs`, ADR-0085's Note + // of 2026-11-27) take their groups' sections out of the overview, and sit + // right after it, in declared order, before every related and built-in tab. + // The overview keeps the rest: the groups no tab names, the ungrouped + // fields, the body tables (the host draws the approval band and the meta + // line there). Every group moved out leaves an overview of its tables and + // an empty field body (`@objectstack/lint` warns of that declaration). + const fieldTabs = fieldTabPlacement(def, resolveDetailSections(def, options.sections)); + const overviewChildren = !fieldTabs + ? bodyTablePlacement(def, options.sections, undefined, bodies) + : fieldTabs.overview.length > 0 + ? bodyTablePlacement(def, fieldTabs.overview, undefined, bodies) + : [componentNode('record:details', { sections: [] }), ...bodies]; const items: any[] = [ { label: 'Overview', value: 'details', - children: bodyTablePlacement(def, options.sections, undefined, bodies), + children: overviewChildren, }, ]; + for (const tab of fieldTabs?.tabs ?? []) { + items.push({ + label: tab.label, + value: `${RECORD_PAGE_FIELD_TAB_PREFIX}${tab.key}`, + ...(tab.icon ? { icon: tab.icon } : {}), + children: [componentNode('record:details', { sections: tab.sections })], + }); + } // objectstack#35595 — EVERY ordinary related list is a tab of its own, in // the order the host passed (the object's `relatedLists`, then the derived // order), whether or not it has records: one table, one tab, one count. The @@ -1163,6 +1274,9 @@ function arrangeDeclaredTabs(declared: readonly unknown[] | undefined, items: an const unlistedRelated = tail < names.length ? tail - 0.5 : unlisted; const rank = (tab: any): number | null => { const value = typeof tab?.value === 'string' ? tab.value : ''; + // objectstack#37802 — a field tab is not a related list: no entry places + // it, and it stays right after the overview, in declared order. + if (value.startsWith(RECORD_PAGE_FIELD_TAB_PREFIX)) return -1; const builtin = (Object.keys(BUILTIN_TAB_VALUES) as RecordPageBuiltinTab[]) .find((name) => BUILTIN_TAB_VALUES[name] === value); if (builtin) { diff --git a/ui/packages/plugin-detail/src/synth/recordPageColumns.ts b/ui/packages/plugin-detail/src/synth/recordPageColumns.ts index ad09e5f0870..716ffca3125 100644 --- a/ui/packages/plugin-detail/src/synth/recordPageColumns.ts +++ b/ui/packages/plugin-detail/src/synth/recordPageColumns.ts @@ -37,18 +37,21 @@ * ## Why the layout is derived, with one declared exception * * The tiers are the renderer's. No page template and no node type says - * "columns", and one object key alone steers the layout: `pinOverview` - * (`ObjectSchema.pinOverview`, a ruled exception recorded by ADR-0085's Note - * of 2026-11-27), which keeps the wide full page from pinning the details - * when it is `false` ({@link recordPagePinsDetails}). Everything else is - * derived. The spec's page vocabulary is closed inside its own + * "columns", and two object keys alone steer the layout, both ruled + * exceptions recorded by ADR-0085's Note of 2026-11-27: `pinOverview` + * (`ObjectSchema.pinOverview`), which keeps the wide full page from pinning + * the details when it is `false` ({@link recordPagePinsDetails}), and + * `fieldTabs` (`ObjectSchema.fieldTabs`, objectstack#37802), which draws + * named field groups as tabs of their own right after the overview (their + * `fields:` items). Everything else is derived. The spec's page vocabulary is closed inside its own * namespaces (`record:*`, `page:*`), so a columns node would be a type an * author — or an AI — could write and the spec could not judge, and a Studio * seed carrying it would be refused at save. The layout is therefore read off * the synthesized page itself, by the stable semantic `value` every tab item * carries (`buildDefaultTabs`, objectui#2257): `details` is the 概览 tab * (its path and highlights are the strip, the rest the details column), - * `timeline` (the one stream, objectstack#27055) is the 动态 tab, and each + * `timeline` (the one stream, objectstack#27055) is the 动态 tab, each + * `fields:` is a field tab (objectstack#37802), and each * `related:object.field`, `approvals` and `attachments` is a tab of its own * (objectstack#35595; 动态 last, objectstack#34590). The synthesized page has one region (`main`); a page with * any other region is not the synthesized page (objectstack#27055 removed the @@ -59,6 +62,12 @@ * and the host draws the page as written, tabs and all. */ +import { + RECORD_PAGE_FIELD_TAB_PREFIX, + deriveFieldGroupDetailEntries, + type ObjectDefLike, +} from './buildDefaultPageSchema'; + /** * The console sidebar's width when it is expanded: `SIDEBAR_WIDTH` (16rem) of * the sidebar primitive in `@object-ui/components`. Measured on the console @@ -187,13 +196,14 @@ export const RECORD_PAGE_PIN_MIN_WIDTH = */ export function recordPagePinsDetails( contentWidth: number, - columns: Pick | null | undefined, + columns: (Pick & Pick, 'fieldTabs'>) | null | undefined, fullPage: boolean, pinOverview?: boolean, ): boolean { if (pinOverview === false) return false; if (!fullPage || !columns || !(contentWidth >= RECORD_PAGE_PIN_MIN_WIDTH)) return false; - if (columns.timeline.length === 0 && columns.related.length === 0) return false; + // A field tab (objectstack#37802) is another tab to put beside the details. + if (columns.timeline.length === 0 && columns.related.length === 0 && !(columns.fieldTabs?.length)) return false; return relatedListIdsIn(columns.details).length === 0; } @@ -224,10 +234,11 @@ export const RECORD_PAGE_TIMELINE_PANEL = 'timeline'; /** * Where a synthesized tab's blocks land: the details column, the 动态 panel - * (`timeline`, the last panel of the right column, objectstack#34590) or the - * related panels before it. + * (`timeline`, the last panel of the right column, objectstack#34590), the + * related panels before it, or a field tab of its own (`fields`, + * objectstack#37802). */ -export type RecordPageColumn = 'details' | 'timeline' | 'related'; +export type RecordPageColumn = 'details' | 'timeline' | 'related' | 'fields'; /** * The column a synthesized tab lands in, by the tab's stable `value`; `null` @@ -246,9 +257,25 @@ export function recordPageColumnOfTab(value: unknown): RecordPageColumn | null { if (value === 'timeline' || value === 'activity' || value === 'history') return 'timeline'; if (value === 'related' || value.startsWith('related:')) return 'related'; if (value === 'approvals' || value === 'attachments') return 'related'; + // objectstack#37802 — `fields:`, a tab of the object's `fieldTabs`. + if (value.startsWith(RECORD_PAGE_FIELD_TAB_PREFIX) && value.length > RECORD_PAGE_FIELD_TAB_PREFIX.length) return 'fields'; return null; } +/** + * One field tab of the synthesized page (objectstack#37802, the object's + * `fieldTabs`): its `fields:` id, its title and icon (its first group's, + * as the page item carries them, untranslated), the field groups its sections + * name in order, and its body (`record:details` nodes). + */ +export interface RecordPageFieldTab { + id: string; + label: unknown; + icon?: string; + groups: string[]; + children: any[]; +} + /** The synthesized record page, partitioned for its layout. */ export interface DefaultPageColumns { /** @@ -273,6 +300,12 @@ export interface DefaultPageColumns { timeline: any[]; /** Related lists in the strip's order, then Approvals and Attachments. */ related: any[]; + /** + * The field tabs (objectstack#37802), in the strip's order: right after the + * overview, before the related tabs. Absent on a hand-built partition, read + * as none. + */ + fieldTabs?: RecordPageFieldTab[]; } type PageNode = Record; @@ -320,6 +353,7 @@ export function buildDefaultPageColumns(page: unknown): DefaultPageColumns | nul // declared `relatedLists` may place attachments or approvals among its lists; // undeclared, the tabs already run lists, then attachments, then approvals). const related: any[] = []; + const fieldTabs: RecordPageFieldTab[] = []; for (const rawItem of items) { const item = asNode(rawItem); if (!item) return null; @@ -329,7 +363,15 @@ export function buildDefaultPageColumns(page: unknown): DefaultPageColumns | nul const children = nodeList(item.children); if (column === 'details') details.push(...children); else if (column === 'timeline') timelineTabs.push(...children); - else related.push(...children); + else if (column === 'fields') { + fieldTabs.push({ + id: item.value, + label: item.label, + ...(typeof item.icon === 'string' && item.icon ? { icon: item.icon } : {}), + groups: fieldGroupsIn(children), + children, + }); + } else related.push(...children); } const before = components.slice(0, tabIndex); @@ -339,9 +381,53 @@ export function buildDefaultPageColumns(page: unknown): DefaultPageColumns | nul details, timeline: [...components.slice(tabIndex + 1), ...timelineTabs], related, + fieldTabs, }; } +/** + * The field groups the `record:details` nodes among `nodes` draw, in order: + * each section's `group` (the reference form) or `name` (a resolved section). + */ +export function fieldGroupsIn(nodes: any[]): string[] { + const out: string[] = []; + for (const raw of nodes) { + const node = asNode(raw); + if (node?.type !== 'record:details') continue; + const props = { ...node, ...(asNode(node.properties) ?? {}) }; + for (const section of nodeList(props.sections)) { + const s = asNode(section); + const key = typeof s?.group === 'string' ? s.group : typeof s?.name === 'string' ? s.name : undefined; + if (key !== undefined && !out.includes(key)) out.push(key); + } + } + return out; +} + +/** + * The field tab (`fields:`, objectstack#37802) whose groups hold the + * field `fieldName`, or `null` when the field is drawn in the overview or not + * at all. Read against the object's `fieldGroups` the way `record:details` + * resolves a group's members (`deriveFieldGroupDetailEntries`), so a cited + * section (`?section=`) inside a field tab opens that tab first. + */ +export function fieldTabIdOfField( + columns: Pick, 'fieldTabs'> | null | undefined, + def: ObjectDefLike | undefined, + fieldName: string, +): string | null { + const tabs = columns?.fieldTabs ?? []; + if (tabs.length === 0) return null; + const groupOfField = new Map(); + for (const entry of deriveFieldGroupDetailEntries(def) ?? []) { + if (typeof entry.key !== 'string') continue; + for (const field of entry.section.fields as Array<{ name: string }>) groupOfField.set(field.name, entry.key); + } + const group = groupOfField.get(fieldName); + if (group === undefined) return null; + return tabs.find((tab) => tab.groups.includes(group))?.id ?? null; +} + /** * The relationship ids (`object.field`) of the body tables a synthesized * record page draws (objectstack#27055, Target 8): every `record:related_list` diff --git a/ui/packages/plugin-form/src/fieldTabs.entryForm-37802.test.tsx b/ui/packages/plugin-form/src/fieldTabs.entryForm-37802.test.tsx new file mode 100644 index 00000000000..db851162801 --- /dev/null +++ b/ui/packages/plugin-form/src/fieldTabs.entryForm-37802.test.tsx @@ -0,0 +1,74 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#37802 — the object's `fieldTabs` (`ObjectSchema.fieldTabs`) + * places field groups as tabs of the standard record PAGE only: the entry + * form still draws every group, in one form, the tab's groups included. + * CONTROL: the same object without `fieldTabs` draws the same form. + */ + +import React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, waitFor, cleanup } from '@testing-library/react'; +import { registerAllFields } from '@object-ui/fields'; +import { ModalForm } from './ModalForm'; + +registerAllFields(); + +const SCHEMA = { + name: 'ticket', + fieldGroups: [ + { key: 'basic', label: 'Basic Info' }, + { key: 'tracking', label: 'Tracking Info' }, + ], + fields: { + title: { type: 'text', label: 'Title', group: 'basic' }, + assignee: { type: 'text', label: 'Assignee', group: 'basic' }, + status_note: { type: 'text', label: 'Status Note', group: 'tracking' }, + channel: { type: 'text', label: 'Channel', group: 'tracking' }, + }, +}; + +const makeDS = (objectSchema: any) => + ({ + getObjectSchema: vi.fn().mockResolvedValue(objectSchema), + create: vi.fn().mockResolvedValue({ id: 't1' }), + update: vi.fn().mockResolvedValue({ id: 't1' }), + findOne: vi.fn().mockResolvedValue({ id: 't1' }), + }) as any; + +afterEach(() => cleanup()); + +async function drawnForm(objectSchema: any) { + render( + , + ); + await waitFor(() => expect(document.body.textContent).toContain('Tracking Info')); + const forms = document.body.querySelectorAll('form'); + expect(forms.length).toBe(1); + return { + text: forms[0].textContent ?? '', + inputs: Array.from(forms[0].querySelectorAll('input')).map((i) => i.getAttribute('name')), + }; +} + +describe('fieldTabs leaves the entry form alone (objectstack#37802)', () => { + it("draws every group, the tab's group included, as the same object without fieldTabs does", async () => { + const control = await drawnForm(SCHEMA); + cleanup(); + const withTabs = await drawnForm({ ...SCHEMA, fieldTabs: [{ key: 'tracking', groups: ['tracking'] }] }); + expect(withTabs.text).toContain('Basic Info'); + expect(withTabs.text).toContain('Tracking Info'); + expect(withTabs.inputs).toEqual(['title', 'assignee', 'status_note', 'channel']); + expect(withTabs.inputs).toEqual(control.inputs); + }); +}); diff --git a/ui/packages/types/src/__tests__/form-field-tabs-object-shape.test.ts b/ui/packages/types/src/__tests__/form-field-tabs-object-shape.test.ts new file mode 100644 index 00000000000..059bacfa400 --- /dev/null +++ b/ui/packages/types/src/__tests__/form-field-tabs-object-shape.test.ts @@ -0,0 +1,42 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * objectstack#37802 — `FormSchema.fieldTabs` and the object-level + * `ObjectSchema.fieldTabs` (`@objectstack/spec`, ADR-0085's Note of + * 2026-11-27) share a key name and differ in shape: a form tab claims field + * names in `fields`, a record-page field tab names field groups in `groups`. + * An entry written in the other shape here is refused with a message that + * names the object-level key (the spec's refusal names this one). + */ + +import { describe, expect, it } from 'vitest'; +import { FormSchema } from '../zod/form.zod'; + +const form = (fieldTabs: unknown) => ({ + type: 'form', + fields: [{ name: 'body', label: 'Body', type: 'textarea' }], + fieldTabs, +}); + +describe('FormSchema.fieldTabs — the object-level shape is refused by name', () => { + it('still parses a form tab that lists fields', () => { + expect(FormSchema.safeParse(form([{ key: 'content', fields: ['body'] }])).success).toBe(true); + }); + + it('refuses an entry that names groups instead of fields, naming ObjectSchema.fieldTabs', () => { + const result = FormSchema.safeParse(form([{ key: 'content', groups: ['content'] }])); + expect(result.success).toBe(false); + if (!result.success) { + // The missing `fields` is the one issue, and it names the object-level + // key. (A `groups` list beside `fields` passes through the loose entry, + // as it did before: refusing it would narrow this published parse.) + expect(result.error.issues).toHaveLength(1); + expect(result.error.issues[0].path).toEqual(['fieldTabs', 0, 'fields']); + expect(result.error.issues[0].message).toContain('ObjectSchema.fieldTabs'); + } + }); +}); diff --git a/ui/packages/types/src/zod/form.zod.ts b/ui/packages/types/src/zod/form.zod.ts index 4a0c95eb5e8..131b7291d47 100644 --- a/ui/packages/types/src/zod/form.zod.ts +++ b/ui/packages/types/src/zod/form.zod.ts @@ -1287,7 +1287,16 @@ const FormFieldTabEntrySchema = z.looseObject({ key: z.string().describe('Stable tab key (the Radix Tabs value)'), label: z.string().optional().describe('Tab trigger text; falls back to key'), description: z.string().optional().describe('Blurb rendered above the tab fields'), - fields: z.array(z.string()).describe('Names of the fields (from FormSchema.fields) this tab renders, in order'), + fields: z.array(z.string(), { + // ADR-0085's Note of 2026-11-27 — the object-level `ObjectSchema.fieldTabs` + // (`@objectstack/spec`) shares this key name and names field GROUPS; an + // entry written in that shape here lacks `fields`, so the refusal names it. + error: (issue) => issue.input === undefined + ? 'A form\'s fieldTabs entry lists the fields it renders in `fields` (field names from FormSchema.fields). ' + + 'Naming field groups in `groups` is the object-level `ObjectSchema.fieldTabs` (the record page\'s field tabs), ' + + 'declared on the object, not on a form.' + : undefined, + }).describe('Names of the fields (from FormSchema.fields) this tab renders, in order'), containerClass: z.string().optional().describe('Field-grid classes for this tab panel'), visibleWhen: ExpressionWireSchema.optional() .describe('Predicate gating the tab: a bare string or the { dialect?, source } envelope; a hidden tab still submits'),